Created
August 7, 2019 07:30
-
-
Save bastman/ecb39b7b40003b8c16b0a0d26caa7ce6 to your computer and use it in GitHub Desktop.
BlobStorageUri (kotlin, jackson)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.fasterxml.jackson.annotation.JsonCreator | |
import com.fasterxml.jackson.annotation.JsonValue | |
data class BlobStorageUri( | |
val account: String, | |
val container: String, | |
val key: String | |
) { | |
val uri: String | |
@JsonValue | |
get() = toUriString() | |
companion object { | |
const val scheme = "blobstorage://" | |
@JsonCreator | |
@JvmStatic | |
fun ofUriString(uriString: String): BlobStorageUri { | |
val (account, container, key) = parse(uriString) | |
return BlobStorageUri(account = account, container = container, key = key) | |
} | |
} | |
} | |
fun BlobStorageUri.toUriString(): String { | |
if (key.isNotEmpty()) { | |
return "${BlobStorageUri.scheme}$account/$container/$key" | |
} | |
if (container.isNotEmpty()) { | |
return "${BlobStorageUri.scheme}$account/$container" | |
} | |
if (account.isNotEmpty()) { | |
return "${BlobStorageUri.scheme}$account" | |
} | |
return BlobStorageUri.scheme | |
} | |
private fun parse(uriString: String): Triple<String, String, String> { | |
if (!uriString.startsWith(BlobStorageUri.scheme)) { | |
error("Malformed UriString! BlobStorageUri must start with ${BlobStorageUri.scheme} . given: $uriString") | |
} | |
val withoutPrefix = uriString.removePrefix(BlobStorageUri.scheme) | |
val parts = withoutPrefix.split("/") | |
val account = parts.getOrNull(0) | |
?: return Triple("", "", "") | |
val container = parts.getOrNull(1) | |
?: return Triple(account, "", "") | |
val rest = parts.filterIndexed { index, value -> | |
index > 1 | |
} | |
val key = rest.joinToString(separator = "/") | |
return Triple(account, container, key) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment