Skip to content

Lenient URI parser #2

@hamnis

Description

@hamnis

This is scala code. We should generalize this and make it as part of the builder.

import java.net.URI

import org.codehaus.httpcache4j.uri.{QueryParams, URIBuilder}
import scalaz.\/

object URIFactory {
  val Extractor = "(http|https)://(\\w+\\.\\w+)(:\\d+)?(/[^\\?#]*)?(\\?.*)?#?(.*)?".r
  def parse(s: String): String \/ URI = {
    \/.fromTryCatch{ URI.create(s) }.orElse(\/.fromTryCatch {
      s match {
        case Extractor(scheme, host, port, path, query, fragment) => {
          URIBuilder.empty().
            withScheme(scheme).
            withHost(host).
            withPort(Option(port).map(_.stripPrefix(":").toInt).getOrElse(-1)).
            withRawPath(path).
            withParameters(QueryParams.parse(Option(query).map(_.stripPrefix("?")).orNull)).
            withFragment(Option(fragment).filterNot(_.isEmpty).orNull).
            toURI
        }
      }
    }).leftMap(_ => s)
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions