Merge branch '0.9.2-dev'

This commit is contained in:
Erik C. Thauvin 2023-01-29 14:58:29 -08:00
commit d2389088ac
31 changed files with 769 additions and 521 deletions

View file

@ -30,19 +30,19 @@ defaults_gradle: &defaults_gradle
path: build/reports/ path: build/reports/
jobs: jobs:
build_gradle_jdk14: build_gradle_jdk18:
<<: *defaults <<: *defaults
docker: docker:
- image: openjdk:14-jdk - image: cimg/openjdk:18.0
<<: *defaults_gradle <<: *defaults_gradle
build_gradle_jdk8: build_gradle_jdk11:
<<: *defaults <<: *defaults
docker: docker:
- image: circleci/openjdk:8-jdk - image: cimg/openjdk:11.0
<<: *defaults_gradle <<: *defaults_gradle
@ -50,5 +50,5 @@ workflows:
version: 2 version: 2
gradle: gradle:
jobs: jobs:
- build_gradle_jdk8 - build_gradle_jdk11
- build_gradle_jdk14 - build_gradle_jdk18

View file

@ -1,19 +1,61 @@
name: Java CI with Gradle name: gradle-ci
on: [push, pull_request, workflow_dispatch] on: [push, pull_request, workflow_dispatch]
jobs: jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
env:
GRADLE_OPTS: "-Dorg.gradle.jvmargs=-XX:MaxMetaspaceSize=512m"
SONAR_JDK: "11"
strategy:
matrix:
java-version: [ 11, 18 ]
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Set up JDK 1.8 with:
fetch-depth: 0
- name: Set up JDK ${{ matrix.java-version }}
uses: actions/setup-java@v1 uses: actions/setup-java@v1
with: with:
java-version: 1.8 java-version: ${{ matrix.java-version }}
- name: Grant execute permission for gradlew - name: Grant execute permission for gradlew
run: chmod +x gradlew run: chmod +x gradlew
- name: Cache SonarCloud packages
if: matrix.java-version == env.SONAR_JDK
uses: actions/cache@v1
with:
path: ~/.sonar/cache
key: ${{ runner.os }}-sonar
restore-keys: ${{ runner.os }}-sonar
- name: Cache Gradle packages
uses: actions/cache@v2
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: ${{ runner.os }}-gradle-${{ matrix.java-version }}-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
${{ runner.os }}-gradle-${{ matrix.java-version }}-
- name: Test with Gradle - name: Test with Gradle
run: ./gradlew check run: ./gradlew build check --stacktrace
- name: SonarCloud
if: success() && matrix.java-version == env.SONAR_JDK
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
run: ./gradlew sonarqube
- name: Cleanup Gradle Cache
run: |
rm -f ~/.gradle/caches/modules-2/modules-2.lock
rm -f ~/.gradle/caches/modules-2/gc.properties

39
.gitignore vendored
View file

@ -1,22 +1,7 @@
.vscode/*
!.vscode/extensions.json !.vscode/extensions.json
!.vscode/launch.json !.vscode/launch.json
!.vscode/settings.json !.vscode/settings.json
!.vscode/tasks.json !.vscode/tasks.json
__pycache__
.classpath
.DS_Store
.gradle
.history
.kobalt
.mtj.tmp/
.mvn/timing.properties
.mvn/wrapper/maven-wrapper.jar
.nb-gradle
.project
.scannerwork
.settings
*.class *.class
*.code-workspace *.code-workspace
*.ctxt *.ctxt
@ -27,7 +12,21 @@ __pycache__
*.sublime-* *.sublime-*
*.tar.gz *.tar.gz
*.zip *.zip
/**/.idea_modules/ .DS_Store
.classpath
.gradle
.history
.kobalt
.mtj.tmp/
.mvn/timing.properties
.mvn/wrapper/maven-wrapper.jar
.nb-gradle
.project
.scannerwork
.settings
.vscode/*
/**/.idea/$CACHE_FILE$
/**/.idea/$PRODUCT_WORKSPACE_FILE$
/**/.idea/**/caches/build_file_checksums.ser /**/.idea/**/caches/build_file_checksums.ser
/**/.idea/**/contentModel.xml /**/.idea/**/contentModel.xml
/**/.idea/**/dataSources.ids /**/.idea/**/dataSources.ids
@ -48,8 +47,10 @@ __pycache__
/**/.idea/**/uiDesigner.xml /**/.idea/**/uiDesigner.xml
/**/.idea/**/usage.statistics.xml /**/.idea/**/usage.statistics.xml
/**/.idea/**/workspace.xml /**/.idea/**/workspace.xml
/**/.idea/$CACHE_FILE$ /**/.idea/sonarlint*
/**/.idea/$PRODUCT_WORKSPACE_FILE$ /**/.idea_modules/
Thumbs.db
__pycache__
atlassian-ide-plugin.xml atlassian-ide-plugin.xml
bin/ bin/
build/ build/
@ -71,6 +72,7 @@ lib/kotlin*
libs/ libs/
local.properties local.properties
out/ out/
pom.xml.asc
pom.xml.next pom.xml.next
pom.xml.releaseBackup pom.xml.releaseBackup
pom.xml.tag pom.xml.tag
@ -80,5 +82,4 @@ project.properties
release.properties release.properties
target/ target/
test-output test-output
Thumbs.db
venv venv

View file

@ -1,4 +1,4 @@
image: gradle:alpine image: gradle:7-jdk11
variables: variables:
GRADLE_OPTS: "-Dorg.gradle.daemon=false" GRADLE_OPTS: "-Dorg.gradle.daemon=false"
@ -12,7 +12,7 @@ stages:
build: build:
stage: build stage: build
script: ./gradlew --build-cache assemble script: gradle --build-cache assemble
cache: cache:
key: "$CI_COMMIT_REF_NAME" key: "$CI_COMMIT_REF_NAME"
policy: push policy: push
@ -22,7 +22,7 @@ build:
test: test:
stage: test stage: test
script: ./gradlew check script: gradle check
cache: cache:
key: "$CI_COMMIT_REF_NAME" key: "$CI_COMMIT_REF_NAME"
policy: pull policy: pull

2
.idea/compiler.xml generated
View file

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="CompilerConfiguration"> <component name="CompilerConfiguration">
<bytecodeTargetLevel target="1.8" /> <bytecodeTargetLevel target="11" />
</component> </component>
</project> </project>

