def registerCanonical()

in path-manager/app/services/PathStore.scala [60:104]


  def registerCanonical(proposedPathRecord: PathRecord) = {

    val id = proposedPathRecord.identifier

    logger.debug(s"Registering path [${proposedPathRecord.path }] for [$id]")

    if (PathValidator.isInvalid(proposedPathRecord.path)) {
      Left(s"invalid path [${proposedPathRecord.path}]")
    } else {
      val existingPath = Option(Dynamo.pathsTable.getItem("path", proposedPathRecord.path)).map(PathRecord(_))
      val index: Index = Dynamo.pathsTable.getIndex("id-index")

      //noinspection Duplicates
      val canonicalPathsForId = index.query(new KeyAttribute("identifier", id), RangeKeyMatches.rangeKeyMatches("type", CANONICAL_PATH_TYPE)).asScala
      val existingCanonicalPathForId = canonicalPathsForId.map{ PathRecord(_) }.headOption

      existingPath match {
        case Some(pr) if (pr.identifier != id) => {
          logger.warn(s"Failed to register existing path [${proposedPathRecord.path}], already claimed by id [${pr.identifier}], submitting id [$id]")
          Left("path already in use")
        }
        case _ => {
          val shortUrlPathRecord = PathRecord(ShortUrlEncoder.generateShortUrlPath(id), id, "short", proposedPathRecord.system)

          existingCanonicalPathForId match {
            case Some(oldCanonical) => {
              if (oldCanonical.path != proposedPathRecord.path) {
                logger.debug(s"Removing old path for item [$id]. old path[${oldCanonical.path}] new path [${proposedPathRecord.path}]")
                Dynamo.pathsTable.deleteItem("path", oldCanonical.path)
              }
            }
            case None => {
              logger.debug(s"Adding new short url record for [$id]. short path[${shortUrlPathRecord.path}]")
              Dynamo.pathsTable.putItem(shortUrlPathRecord.asDynamoItem)
            }
          }

          putPathItemAndAwaitIndexUpdate(proposedPathRecord)

          logger.debug(s"Registered path [${proposedPathRecord.path}] for id [$id] successfully")
          Right(List(proposedPathRecord, shortUrlPathRecord).groupBy(_.`type`))
        }
      }
    }
  }