View file

@ -1,6 +1,6 @@
<component name="CopyrightManager"> <component name="CopyrightManager">
<copyright> <copyright>
<option name="notice" value="&amp;#36;file.fileName&#10;&#10;Copyright (c) &amp;#36;today.year, Erik C. Thauvin (erik@thauvin.net)&#10;All rights reserved.&#10;&#10;Redistribution and use in source and binary forms, with or without&#10;modification, are permitted provided that the following conditions are met:&#10;&#10; Redistributions of source code must retain the above copyright notice, this&#10; list of conditions and the following disclaimer.&#10;&#10; Redistributions in binary form must reproduce the above copyright notice,&#10; this list of conditions and the following disclaimer in the documentation&#10; and/or other materials provided with the distribution.&#10;&#10; Neither the name of this project nor the names of its contributors may be&#10; used to endorse or promote products derived from this software without&#10; specific prior written permission.&#10;&#10;THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &quot;AS IS&quot;&#10;AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE&#10;IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE&#10;DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE&#10;FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL&#10;DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR&#10;SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER&#10;CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,&#10;OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE&#10;OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." /> <option name="notice" value="&amp;#36;file.fileName&#10;&#10;Copyright &amp;#36;today.year Erik C. Thauvin (erik@thauvin.net)&#10;&#10;Redistribution and use in source and binary forms, with or without&#10;modification, are permitted provided that the following conditions are met:&#10;&#10; Redistributions of source code must retain the above copyright notice, this&#10; list of conditions and the following disclaimer.&#10;&#10; Redistributions in binary form must reproduce the above copyright notice,&#10; this list of conditions and the following disclaimer in the documentation&#10; and/or other materials provided with the distribution.&#10;&#10; Neither the name of this project nor the names of its contributors may be&#10; used to endorse or promote products derived from this software without&#10; specific prior written permission.&#10;&#10;THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &quot;AS IS&quot;&#10;AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE&#10;IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE&#10;DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE&#10;FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL&#10;DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR&#10;SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER&#10;CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,&#10;OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE&#10;OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." />
<option name="myName" value="Erik's Copyright Notice" /> <option name="myName" value="Erik's Copyright Notice" />
</copyright> </copyright>
</component> </component>

View file

@ -1,2 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4" />

View file

@ -26,5 +26,20 @@
<option name="name" value="MavenLocal" /> <option name="name" value="MavenLocal" />
<option name="url" value="file:$MAVEN_REPOSITORY$/" /> <option name="url" value="file:$MAVEN_REPOSITORY$/" />
</remote-repository> </remote-repository>
<remote-repository>
<option name="id" value="MavenRepo" />
<option name="name" value="MavenRepo" />
<option name="url" value="https://repo.maven.apache.org/maven2/" />
</remote-repository>
<remote-repository>
<option name="id" value="maven" />
<option name="name" value="maven" />
<option name="url" value="https://oss.sonatype.org/content/repositories/snapshots" />
</remote-repository>
<remote-repository>
<option name="id" value="maven" />
<option name="name" value="maven" />
<option name="url" value="https://packages.jetbrains.team/maven/p/ij/intellij-dependencies" />
</remote-repository>
</component> </component>
</project> </project>

6
.idea/kotlinc.xml generated Normal file
View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="KotlinJpsPluginSettings">
<option name="version" value="1.8.0" />
</component>
</project>

5
.idea/misc.xml generated
View file

@ -4,7 +4,10 @@
<component name="FrameworkDetectionExcludesConfiguration"> <component name="FrameworkDetectionExcludesConfiguration">
<file type="web" url="file://$PROJECT_DIR$" /> <file type="web" url="file://$PROJECT_DIR$" />
</component> </component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK"> <component name="PDMPlugin">
<option name="skipTestSources" value="false" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" project-jdk-name="18" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" /> <output url="file://$PROJECT_DIR$/build/classes" />
</component> </component>
<component name="ProjectType"> <component name="ProjectType">

View file

@ -1,26 +0,0 @@
language: java
dist: trusty
env:
global:
- CI=true
#install:
# - git fetch --unshallow --tags
addons:
sonarcloud:
organization: "ethauvin-github"
jdk:
- oraclejdk8
- openjdk14
before_install:
- chmod +x gradlew
after_success:
- |
if [ "${TRAVIS_TEST_RESULT}" == 0 ] && [ "$TRAVIS_JDK_VERSION" == "openjdk14" ]; then
./gradlew sonarqube
fi

View file

@ -1,5 +1,4 @@
Copyright (c) 2020, Erik C. Thauvin (erik@thauvin.net) Copyright 2020-2023 Erik C. Thauvin (erik@thauvin.net)
All rights reserved.
Redistribution and use in source and binary forms, with or without Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met: modification, are permitted provided that the following conditions are met:

View file

@ -1,10 +1,16 @@
[![License (3-Clause BSD)](https://img.shields.io/badge/license-BSD%203--Clause-blue.svg?style=flat-square)](http://opensource.org/licenses/BSD-3-Clause) [![release](https://img.shields.io/github/release/ethauvin/isgd-shorten.svg)](https://github.com/ethauvin/isgd-shorten/releases/latest) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/net.thauvin.erik/isgd-shorten/badge.svg)](https://maven-badges.herokuapp.com/maven-central/net.thauvin.erik/isgd-shorten) [![Download](https://api.bintray.com/packages/ethauvin/maven/isgd-shorten/images/download.svg)](https://bintray.com/ethauvin/maven/isgd-shorten/_latestVersion) [![License (3-Clause BSD)](https://img.shields.io/badge/license-BSD%203--Clause-blue.svg?style=flat-square)](https://opensource.org/licenses/BSD-3-Clause)
[![Kotlin](https://img.shields.io/badge/kotlin-1.8.0-blue)](https://kotlinlang.org/)
[![Nexus Snapshot](https://img.shields.io/nexus/s/net.thauvin.erik/isgd-shorten?label=snapshot&server=https%3A%2F%2Foss.sonatype.org%2F)](https://oss.sonatype.org/content/repositories/snapshots/net/thauvin/erik/isgd-shorten/)
[![release](https://img.shields.io/github/release/ethauvin/isgd-shorten.svg)](https://github.com/ethauvin/isgd-shorten/releases/latest)
[![Maven Central](https://maven-badges.herokuapp.com/maven-central/net.thauvin.erik/isgd-shorten/badge.svg)](https://maven-badges.herokuapp.com/maven-central/net.thauvin.erik/isgd-shorten)
[![Known Vulnerabilities](https://snyk.io/test/github/ethauvin/isgd-shorten/badge.svg?targetFile=pom.xml)](https://snyk.io/test/github/ethauvin/isgd-shorten?targetFile=pom.xml) [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=ethauvin_isgd-shorten&metric=alert_status)](https://sonarcloud.io/dashboard?id=ethauvin_isgd-shorten) [![Build Status](https://travis-ci.com/ethauvin/isgd-shorten.svg?branch=master)](https://travis-ci.com/ethauvin/isgd-shorten) [![CircleCI](https://circleci.com/gh/ethauvin/isgd-shorten/tree/master.svg?style=shield)](https://circleci.com/gh/ethauvin/isgd-shorten/tree/master) [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=ethauvin_isgd-shorten&metric=alert_status)](https://sonarcloud.io/dashboard?id=ethauvin_isgd-shorten)
[![GitHub CI](https://github.com/ethauvin/isgd-shorten/actions/workflows/gradle.yml/badge.svg)](https://github.com/ethauvin/isgd-shorten/actions/workflows/gradle.yml)
[![CircleCI](https://circleci.com/gh/ethauvin/isgd-shorten/tree/master.svg?style=shield)](https://circleci.com/gh/ethauvin/isgd-shorten/tree/master)
# [is.gd](https://is.gd/developers.php) Shortener for Kotlin/Java/Android # [is.gd](https://is.gd/developers.php) Shortener for Kotlin, Java & Android
A simple implementation of the [is.gd API](https://is.gd/developers.php). A simple implementation of the [is.gd](https://is.gd/) URL shortening and lookup [APIs](https://is.gd/developers.php).
## Examples (TL;DR) ## Examples (TL;DR)
@ -44,7 +50,7 @@ Isgd.shorten(url = url, shorturl="foobar", callback = "test", logstats = true, f
``` ```
returns: returns:
```json ```js
test({ "shorturl": "https://is.gd/foobar" }); test({ "shorturl": "https://is.gd/foobar" });
``` ```
### Gradle ### Gradle
@ -53,14 +59,33 @@ To use with [Gradle](https://gradle.org/), include the following dependency in y
```gradle ```gradle
repositories { repositories {
jcenter() mavenCentral()
maven { url = uri("https://oss.sonatype.org/content/repositories/snapshots") } // only needed for SNAPSHOT
} }
dependencies { dependencies {
implementation("net.thauvin.erik:isgd-shorten:0.9.1") implementation("net.thauvin.erik:isgd-shorten:0.9.2")
} }
``` ```
Instructions for using with Maven, Ivy, etc. can be found on [Maven Central](https://search.maven.org/artifact/net.thauvin.erik/isgd-shorten/0.9.1/jar). Instructions for using with Maven, Ivy, etc. can be found on [Maven Central](https://maven-badges.herokuapp.com/maven-central/net.thauvin.erik/isgd-shorten).
### Errors
An `IsgdException` is thrown when an API error occurs. The error message (text, XML or JSON) and HTTP status code can be retrieved as follows:
```kotlin
try {
Isgd.shorten("https://is.gd/Pt2sET") // already shorten
} catch (e: IsgdException)
println("Status Code: ${e.statusCode}")
println("${e.message})
}
```
```
Status Code: 400
Error: Sorry, the URL you entered is on our internal blacklist. It may have been used abusively in the past, or it may link to another URL redirection service.
```
### v.gd ### v.gd

View file

@ -1,4 +1,4 @@
image: openjdk:8 image: maven:3-openjdk-18
pipelines: pipelines:
default: default:

View file

@ -1,24 +1,24 @@
import com.jfrog.bintray.gradle.tasks.BintrayUploadTask
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import java.io.FileInputStream import org.gradle.api.tasks.testing.logging.TestExceptionFormat
import java.util.* import org.gradle.api.tasks.testing.logging.TestLogEvent
plugins { plugins {
jacoco id("com.github.ben-manes.versions") version "0.44.0"
`java-library` id("io.gitlab.arturbosch.detekt") version "1.22.0"
`maven-publish` id("java")
id("com.github.ben-manes.versions") version "0.29.0" id("java-library")
id("com.jfrog.bintray") version "1.8.5" id("maven-publish")
id("io.gitlab.arturbosch.detekt") version "1.11.0"
id("net.thauvin.erik.gradle.semver") version "1.0.4" id("net.thauvin.erik.gradle.semver") version "1.0.4"
id("org.jetbrains.dokka") version "1.4.0-rc" id("org.jetbrains.dokka") version "1.7.20"
id("org.jetbrains.kotlin.jvm") version "1.4.0" id("org.jetbrains.kotlinx.kover") version "0.6.1"
id("org.jetbrains.kotlin.kapt") version "1.4.0" id("org.sonarqube") version "3.5.0.2730"
id("org.sonarqube") version "3.0" id("signing")
kotlin("jvm") version "1.8.0"
kotlin("kapt") version "1.8.0"
} }
group = "net.thauvin.erik" group = "net.thauvin.erik"
description = "is.gd Shortener for Kotlin/Java" description = "A simple implementation of the is.gd URL shortening and lookup APIs"
val gitHub = "ethauvin/$name" val gitHub = "ethauvin/$name"
val mavenUrl = "https://github.com/$gitHub" val mavenUrl = "https://github.com/$gitHub"
@ -27,62 +27,41 @@ var isRelease = "release" in gradle.startParameter.taskNames
val publicationName = "mavenJava" val publicationName = "mavenJava"
var semverProcessor = "net.thauvin.erik:semver:1.2.0"
// Load local.properties
File("local.properties").apply {
if (exists()) {
FileInputStream(this).use { fis ->
Properties().apply {
load(fis)
forEach { (k, v) ->
extra[k as String] = v
}
}
}
}
}
repositories { repositories {
jcenter() mavenCentral()
maven { url = uri("https://oss.sonatype.org/content/repositories/snapshots") }
} }
dependencies { dependencies {
testImplementation("org.jetbrains.kotlin:kotlin-test") implementation(platform(kotlin("bom")))
testImplementation("org.jetbrains.kotlin:kotlin-test-junit") implementation("net.thauvin.erik:urlencoder:1.3.0")
}
kapt { testImplementation(kotlin("test"))
arguments { testImplementation(kotlin("test-junit"))
arg("semver.project.dir", projectDir) testImplementation("com.willowtreeapps.assertk:assertk-jvm:0.25")
}
} }
java { java {
sourceCompatibility = JavaVersion.VERSION_1_8 sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_11
withSourcesJar()
} }
detekt { detekt {
//toolVersion = "main-SNAPSHOT"
baseline = project.rootDir.resolve("config/detekt/baseline.xml") baseline = project.rootDir.resolve("config/detekt/baseline.xml")
} }
jacoco {
toolVersion = "0.8.5"
}
sonarqube { sonarqube {
properties { properties {
property("sonar.projectKey", "ethauvin_$name") property("sonar.projectKey", "ethauvin_$name")
property("sonar.organization", "ethauvin-github")
property("sonar.host.url", "https://sonarcloud.io")
property("sonar.sourceEncoding", "UTF-8") property("sonar.sourceEncoding", "UTF-8")
property("sonar.coverage.jacoco.xmlReportPaths", "${project.buildDir}/reports/kover/xml/report.xml")
} }
} }
val sourcesJar by tasks.creating(Jar::class) {
archiveClassifier.set("sources")
from(sourceSets.getByName("main").allSource)
}
val javadocJar by tasks.creating(Jar::class) { val javadocJar by tasks.creating(Jar::class) {
dependsOn(tasks.dokkaJavadoc) dependsOn(tasks.dokkaJavadoc)
from(tasks.dokkaJavadoc) from(tasks.dokkaJavadoc)
@ -92,15 +71,15 @@ val javadocJar by tasks.creating(Jar::class) {
} }
tasks { tasks {
withType<JacocoReport> { withType<KotlinCompile>().configureEach {
reports { kotlinOptions.jvmTarget = java.targetCompatibility.toString()
xml.isEnabled = true
html.isEnabled = true
}
} }
withType<KotlinCompile>().configureEach { withType<Test> {
kotlinOptions.jvmTarget = "1.8" testLogging {
exceptionFormat = TestExceptionFormat.FULL
events = setOf(TestLogEvent.PASSED, TestLogEvent.SKIPPED, TestLogEvent.FAILED)
}
} }
withType<GenerateMavenPom> { withType<GenerateMavenPom> {
@ -108,7 +87,7 @@ tasks {
} }
assemble { assemble {
dependsOn(sourcesJar, javadocJar) dependsOn(javadocJar)
} }
clean { clean {
@ -140,75 +119,23 @@ tasks {
} }
} }
val bintrayUpload by existing(BintrayUploadTask::class) {
dependsOn(publishToMavenLocal, gitTag)
doFirst {
versionName = "${project.version}"
versionDesc = "${project.name} ${project.version}"
versionVcsTag = "${project.version}"
versionReleased = Date().toString()
}
}
register("deploy") { register("deploy") {
description = "Copies all needed files to the $deployDir directory." description = "Copies all needed files to the $deployDir directory."
group = PublishingPlugin.PUBLISH_TASK_GROUP group = PublishingPlugin.PUBLISH_TASK_GROUP
dependsOn("build", "jar") dependsOn(clean, wrapper, build, jar)
outputs.dir(deployDir) outputs.dir(deployDir)
inputs.files(copyToDeploy) inputs.files(copyToDeploy)
mustRunAfter("clean") mustRunAfter(clean)
} }
register("release") { register("release") {
description = "Publishes version ${project.version} to Bintray." description = "Publishes version ${project.version} to local repository."
group = PublishingPlugin.PUBLISH_TASK_GROUP group = PublishingPlugin.PUBLISH_TASK_GROUP
dependsOn("wrapper", bintrayUpload) dependsOn(wrapper, "deploy", gitTag, publishToMavenLocal)
} }
"sonarqube" { "sonarqube" {
dependsOn("jacocoTestReport") dependsOn(koverReport)
}
}
fun findProperty(s: String) = project.findProperty(s) as String?
bintray {
user = findProperty("bintray.user")
key = findProperty("bintray.apikey")
publish = isRelease
setPublications(publicationName)
pkg.apply {
repo = "maven"
name = project.name
desc = description
websiteUrl = mavenUrl
issueTrackerUrl = "$mavenUrl/issues"
githubRepo = gitHub
githubReleaseNotesFile = "README.md"
vcsUrl = "$mavenUrl.git"
setLabels(
"android",
"is.gd",
"v.gd",
"java",
"kotlin",
"shorten",
"shorten-urls",
"shortener",
"shortener-service",
"shortens-links",
"shorturl",
"url-shortener"
)
setLicenses("BSD 3-Clause")
publicDownloadNumbers = true
version.apply {
name = project.version as String
desc = description
vcsTag = project.version as String
gpg.apply {
sign = true
}
}
} }
} }
@ -216,37 +143,51 @@ publishing {
publications { publications {
create<MavenPublication>(publicationName) { create<MavenPublication>(publicationName) {
from(components["java"]) from(components["java"])
artifact(sourcesJar)
artifact(javadocJar) artifact(javadocJar)
pom.withXml { pom {
asNode().apply { name.set(project.name)
appendNode("name", project.name) description.set(project.description)
appendNode("description", project.description) url.set(mavenUrl)
appendNode("url", mavenUrl) licenses {
license {
appendNode("licenses").appendNode("license").apply { name.set("BSD 3-Clause")
appendNode("name", "BSD 3-Clause") url.set("https://opensource.org/licenses/BSD-3-Clause")
appendNode("url", "https://opensource.org/licenses/BSD-3-Clause")
} }
appendNode("developers").appendNode("developer").apply {
appendNode("id", "ethauvin")
appendNode("name", "Erik C. Thauvin")
appendNode("email", "erik@thauvin.net")
} }
developers {
appendNode("scm").apply { developer {
appendNode("connection", "scm:git:$mavenUrl.git") id.set("ethauvin")
appendNode("developerConnection", "scm:git:git@github.com:$gitHub.git") name.set("Erik C. Thauvin")
appendNode("url", mavenUrl) email.set("erik@thauvin.net")
url.set("https://erik.thauvin.net/")
} }
}
appendNode("issueManagement").apply { scm {
appendNode("system", "GitHub") connection.set("scm:git://github.com/$gitHub.git")
appendNode("url", "$mavenUrl/issues") developerConnection.set("scm:git@github.com:$gitHub.git")
url.set(mavenUrl)
}
issueManagement {
system.set("GitHub")
url.set("$mavenUrl/issues")
} }
} }
} }
} }
repositories {
maven {
name = "ossrh"
project.afterEvaluate {
url = if (project.version.toString().contains("SNAPSHOT"))
uri("https://oss.sonatype.org/content/repositories/snapshots/") else
uri("https://oss.sonatype.org/service/local/staging/deploy/maven2/")
}
credentials(PasswordCredentials::class)
}
} }
} }
signing {
useGpgCmd()
sign(publishing.publications[publicationName])
}

View file

@ -1,7 +1,9 @@
<?xml version="1.0" ?> <?xml version='1.0' encoding='UTF-8'?>
<SmellBaseline> <SmellBaseline>
<Blacklist></Blacklist> <ManuallySuppressedIssues/>
<Whitelist> <CurrentIssues>
<ID>LongParameterList:Isgd.kt$Isgd.Companion$( url: String, shorturl: String = "", callback: String = "", logstats: Boolean = false, format: Format = Format.SIMPLE, isVgd: Boolean = false )</ID> <ID>LongParameterList:Isgd.kt$Isgd.Companion$( url: String, shorturl: String = "", callback: String = "", logstats: Boolean = false, format: Format = Format.SIMPLE, isVgd: Boolean = false )</ID>
</Whitelist> <ID>MagicNumber:Isgd.kt$Isgd.Companion$200</ID>
<ID>MagicNumber:Isgd.kt$Isgd.Companion$399</ID>
</CurrentIssues>
</SmellBaseline> </SmellBaseline>

View file

@ -1,29 +1,41 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins { plugins {
id("org.jetbrains.kotlin.jvm") version "1.4.0" id("application")
id("com.github.ben-manes.versions") version "0.29.0" id("com.github.ben-manes.versions") version "0.44.0"
application kotlin("jvm") version "1.8.0"
} }
// ./gradlew run --args='https://wwwcom.example. https://is.gd/Pt2sET' // ./gradlew run --args='https://www.example.com https://is.gd/Pt2sET'
// ./gradlew runJava --args='https://www.example.com https://is.gd/Pt2sET' // ./gradlew runJava --args='https://www.example.com https://is.gd/Pt2sET'
repositories { repositories {
mavenLocal() mavenLocal()
jcenter() mavenCentral()
maven { url = uri("https://oss.sonatype.org/content/repositories/snapshots") } // only needed for SNAPSHOT
} }
dependencies { dependencies {
implementation("net.thauvin.erik:isgd-shorten:0.9.1") implementation("net.thauvin.erik:isgd-shorten:0.9.2-SNAPSHOT")
}
java {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
} }
application { application {
mainClassName = "com.example.IsgdExampleKt" mainClass.set("com.example.IsgdExampleKt")
} }
tasks { tasks {
withType<KotlinCompile>().configureEach {
kotlinOptions.jvmTarget = java.targetCompatibility.toString()
}
register("runJava", JavaExec::class) { register("runJava", JavaExec::class) {
group = "application" group = "application"
main = "com.example.IsgdSample" mainClass.set("com.example.IsgdSample")
classpath = sourceSets["main"].runtimeClasspath classpath = sourceSets.main.get().runtimeClasspath
} }
} }

Binary file not shown.

View file

@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.6-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists

269
examples/gradlew vendored Normal file → Executable file
View file

@ -1,7 +1,7 @@
#!/usr/bin/env sh #!/bin/sh
# #
# Copyright 2015 the original author or authors. # Copyright © 2015-2021 the original authors.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@ -17,67 +17,101 @@
# #
############################################################################## ##############################################################################
## #
## Gradle start up script for UN*X # Gradle start up script for POSIX generated by Gradle.
## #
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
############################################################################## ##############################################################################
# Attempt to set APP_HOME # Attempt to set APP_HOME
# Resolve links: $0 may be a link # Resolve links: $0 may be a link
PRG="$0" app_path=$0
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do # Need this for daisy-chained symlinks.
ls=`ls -ld "$PRG"` while
link=`expr "$ls" : '.*-> \(.*\)$'` APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
if expr "$link" : '/.*' > /dev/null; then [ -h "$app_path" ]
PRG="$link" do
else ls=$( ls -ld "$app_path" )
PRG=`dirname "$PRG"`"/$link" link=${ls#*' -> '}
fi case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle" APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"` APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum" MAX_FD=maximum
warn () { warn () {
echo "$*" echo "$*"
} } >&2
die () { die () {
echo echo
echo "$*" echo "$*"
echo echo
exit 1 exit 1
} } >&2
# OS specific support (must be 'true' or 'false'). # OS specific support (must be 'true' or 'false').
cygwin=false cygwin=false
msys=false msys=false
darwin=false darwin=false
nonstop=false nonstop=false
case "`uname`" in case "$( uname )" in #(
CYGWIN* ) CYGWIN* ) cygwin=true ;; #(
cygwin=true Darwin* ) darwin=true ;; #(
;; MSYS* | MINGW* ) msys=true ;; #(
Darwin* ) NONSTOP* ) nonstop=true ;;
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
@ -87,9 +121,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
if [ -n "$JAVA_HOME" ] ; then if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables # IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java" JAVACMD=$JAVA_HOME/jre/sh/java
else else
JAVACMD="$JAVA_HOME/bin/java" JAVACMD=$JAVA_HOME/bin/java
fi fi
if [ ! -x "$JAVACMD" ] ; then if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@ -98,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi fi
else else
JAVACMD="java" JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the Please set the JAVA_HOME variable in your environment to match the
@ -106,80 +140,95 @@ location of your Java installation."
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
MAX_FD_LIMIT=`ulimit -H -n` case $MAX_FD in #(
if [ $? -eq 0 ] ; then max*)
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD=$( ulimit -H -n ) ||
MAX_FD="$MAX_FD_LIMIT" warn "Could not query maximum file descriptor limit"
fi esac
ulimit -n $MAX_FD case $MAX_FD in #(
if [ $? -ne 0 ] ; then '' | soft) :;; #(
warn "Could not set maximum file descriptor limit: $MAX_FD" *)
fi ulimit -n "$MAX_FD" ||
else warn "Could not set maximum file descriptor limit to $MAX_FD"
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac esac
fi fi
# Escape application args # Collect all arguments for the java command, stacking in reverse order:
save () { # * args from the command line
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done # * the main class name
echo " " # * -classpath
} # * -D...appname settings
APP_ARGS=`save "$@"` # * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# Collect all arguments for the java command, following the shell quoting and substitution rules # For Cygwin or MSYS, switch paths to Windows format before running java
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@" exec "$JAVACMD" "$@"

View file

@ -1,16 +1,21 @@
package com.example; package com.example;
import net.thauvin.erik.isgd.Isgd; import net.thauvin.erik.isgd.Isgd;
import net.thauvin.erik.isgd.IsgdException;
public final class IsgdSample { public final class IsgdSample {
public static void main(final String[] args) { public static void main(final String[] args) {
if (args.length > 0) { if (args.length > 0) {
for (final String arg : args) { for (final String arg : args) {
try {
if (arg.contains("is.gd")) { if (arg.contains("is.gd")) {
System.out.println(arg + " <-- " + Isgd.lookup(arg)); System.out.println(arg + " <-- " + Isgd.lookup(arg));
} else { } else {
System.out.println(arg + " --> " + Isgd.shorten(arg)); System.out.println(arg + " --> " + Isgd.shorten(arg));
} }
} catch (IsgdException e) {
System.out.println(e.getMessage());
}
} }
} else { } else {
System.err.println("Try specifying one or more URLs as arguments."); System.err.println("Try specifying one or more URLs as arguments.");

View file

@ -1,15 +1,20 @@
package com.example package com.example
import net.thauvin.erik.isgd.Isgd import net.thauvin.erik.isgd.Isgd
import net.thauvin.erik.isgd.IsgdException
import kotlin.system.exitProcess import kotlin.system.exitProcess
fun main(args: Array<String>) { fun main(args: Array<String>) {
if (args.isNotEmpty()) { if (args.isNotEmpty()) {
args.forEach { args.forEach {
try {
if (it.contains("is.gd")) if (it.contains("is.gd"))
println(it + " <-- " + Isgd.lookup(it)) println(it + " <-- " + Isgd.lookup(it))
else else
println(it + " --> " + Isgd.shorten(it)) println(it + " --> " + Isgd.shorten(it))
} catch (e: IsgdException) {
println(e.message)
}
} }
} else { } else {
println("Try specifying one or more URLs as arguments.") println("Try specifying one or more URLs as arguments.")

Binary file not shown.

View file

@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.6-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists

269
gradlew vendored
View file

@ -1,7 +1,7 @@
#!/usr/bin/env sh #!/bin/sh
# #
# Copyright 2015 the original author or authors. # Copyright © 2015-2021 the original authors.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@ -17,67 +17,101 @@
# #
############################################################################## ##############################################################################
## #
## Gradle start up script for UN*X # Gradle start up script for POSIX generated by Gradle.
## #
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
############################################################################## ##############################################################################
# Attempt to set APP_HOME # Attempt to set APP_HOME
# Resolve links: $0 may be a link # Resolve links: $0 may be a link
PRG="$0" app_path=$0
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do # Need this for daisy-chained symlinks.
ls=`ls -ld "$PRG"` while
link=`expr "$ls" : '.*-> \(.*\)$'` APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
if expr "$link" : '/.*' > /dev/null; then [ -h "$app_path" ]
PRG="$link" do
else ls=$( ls -ld "$app_path" )
PRG=`dirname "$PRG"`"/$link" link=${ls#*' -> '}
fi case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle" APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"` APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum" MAX_FD=maximum
warn () { warn () {
echo "$*" echo "$*"
} } >&2
die () { die () {
echo echo
echo "$*" echo "$*"
echo echo
exit 1 exit 1
} } >&2
# OS specific support (must be 'true' or 'false'). # OS specific support (must be 'true' or 'false').
cygwin=false cygwin=false
msys=false msys=false
darwin=false darwin=false
nonstop=false nonstop=false
case "`uname`" in case "$( uname )" in #(
CYGWIN* ) CYGWIN* ) cygwin=true ;; #(
cygwin=true Darwin* ) darwin=true ;; #(
;; MSYS* | MINGW* ) msys=true ;; #(
Darwin* ) NONSTOP* ) nonstop=true ;;
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
@ -87,9 +121,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
if [ -n "$JAVA_HOME" ] ; then if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables # IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java" JAVACMD=$JAVA_HOME/jre/sh/java
else else
JAVACMD="$JAVA_HOME/bin/java" JAVACMD=$JAVA_HOME/bin/java
fi fi
if [ ! -x "$JAVACMD" ] ; then if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@ -98,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi fi
else else
JAVACMD="java" JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the Please set the JAVA_HOME variable in your environment to match the
@ -106,80 +140,95 @@ location of your Java installation."
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
MAX_FD_LIMIT=`ulimit -H -n` case $MAX_FD in #(
if [ $? -eq 0 ] ; then max*)
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD=$( ulimit -H -n ) ||
MAX_FD="$MAX_FD_LIMIT" warn "Could not query maximum file descriptor limit"
fi esac
ulimit -n $MAX_FD case $MAX_FD in #(
if [ $? -ne 0 ] ; then '' | soft) :;; #(
warn "Could not set maximum file descriptor limit: $MAX_FD" *)
fi ulimit -n "$MAX_FD" ||
else warn "Could not set maximum file descriptor limit to $MAX_FD"
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac esac
fi fi
# Escape application args # Collect all arguments for the java command, stacking in reverse order:
save () { # * args from the command line
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done # * the main class name
echo " " # * -classpath
} # * -D...appname settings
APP_ARGS=`save "$@"` # * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# Collect all arguments for the java command, following the shell quoting and substitution rules # For Cygwin or MSYS, switch paths to Windows format before running java
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@" exec "$JAVACMD" "$@"

55
pom.xml
View file

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!-- This module was also published with a richer model, Gradle metadata, --> <!-- This module was also published with a richer model, Gradle metadata, -->
<!-- which should be used instead. Do not delete the following line which --> <!-- which should be used instead. Do not delete the following line which -->
<!-- is to indicate to Gradle or any Gradle module metadata file consumer --> <!-- is to indicate to Gradle or any Gradle module metadata file consumer -->
@ -8,28 +8,9 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>net.thauvin.erik</groupId> <groupId>net.thauvin.erik</groupId>
<artifactId>isgd-shorten</artifactId> <artifactId>isgd-shorten</artifactId>
<version>0.9.1</version> <version>0.9.2-SNAPSHOT</version>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-bom</artifactId>
<version>1.3.72</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
<version>1.3.72</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<name>isgd-shorten</name> <name>isgd-shorten</name>
<description>is.gd Shortener for Kotlin/Java</description> <description>A simple implementation of the is.gd URL shortening and lookup APIs</description>
<url>https://github.com/ethauvin/isgd-shorten</url> <url>https://github.com/ethauvin/isgd-shorten</url>
<licenses> <licenses>
<license> <license>
@ -42,15 +23,41 @@
<id>ethauvin</id> <id>ethauvin</id>
<name>Erik C. Thauvin</name> <name>Erik C. Thauvin</name>
<email>erik@thauvin.net</email> <email>erik@thauvin.net</email>
<url>https://erik.thauvin.net/</url>
</developer> </developer>
</developers> </developers>
<scm> <scm>
<connection>scm:git:https://github.com/ethauvin/isgd-shorten.git</connection> <connection>scm:git://github.com/ethauvin/isgd-shorten.git</connection>
<developerConnection>scm:git:git@github.com:ethauvin/isgd-shorten.git</developerConnection> <developerConnection>scm:git@github.com:ethauvin/isgd-shorten.git</developerConnection>
<url>https://github.com/ethauvin/isgd-shorten</url> <url>https://github.com/ethauvin/isgd-shorten</url>
</scm> </scm>
<issueManagement> <issueManagement>
<system>GitHub</system> <system>GitHub</system>
<url>https://github.com/ethauvin/isgd-shorten/issues</url> <url>https://github.com/ethauvin/isgd-shorten/issues</url>
</issueManagement> </issueManagement>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-bom</artifactId>
<version>1.8.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
<version>1.8.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.thauvin.erik</groupId>
<artifactId>urlencoder</artifactId>
<version>1.3.0</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</project> </project>

View file

@ -1 +1,18 @@
plugins {
id("com.gradle.enterprise").version("3.6.3")
}
gradleEnterprise {
buildScan {
link("GitHub", "https://github.com/ethauvin/isgd-shorten/tree/master")
if (!System.getenv("CI").isNullOrEmpty()) {
isUploadInBackground = false
publishOnFailure()
tag("CI")
}
termsOfServiceUrl = "https://gradle.com/terms-of-service"
termsOfServiceAgree = "yes"
}
}
rootProject.name = "isgd-shorten" rootProject.name = "isgd-shorten"

View file

@ -1,8 +1,7 @@
/* /*
* Isgd.kt * Isgd.kt
* *
* Copyright (c) 2020, Erik C. Thauvin (erik@thauvin.net) * Copyright 2023 Erik C. Thauvin (erik@thauvin.net)
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
@ -32,34 +31,38 @@
package net.thauvin.erik.isgd package net.thauvin.erik.isgd
import net.thauvin.erik.urlencoder.UrlEncoder
import java.net.HttpURLConnection import java.net.HttpURLConnection
import java.net.URL import java.net.URL
import java.net.URLEncoder
import java.nio.charset.StandardCharsets
/** /**
* See the [is.gd API](https://is.gd/apishorteningreference.php) * See the [is.gd API](https://is.gd/apishorteningreference.php).
*/ */
enum class Format(val type: String) { enum class Format(val type: String) {
WEB("web"), SIMPLE("simple"), XML("xml"), JSON("json") WEB("web"), SIMPLE("simple"), XML("xml"), JSON("json")
} }
fun String.encode(): String { fun String.encode(): String = UrlEncoder.encode(this)
return URLEncoder.encode(this, StandardCharsets.UTF_8.name())
}
/**
* Implements the [is.gd API](https://is.gd/developers.php).
*/
class Isgd private constructor() { class Isgd private constructor() {
companion object { companion object {
private fun callApi(url: String): String { private fun callApi(url: String): String {
val connection = URL(url).openConnection() as HttpURLConnection val connection = URL(url).openConnection() as HttpURLConnection
connection.setRequestProperty( connection.setRequestProperty(
"User-Agent", "User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0" "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/109.0"
) )
if (connection.responseCode in 200..399) {
return connection.inputStream.bufferedReader().readText() return connection.inputStream.bufferedReader().readText()
} else {
throw IsgdException(connection.responseCode, connection.errorStream.bufferedReader().readText())
}
} }
private fun host(isVgd: Boolean = false): String { private fun getHost(isVgd: Boolean = false): String {
return if (isVgd) "v.gd" else "is.gd" return if (isVgd) "v.gd" else "is.gd"
} }
@ -68,17 +71,16 @@ class Isgd private constructor() {
*/ */
@JvmStatic @JvmStatic
@JvmOverloads @JvmOverloads
@Throws(IsgdException::class)
fun lookup( fun lookup(
shorturl: String, shorturl: String,
callback: String = "", callback: String = "",
format: Format = Format.SIMPLE, format: Format = Format.SIMPLE,
isVgd: Boolean = false isVgd: Boolean = false
): String { ): String {
if (shorturl.isEmpty()) { require(shorturl.isNotEmpty()) { "Please specify a valid short URL to lookup." }
throw IllegalArgumentException("Please specify a valid short URL to lookup.")
}
val sb = StringBuilder("https://${host(isVgd)}/forward.php?shorturl=${shorturl.encode()}") val sb = StringBuilder("https://${getHost(isVgd)}/forward.php?shorturl=${shorturl.encode()}")
if (callback.isNotEmpty()) { if (callback.isNotEmpty()) {
sb.append("&callback=${callback.encode()}") sb.append("&callback=${callback.encode()}")
@ -94,6 +96,7 @@ class Isgd private constructor() {
*/ */
@JvmStatic @JvmStatic
@JvmOverloads @JvmOverloads
@Throws(IsgdException::class)
fun shorten( fun shorten(
url: String, url: String,
shorturl: String = "", shorturl: String = "",
@ -102,11 +105,9 @@ class Isgd private constructor() {
format: Format = Format.SIMPLE, format: Format = Format.SIMPLE,
isVgd: Boolean = false isVgd: Boolean = false
): String { ): String {
if (url.isEmpty()) { require(url.isNotEmpty()) { "Please enter a valid URL to shorten." }
throw IllegalArgumentException("Please enter a valid URL to shorten.")
}
val sb = StringBuilder("https://${host(isVgd)}/create.php?url=${url.encode()}") val sb = StringBuilder("https://${getHost(isVgd)}/create.php?url=${url.encode()}")
if (shorturl.isNotEmpty()) { if (shorturl.isNotEmpty()) {
sb.append("&shorturl=${shorturl.encode()}") sb.append("&shorturl=${shorturl.encode()}")

View file

@ -0,0 +1,44 @@
/*
* IsgdException.kt
*
* Copyright 2023 Erik C. Thauvin (erik@thauvin.net)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of this project nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.thauvin.erik.isgd
/**
* Thrown when an exceptional condition has occurred.
*
* @property statusCode The HTTP status code.
* @property message The error message.
*/
class IsgdException(val statusCode: Int, message: String) : Exception(message) {
companion object {
private const val serialVersionUID = 1L
}
}

View file

@ -1,8 +1,7 @@
/* /*
* IsgdTest.kt * IsgdTest.kt
* *
* Copyright (c) 2020, Erik C. Thauvin (erik@thauvin.net) * Copyright 2023 Erik C. Thauvin (erik@thauvin.net)
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
@ -32,19 +31,54 @@
package net.thauvin.erik.isgd package net.thauvin.erik.isgd
import assertk.all
import assertk.assertThat
import assertk.assertions.contains
import assertk.assertions.isEqualTo
import assertk.assertions.isNotNull
import assertk.assertions.matches
import assertk.assertions.prop
import assertk.assertions.startsWith
import kotlin.test.Test import kotlin.test.Test
import kotlin.test.assertEquals import kotlin.test.assertEquals
import kotlin.test.assertTrue import kotlin.test.assertFailsWith
class IsgdTest { class IsgdTest {
private val url = "https://www.example.com" private val url = "https://www.example.com"
private val shortUrl = "https://is.gd/Pt2sET" private val shortUrl = "https://is.gd/Pt2sET"
private val shortVgdUrl = "https://v.gd/2z2ncj" private val shortVgdUrl = "https://v.gd/2z2ncj"
@Test
fun testException() {
assertFailsWith(
message = "shorten(duplicate)",
exceptionClass = IsgdException::class,
block = { Isgd.shorten(shortUrl) }
)
try {
Isgd.shorten(shortUrl)
} catch (e: IsgdException) {
assertThat(e, "shorten(duplicate)").all {
prop(IsgdException::statusCode).isEqualTo(400)
prop(IsgdException::message).isNotNull().startsWith("Error: ")
}
}
}
@Test
fun testLookup() {
assertFailsWith(
message = "lookup(empty)",
exceptionClass = IllegalArgumentException::class,
block = { Isgd.lookup("") }
)
}
@Test @Test
fun testLookupDefault() { fun testLookupDefault() {
assertEquals(url, Isgd.lookup(shortUrl)) assertEquals(url, Isgd.lookup(shortUrl))
assertEquals(url, Isgd.lookup(shortVgdUrl, isVgd = true), "v.gd") assertEquals(url, Isgd.lookup(shortVgdUrl, isVgd = true), "lookup(isVgd)")
} }
@Test @Test
@ -53,7 +87,7 @@ class IsgdTest {
assertEquals( assertEquals(
"test({ \"url\": \"$url\" });", "test({ \"url\": \"$url\" });",
Isgd.lookup(shortUrl, callback = "test", format = Format.JSON), Isgd.lookup(shortUrl, callback = "test", format = Format.JSON),
"with callback" "lookup(callback)"
) )
} }
@ -65,10 +99,28 @@ class IsgdTest {
) )
} }
@Test
fun testShorten() {
assertFailsWith(
message = "shorten(empty)",
exceptionClass = IllegalArgumentException::class,
block = { Isgd.shorten("") }
)
assertFailsWith(
message = "shorten(shorturl)",
exceptionClass = IsgdException::class,
block = { Isgd.shorten(url, shorturl = "test") }
)
}
@Test @Test
fun testShortenDefault() { fun testShortenDefault() {
assertEquals(shortUrl, Isgd.shorten(url)) assertEquals(shortUrl, Isgd.shorten(url), "shorten(url)")
assertEquals(shortVgdUrl, Isgd.shorten(url, isVgd = true), "v.gd") assertEquals(shortVgdUrl, Isgd.shorten(url, isVgd = true), "shorten(isVgd)")
assertThat(Isgd.shorten(url, logstats = true), "shorten(callback)").matches("https://is.gd/\\w{6}".toRegex())
} }
@Test @Test
@ -77,20 +129,21 @@ class IsgdTest {
assertEquals( assertEquals(
"test({ \"shorturl\": \"$shortUrl\" });", "test({ \"shorturl\": \"$shortUrl\" });",
Isgd.shorten(url, callback = "test", format = Format.JSON), Isgd.shorten(url, callback = "test", format = Format.JSON),
"with callback" "shorten(callback,json)"
) )
} }
@Test @Test
fun testShortenXml() { fun testShortenXml() {
assertEquals( assertEquals(
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><output><shorturl>$shortUrl</shorturl></output>", "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
"<output><shorturl>$shortUrl</shorturl></output>",
Isgd.shorten(url, format = Format.XML) Isgd.shorten(url, format = Format.XML)
) )
} }
@Test @Test
fun testShortenWeb() { fun testShortenWeb() {
assertTrue(Isgd.shorten(url, format = Format.WEB).contains(shortUrl)) assertThat(Isgd.shorten(url, format = Format.WEB)).contains(shortUrl)
} }
} }

View file

@ -1,8 +1,8 @@
#Generated by the Semver Plugin for Gradle #Generated by the Semver Plugin for Gradle
#Sat Mar 21 16:36:23 PDT 2020 #Sun May 02 21:57:08 PDT 2021
version.buildmeta= version.buildmeta=
version.major=0 version.major=0
version.minor=9 version.minor=9
version.patch=1 version.patch=2
version.prerelease= version.prerelease=SNAPSHOT
version.semver=0.9.1 version.semver=0.9.2-SNAPSHOT