Repository: clayallsopp/routable-android
Branch: master
Commit: 053603f9f06d
Files: 31
Total size: 53.7 KB
Directory structure:
gitextract_1hx1dx12/
├── .classpath
├── .gitignore
├── .idea/
│ ├── .name
│ ├── compiler.xml
│ ├── copyright/
│ │ └── profiles_settings.xml
│ ├── encodings.xml
│ ├── gradle.xml
│ ├── misc.xml
│ ├── modules.xml
│ └── vcs.xml
├── .project
├── AndroidManifest.xml
├── LICENSE
├── README.md
├── Routable.iml
├── RoutableTestTest/
│ ├── .classpath
│ ├── .project
│ ├── AndroidManifest.xml
│ ├── proguard-project.txt
│ ├── project.properties
│ └── src/
│ └── com/
│ └── usepropeller/
│ └── routable/
│ └── test/
│ └── RouterTest.java
├── build.gradle
├── build.xml
├── gradle/
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── proguard-project.txt
├── project.properties
└── src/
└── com/
└── usepropeller/
└── routable/
├── Router.java
└── RouterActivity.java
================================================
FILE CONTENTS
================================================
================================================
FILE: .classpath
================================================
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>
================================================
FILE: .gitignore
================================================
_site
MANIFEST.MF
./*.jar
build.num
build
local.properties
bin/
gen/
_layouts
.DS_Store
gh-pages
res/
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build
================================================
FILE: .idea/.name
================================================
Routable
================================================
FILE: .idea/compiler.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<resourceExtensions />
<wildcardResourcePatterns>
<entry name="!?*.java" />
<entry name="!?*.form" />
<entry name="!?*.class" />
<entry name="!?*.groovy" />
<entry name="!?*.scala" />
<entry name="!?*.flex" />
<entry name="!?*.kt" />
<entry name="!?*.clj" />
<entry name="!?*.aj" />
</wildcardResourcePatterns>
<annotationProcessing>
<profile default="true" name="Default" enabled="false">
<processorPath useClasspath="true" />
</profile>
</annotationProcessing>
</component>
</project>
================================================
FILE: .idea/copyright/profiles_settings.xml
================================================
<component name="CopyrightManager">
<settings default="" />
</component>
================================================
FILE: .idea/encodings.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="PROJECT" charset="UTF-8" />
</component>
</project>
================================================
FILE: .idea/gradle.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleJvm" value="1.7" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>
================================================
FILE: .idea/misc.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EntryPointsManager">
<entry_points version="2.0" />
</component>
<component name="ProjectLevelVcsManager" settingsEditedManually="false">
<OptionsSetting value="true" id="Add" />
<OptionsSetting value="true" id="Remove" />
<OptionsSetting value="true" id="Checkout" />
<OptionsSetting value="true" id="Update" />
<OptionsSetting value="true" id="Status" />
<OptionsSetting value="true" id="Edit" />
<ConfirmationsSetting value="0" id="Add" />
<ConfirmationsSetting value="0" id="Remove" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" default="true" assert-keyword="true" jdk-15="true" project-jdk-name="1.7" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
</project>
================================================
FILE: .idea/modules.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/Routable.iml" filepath="$PROJECT_DIR$/Routable.iml" />
</modules>
</component>
</project>
================================================
FILE: .idea/vcs.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
================================================
FILE: .project
================================================
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Routable</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
================================================
FILE: AndroidManifest.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.usepropeller.routable"
android:versionName="1.0.0"
android:versionCode="1">
<uses-sdk
android:minSdkVersion="3" />
<application />
</manifest>
================================================
FILE: LICENSE
================================================
Copyright (c) 2013 Turboprop, Inc. (http://usepropeller.com/)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
================================================
FILE: README.md
================================================
# Routable
Routable is an in-app native URL router, for Android. Also available for [iOS](https://github.com/usepropeller/routable-ios).
## Usage
Set up your app's router and URLs:
```java
import com.usepropeller.routable.Router;
public class PropellerApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// Set the global context
Router.sharedRouter().setContext(getApplicationContext());
// Symbol-esque params are passed as intent extras to the activities
Router.sharedRouter().map("users/:id", UserActivity.class);
Router.sharedRouter().map("users/new/:name/:zip", NewUserActivity.class);
}
}
```
In your `Activity` classes, add support for the URL params:
```java
import com.usepropeller.routable.Router;
public class UserActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle intentExtras = getIntent().getExtras();
// Note this extra, and how it corresponds to the ":id" above
String userId = intentExtras.get("id");
}
}
public class NewUserActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle intentExtras = getIntent().getExtras();
// Corresponds to the ":name" above
String name = intentExtras.get("name");
// Corresponds to the ":zip" above
String zip = intentExtras.get("zip");
}
}
```
*Anywhere* else in your app, open some URLs:
```java
// starts a new UserActivity
Router.sharedRouter().open("users/16");
// starts a new NewUserActivity
Router.sharedRouter().open("users/new/Clay/94303");
```
## Installation
Routable is currently an Android library project (so no Maven).
If you're in a hurry, you can just copy-paste the [Router.java](https://github.com/usepropeller/routable-android/blob/master/src/com/usepropeller/routable/Router.java) file.
Or if you're being a little more proactive, you should import the Routable project (this entire git repo) into Eclipse and [reference it](http://developer.android.com/tools/projects/projects-eclipse.html#ReferencingLibraryProject) in your own project.
## Features
### Routable Functions
You can call arbitrary blocks of code with Routable:
```java
Router.sharedRouter().map("logout", new Router.RouterCallback() {
public void run(Router.RouteContext context) {
User.logout();
}
});
// Somewhere else
Router.sharedRouter().open("logout");
```
### Open External URLs
Sometimes you want to open a URL outside of your app, like a YouTube URL or open a web URL in the browser. You can use Routable to do that:
```java
Router.sharedRouter().openExternal("http://www.youtube.com/watch?v=oHg5SJYRHA0")
```
### Multiple Routers
If you need to use multiple routers, simply create new instances of `Router`:
```java
Router adminRouter = new Router();
Router userRouter = new Router();
```
## Contact
Clay Allsopp ([http://clayallsopp.com](http://clayallsopp.com))
- [http://twitter.com/clayallsopp](http://twitter.com/clayallsopp)
- [clay@usepropeller.com](clay@usepropeller.com)
## License
Routable for Android is available under the MIT license. See the LICENSE file for more info.
================================================
FILE: Routable.iml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<module external.linked.project.id="Routable" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="android" name="Android">
<configuration>
<option name="SELECTED_BUILD_VARIANT" value="debug" />
<option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
<option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
<option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
<option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
<option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugAndroidTest" />
<option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugAndroidTestSources" />
<option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugAndroidTestSources" />
<option name="ALLOW_USER_CONFIGURATION" value="false" />
<option name="RES_FOLDERS_RELATIVE_PATH" value="" />
<option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
<option name="LIBRARY_PROJECT" value="true" />
</configuration>
</facet>
<facet type="android-gradle" name="Android-Gradle">
<configuration>
<option name="GRADLE_PROJECT_PATH" value=":" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" inherit-compiler-output="false">
<output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
<output-test url="file://$MODULE_DIR$/build/intermediates/classes/androidTest/debug" />
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/androidTest/debug" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/res" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/RoutableTestTest/src" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
<excludeFolder url="file://$MODULE_DIR$/build/outputs" />
<excludeFolder url="file://$MODULE_DIR$/build/reports" />
<excludeFolder url="file://$MODULE_DIR$/build/test-results" />
<excludeFolder url="file://$MODULE_DIR$/build/tmp" />
</content>
<orderEntry type="jdk" jdkName="Android API 17 Platform" jdkType="Android SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
================================================
FILE: RoutableTestTest/.classpath
================================================
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry combineaccessrules="false" kind="src" path="/Routable"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>
================================================
FILE: RoutableTestTest/.project
================================================
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>RoutableTest</name>
<comment></comment>
<projects>
<project>Routable</project>
</projects>
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
================================================
FILE: RoutableTestTest/AndroidManifest.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.usepropeller.routable.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="3" />
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.usepropeller.routable.test" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<uses-library android:name="android.test.runner" />
</application>
</manifest>
================================================
FILE: RoutableTestTest/proguard-project.txt
================================================
# To enable ProGuard in your project, edit project.properties
# to define the proguard.config property as described in that file.
#
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in ${sdk.dir}/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the ProGuard
# include property in project.properties.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
================================================
FILE: RoutableTestTest/project.properties
================================================
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system edit
# "ant.properties", and override values to adapt the script to your
# project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Project target.
target=android-7
android.library.reference.1=..
================================================
FILE: RoutableTestTest/src/com/usepropeller/routable/test/RouterTest.java
================================================
package com.usepropeller.routable.test;
import java.util.Map;
import com.usepropeller.routable.Router;
import junit.framework.Assert;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.test.AndroidTestCase;
public class RouterTest extends AndroidTestCase {
private boolean _called;
@Override
public void setUp() throws Exception {
super.setUp();
this._called = false;
}
public void test_basic() {
Router router = new Router();
router.map("users/:user_id", ListActivity.class);
Intent intent = router.intentFor("users/4");
Assert.assertEquals("4", intent.getExtras().getString("user_id"));
}
public void test_empty() {
Router router = new Router();
router.map("users", ListActivity.class);
Intent intent = router.intentFor("users");
Assert.assertNull(intent.getExtras());
}
public void test_invalid_route() {
Router router = new Router();
boolean exceptionThrown = false;
try {
router.intentFor("users/4");
} catch (Router.RouteNotFoundException e) {
exceptionThrown = true;
} catch (Exception e) {
e.printStackTrace();
fail("Incorrect exception throw: " + e.toString());
}
Assert.assertTrue("Invalid route did not throw exception", exceptionThrown);
}
public void test_invalid_context() {
Router router = new Router();
router.map("users", ListActivity.class);
boolean exceptionThrown = false;
try {
router.open("users");
} catch (Router.ContextNotProvided e) {
exceptionThrown = true;
} catch (Exception e) {
e.printStackTrace();
fail("Incorrect exception throw: " + e.toString());
}
Assert.assertTrue("Invalid context did not throw exception", exceptionThrown);
}
public void test_code_callbacks() {
Router router = new Router(this.getContext());
router.map("callback", new Router.RouterCallback() {
@Override
public void run(Router.RouteContext context) {
RouterTest.this._called = true;
Assert.assertNotNull(context.getContext());
}
});
router.open("callback");
Assert.assertTrue(this._called);
}
public void test_code_callbacks_with_params() {
Router router = new Router(this.getContext());
router.map("callback/:id", new Router.RouterCallback() {
@Override
public void run(Router.RouteContext context) {
RouterTest.this._called = true;
Assert.assertEquals("123", context.getParams().get("id"));
}
});
router.open("callback/123");
Assert.assertTrue(this._called);
}
public void test_code_callbacks_with_extras() {
Router router = new Router(this.getContext());
router.map("callback/:id", new Router.RouterCallback() {
@Override
public void run(Router.RouteContext context) {
RouterTest.this._called = true;
Assert.assertEquals("value", context.getExtras().getString("test"));
}
});
Bundle extras = new Bundle();
extras.putString("test", "value");
router.open("callback/123", extras);
Assert.assertTrue(this._called);
}
public void test_url_starting_with_slash() {
Router router = new Router();
router.map("/users", ListActivity.class);
Intent intent = router.intentFor("/users");
Assert.assertNull(intent.getExtras());
}
public void test_url_querystring() {
Router router = new Router();
router.map("/users/:id", ListActivity.class);
Intent intent = router.intentFor("/users/123?key1=val2");
Bundle extras = intent.getExtras();
Assert.assertEquals("123", extras.getString("id"));
Assert.assertEquals("val2", extras.getString("key1"));
}
public void test_url_containing_spaces() {
Router router = new Router();
router.map("/path+entry/:id", ListActivity.class);
Intent intent = router.intentFor("/path+entry/123");
Bundle extras = intent.getExtras();
Assert.assertEquals("123", extras.getString("id"));
}
public void test_url_querystring_with_encoded_value() {
Router router = new Router();
router.map("/users/:id", ListActivity.class);
Intent intent = router.intentFor("/users/123?key1=val+1&key2=val%202");
Bundle extras = intent.getExtras();
Assert.assertEquals("val 1", extras.getString("key1"));
Assert.assertEquals("val 2", extras.getString("key2"));
}
public void test_url_querystring_without_value() {
Router router = new Router();
router.map("/users/:id", ListActivity.class);
Intent intent = router.intentFor("/users/123?val1");
Bundle extras = intent.getExtras();
Assert.assertTrue(extras.containsKey("val1"));
}
public void test_url_starting_with_slash_with_params() {
Router router = new Router();
router.map("/users/:user_id", ListActivity.class);
Intent intent = router.intentFor("/users/4");
Assert.assertEquals("4", intent.getExtras().getString("user_id"));
}
}
================================================
FILE: build.gradle
================================================
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.2.3'
}
}
apply plugin: 'android-library'
repositories {
mavenCentral()
}
android {
compileSdkVersion 17
buildToolsVersion "19.1.0"
defaultConfig {
minSdkVersion 9
targetSdkVersion 17
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
res.srcDirs = ['res']
}
androidTest {
java.srcDir 'RoutableTestTest/src'
}
}
}
================================================
FILE: build.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project name="library" default="help">
<!-- The local.properties file is created and updated by the 'android' tool.
It contains the path to the SDK. It should *NOT* be checked into
Version Control Systems. -->
<property file="local.properties" />
<!-- The ant.properties file can be created by you. It is only edited by the
'android' tool to add properties to it.
This is the place to change some Ant specific build properties.
Here are some properties you may want to change/update:
source.dir
The name of the source directory. Default is 'src'.
out.dir
The name of the output directory. Default is 'bin'.
For other overridable properties, look at the beginning of the rules
files in the SDK, at tools/ant/build.xml
Properties related to the SDK location or the project target should
be updated using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your
application and should be checked into Version Control Systems.
-->
<property file="ant.properties" />
<!-- if sdk.dir was not set from one of the property file, then
get it from the ANDROID_HOME env var.
This must be done before we load project.properties since
the proguard config can use sdk.dir -->
<property environment="env" />
<condition property="sdk.dir" value="${env.ANDROID_HOME}">
<isset property="env.ANDROID_HOME" />
</condition>
<!-- The project.properties file is created and updated by the 'android'
tool, as well as ADT.
This contains project specific properties such as project target, and library
dependencies. Lower level build properties are stored in ant.properties
(or in .classpath for Eclipse projects).
This file is an integral part of the build system for your
application and should be checked into Version Control Systems. -->
<loadproperties srcFile="project.properties" />
<!-- quick check on sdk.dir -->
<fail
message="sdk.dir is missing. Make sure to generate local.properties using 'android update project' or to inject it through the ANDROID_HOME environment variable."
unless="sdk.dir"
/>
<!--
Import per project custom build rules if present at the root of the project.
This is the place to put custom intermediary targets such as:
-pre-build
-pre-compile
-post-compile (This is typically used for code obfuscation.
Compiled code location: ${out.classes.absolute.dir}
If this is not done in place, override ${out.dex.input.absolute.dir})
-post-package
-post-build
-pre-clean
-->
<import file="custom_rules.xml" optional="true" />
<!-- Import the actual build file.
To customize existing targets, there are two options:
- Customize only one target:
- copy/paste the target into this file, *before* the
<import> task.
- customize it to your needs.
- Customize the whole content of build.xml
- copy/paste the content of the rules files (minus the top node)
into this file, replacing the <import> task.
- customize to your needs.
***********************
****** IMPORTANT ******
***********************
In all cases you must update the value of version-tag below to read 'custom' instead of an integer,
in order to avoid having your file be overridden by tools such as "android update project"
-->
<!-- version-tag: 1 -->
<import file="${sdk.dir}/tools/ant/build.xml" />
</project>
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Wed Apr 10 15:27:10 PDT 2013
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip
================================================
FILE: gradlew
================================================
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# For Cygwin, ensure paths are in UNIX format before anything is touched.
if $cygwin ; then
[ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >&-
APP_HOME="`pwd -P`"
cd "$SAVED" >&-
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
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.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
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, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
# 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=$((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
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
================================================
FILE: gradlew.bat
================================================
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
================================================
FILE: proguard-project.txt
================================================
# To enable ProGuard in your project, edit project.properties
# to define the proguard.config property as described in that file.
#
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in ${sdk.dir}/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the ProGuard
# include property in project.properties.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
================================================
FILE: project.properties
================================================
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system edit
# "ant.properties", and override values to adapt the script to your
# project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Project target.
target=android-17
android.library=true
================================================
FILE: src/com/usepropeller/routable/Router.java
================================================
/*
Routable for Android
Copyright (c) 2013 Turboprop, Inc. <clay@usepropeller.com>
http://usepropeller.com
Licensed under the MIT License.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package com.usepropeller.routable;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
public class Router {
private static final Router _router = new Router();
/**
* A globally accessible Router instance that will work for
* most use cases.
*/
public static Router sharedRouter() {
return _router;
}
/**
* The class used when you want to map a function (given in `run`)
* to a Router URL.
*/
public static abstract class RouterCallback {
public abstract void run(RouteContext context);
}
/**
* The class supplied to custom callbacks to describe the route route
*/
public class RouteContext {
Map<String, String> _params;
Bundle _extras;
Context _context;
public RouteContext(Map<String, String> params, Bundle extras, Context context) {
_params = params;
_extras = extras;
_context = context;
}
/**
* Returns the route parameters as specified by the configured route
*/
public Map<String, String> getParams() { return _params; }
/**
* Returns the extras supplied with the route
*/
public Bundle getExtras() { return _extras; }
/**
* Returns the Android Context that should be used to open the route
*/
public Context getContext() { return _context; }
}
/**
* The class used to determine behavior when opening a URL.
* If you want to extend Routable to handle things like transition
* animations or fragments, this class should be augmented.
*/
public static class RouterOptions {
Class<? extends Activity> _klass;
RouterCallback _callback;
Map<String, String> _defaultParams;
public RouterOptions() {
}
public RouterOptions(Class<? extends Activity> klass) {
this.setOpenClass(klass);
}
public RouterOptions(Map<String, String> defaultParams) {
this.setDefaultParams(defaultParams);
}
public RouterOptions(Map<String, String> defaultParams, Class<? extends Activity> klass) {
this.setDefaultParams(defaultParams);
this.setOpenClass(klass);
}
public void setOpenClass(Class<? extends Activity> klass) {
this._klass = klass;
}
public Class<? extends Activity> getOpenClass() {
return this._klass;
}
public RouterCallback getCallback() {
return this._callback;
}
public void setCallback(RouterCallback callback) {
this._callback = callback;
}
public void setDefaultParams(Map<String, String> defaultParams) {
this._defaultParams = defaultParams;
}
public Map<String, String> getDefaultParams() {
return this._defaultParams;
}
}
private static class RouterParams {
public RouterOptions routerOptions;
public Map<String, String> openParams;
}
private final Map<String, RouterOptions> _routes = new HashMap<String, RouterOptions>();
private String _rootUrl = null;
private final Map<String, RouterParams> _cachedRoutes = new HashMap<String, RouterParams>();
private Context _context;
/**
* Creates a new Router
*/
public Router() {
}
/**
* Creates a new Router
* @param context {@link Context} that all {@link Intent}s generated by the router will use
*/
public Router(Context context) {
this.setContext(context);
}
/**
* @param context {@link Context} that all {@link Intent}s generated by the router will use
*/
public void setContext(Context context) {
this._context = context;
}
/**
* @return The context for the router
*/
public Context getContext() {
return this._context;
}
/**
* Map a URL to a callback
* @param format The URL being mapped; for example, "users/:id" or "groups/:id/topics/:topic_id"
* @param callback {@link RouterCallback} instance which contains the code to execute when the URL is opened
*/
public void map(String format, RouterCallback callback) {
RouterOptions options = new RouterOptions();
options.setCallback(callback);
this.map(format, null, options);
}
/**
* Map a URL to open an {@link Activity}
* @param format The URL being mapped; for example, "users/:id" or "groups/:id/topics/:topic_id"
* @param klass The {@link Activity} class to be opened with the URL
*/
public void map(String format, Class<? extends Activity> klass) {
this.map(format, klass, null);
}
/**
* Map a URL to open an {@link Activity}
* @param format The URL being mapped; for example, "users/:id" or "groups/:id/topics/:topic_id"
* @param klass The {@link Activity} class to be opened with the URL
* @param options The {@link RouterOptions} to be used for more granular and customized options for when the URL is opened
*/
public void map(String format, Class<? extends Activity> klass, RouterOptions options) {
if (options == null) {
options = new RouterOptions();
}
options.setOpenClass(klass);
this._routes.put(format, options);
}
/**
* Set the root url; used when opening an activity or callback via RouterActivity
* @param rootUrl The URL format to use as the root
*/
public void setRootUrl(String rootUrl) {
this._rootUrl = rootUrl;
}
/**
* @return The router's root URL, or null.
*/
public String getRootUrl() {
return this._rootUrl;
}
/**
* Open a URL using the operating system's configuration (such as opening a link to Chrome or a video to YouTube)
* @param url The URL; for example, "http://www.youtube.com/watch?v=oHg5SJYRHA0"
*/
public void openExternal(String url) {
this.openExternal(url, this._context);
}
/**
* Open a URL using the operating system's configuration (such as opening a link to Chrome or a video to YouTube)
* @param url The URL; for example, "http://www.youtube.com/watch?v=oHg5SJYRHA0"
* @param context The context which is used in the generated {@link Intent}
*/
public void openExternal(String url, Context context) {
this.openExternal(url, null, context);
}
/**
* Open a URL using the operating system's configuration (such as opening a link to Chrome or a video to YouTube)
* @param url The URL; for example, "http://www.youtube.com/watch?v=oHg5SJYRHA0"
* @param extras The {@link Bundle} which contains the extras to be assigned to the generated {@link Intent}
*/
public void openExternal(String url, Bundle extras) {
this.openExternal(url, extras, this._context);
}
/**
* Open a URL using the operating system's configuration (such as opening a link to Chrome or a video to YouTube)
* @param url The URL; for example, "http://www.youtube.com/watch?v=oHg5SJYRHA0"
* @param extras The {@link Bundle} which contains the extras to be assigned to the generated {@link Intent}
* @param context The context which is used in the generated {@link Intent}
*/
public void openExternal(String url, Bundle extras, Context context) {
if (context == null) {
throw new ContextNotProvided(
"You need to supply a context for Router "
+ this.toString());
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
this.addFlagsToIntent(intent, context);
if (extras != null) {
intent.putExtras(extras);
}
context.startActivity(intent);
}
/**
* Open a map'd URL set using {@link #map(String, Class)} or {@link #map(String, RouterCallback)}
* @param url The URL; for example, "users/16" or "groups/5/topics/20"
*/
public void open(String url) {
this.open(url, this._context);
}
/**
* Open a map'd URL set using {@link #map(String, Class)} or {@link #map(String, RouterCallback)}
* @param url The URL; for example, "users/16" or "groups/5/topics/20"
* @param extras The {@link Bundle} which contains the extras to be assigned to the generated {@link Intent}
*/
public void open(String url, Bundle extras) {
this.open(url, extras, this._context);
}
/**
* Open a map'd URL set using {@link #map(String, Class)} or {@link #map(String, RouterCallback)}
* @param url The URL; for example, "users/16" or "groups/5/topics/20"
* @param context The context which is used in the generated {@link Intent}
*/
public void open(String url, Context context) {
this.open(url, null, context);
}
/**
* Open a map'd URL set using {@link #map(String, Class)} or {@link #map(String, RouterCallback)}
* @param url The URL; for example, "users/16" or "groups/5/topics/20"
* @param extras The {@link Bundle} which contains the extras to be assigned to the generated {@link Intent}
* @param context The context which is used in the generated {@link Intent}
*/
public void open(String url, Bundle extras, Context context) {
if (context == null) {
throw new ContextNotProvided(
"You need to supply a context for Router "
+ this.toString());
}
RouterParams params = this.paramsForUrl(url);
RouterOptions options = params.routerOptions;
if (options.getCallback() != null) {
RouteContext routeContext = new RouteContext(params.openParams, extras, context);
options.getCallback().run(routeContext);
return;
}
Intent intent = this.intentFor(context, params);
if (intent == null) {
// Means the options weren't opening a new activity
return;
}
if (extras != null) {
intent.putExtras(extras);
}
context.startActivity(intent);
}
/*
* Allows Intents to be spawned regardless of what context they were opened with.
*/
private void addFlagsToIntent(Intent intent, Context context) {
if (context == this._context) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
}
/**
* @param url The URL; for example, "users/16" or "groups/5/topics/20"
* @return The {@link Intent} for the url
*/
public Intent intentFor(String url) {
RouterParams params = this.paramsForUrl(url);
return intentFor(params);
}
private Intent intentFor(RouterParams params) {
RouterOptions options = params.routerOptions;
Intent intent = new Intent();
if (options.getDefaultParams() != null) {
for (Entry<String, String> entry : options.getDefaultParams().entrySet()) {
intent.putExtra(entry.getKey(), entry.getValue());
}
}
for (Entry<String, String> entry : params.openParams.entrySet()) {
intent.putExtra(entry.getKey(), entry.getValue());
}
return intent;
}
/**
* @param url The URL to check
* @return Whether or not the URL refers to an anonymous callback function
*/
public boolean isCallbackUrl(String url) {
RouterParams params = this.paramsForUrl(url);
RouterOptions options = params.routerOptions;
return options.getCallback() != null;
}
/**
*
* @param context The context which is spawning the intent
* @param url The URL; for example, "users/16" or "groups/5/topics/20"
* @return The {@link Intent} for the url, with the correct {@link Activity} set, or null.
*/
public Intent intentFor(Context context, String url) {
RouterParams params = this.paramsForUrl(url);
return intentFor(context, params);
}
private Intent intentFor(Context context, RouterParams params) {
RouterOptions options = params.routerOptions;
if (options.getCallback() != null) {
return null;
}
Intent intent = intentFor(params);
intent.setClass(context, options.getOpenClass());
this.addFlagsToIntent(intent, context);
return intent;
}
/*
* Takes a url (i.e. "/users/16/hello") and breaks it into a {@link RouterParams} instance where
* each of the parameters (like ":id") has been parsed.
*/
private RouterParams paramsForUrl(String url) {
final String cleanedUrl = cleanUrl(url);
URI parsedUri = URI.create("http://tempuri.org/" + cleanedUrl);
String urlPath = parsedUri.getPath().substring(1);
if (this._cachedRoutes.get(cleanedUrl) != null) {
return this._cachedRoutes.get(cleanedUrl);
}
String[] givenParts = urlPath.split("/");
RouterParams routerParams = null;
for (Entry<String, RouterOptions> entry : this._routes.entrySet()) {
String routerUrl = cleanUrl(entry.getKey());
RouterOptions routerOptions = entry.getValue();
String[] routerParts = routerUrl.split("/");
if (routerParts.length != givenParts.length) {
continue;
}
Map<String, String> givenParams = urlToParamsMap(givenParts, routerParts);
if (givenParams == null) {
continue;
}
routerParams = new RouterParams();
routerParams.openParams = givenParams;
routerParams.routerOptions = routerOptions;
break;
}
if (routerParams == null) {
throw new RouteNotFoundException("No route found for url " + url);
}
List<NameValuePair> query = URLEncodedUtils.parse(parsedUri, "utf-8");
for (NameValuePair pair : query) {
routerParams.openParams.put(pair.getName(), pair.getValue());
}
this._cachedRoutes.put(cleanedUrl, routerParams);
return routerParams;
}
/**
*
* @param givenUrlSegments An array representing the URL path attempting to be opened (i.e. ["users", "42"])
* @param routerUrlSegments An array representing a possible URL match for the router (i.e. ["users", ":id"])
* @return A map of URL parameters if it's a match (i.e. {"id" => "42"}) or null if there is no match
*/
private Map<String, String> urlToParamsMap(String[] givenUrlSegments, String[] routerUrlSegments) {
Map<String, String> formatParams = new HashMap<String, String>();
for (int index = 0; index < routerUrlSegments.length; index++) {
String routerPart = routerUrlSegments[index];
String givenPart = givenUrlSegments[index];
if (routerPart.charAt(0) == ':') {
String key = routerPart.substring(1, routerPart.length());
formatParams.put(key, givenPart);
continue;
}
if (!routerPart.equals(givenPart)) {
return null;
}
}
return formatParams;
}
/**
* Clean up url
* @param url
* @return cleaned url
*/
private String cleanUrl(String url) {
if (url.startsWith("/")) {
return url.substring(1, url.length());
}
return url;
}
/**
* Thrown if a given route is not found.
*/
public static class RouteNotFoundException extends RuntimeException {
private static final long serialVersionUID = -2278644339983544651L;
public RouteNotFoundException(String message) {
super(message);
}
}
/**
* Thrown if no context has been found.
*/
public static class ContextNotProvided extends RuntimeException {
private static final long serialVersionUID = -1381427067387547157L;
public ContextNotProvided(String message) {
super(message);
}
}
}
================================================
FILE: src/com/usepropeller/routable/RouterActivity.java
================================================
package com.usepropeller.routable;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
public class RouterActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String url;
Bundle extras = intent.getExtras();
if (extras.containsKey("url")) {
url = extras.getString("url");
}
else {
Uri data = intent.getData();
String protocol = data.getScheme() + "://";
url = data.toString().replaceFirst(protocol, "");
if (Router.sharedRouter().getRootUrl() != null) {
Router.sharedRouter().open(Router.sharedRouter().getRootUrl());
}
}
Router.sharedRouter().open(url);
setResult(RESULT_OK, null);
finish();
}
}
gitextract_1hx1dx12/
├── .classpath
├── .gitignore
├── .idea/
│ ├── .name
│ ├── compiler.xml
│ ├── copyright/
│ │ └── profiles_settings.xml
│ ├── encodings.xml
│ ├── gradle.xml
│ ├── misc.xml
│ ├── modules.xml
│ └── vcs.xml
├── .project
├── AndroidManifest.xml
├── LICENSE
├── README.md
├── Routable.iml
├── RoutableTestTest/
│ ├── .classpath
│ ├── .project
│ ├── AndroidManifest.xml
│ ├── proguard-project.txt
│ ├── project.properties
│ └── src/
│ └── com/
│ └── usepropeller/
│ └── routable/
│ └── test/
│ └── RouterTest.java
├── build.gradle
├── build.xml
├── gradle/
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── proguard-project.txt
├── project.properties
└── src/
└── com/
└── usepropeller/
└── routable/
├── Router.java
└── RouterActivity.java
SYMBOL INDEX (68 symbols across 3 files)
FILE: RoutableTestTest/src/com/usepropeller/routable/test/RouterTest.java
class RouterTest (line 14) | public class RouterTest extends AndroidTestCase {
method setUp (line 17) | @Override
method test_basic (line 24) | public void test_basic() {
method test_empty (line 32) | public void test_empty() {
method test_invalid_route (line 40) | public void test_invalid_route() {
method test_invalid_context (line 56) | public void test_invalid_context() {
method test_code_callbacks (line 73) | public void test_code_callbacks() {
method test_code_callbacks_with_params (line 89) | public void test_code_callbacks_with_params() {
method test_code_callbacks_with_extras (line 104) | public void test_code_callbacks_with_extras() {
method test_url_starting_with_slash (line 122) | public void test_url_starting_with_slash() {
method test_url_querystring (line 130) | public void test_url_querystring() {
method test_url_containing_spaces (line 141) | public void test_url_containing_spaces() {
method test_url_querystring_with_encoded_value (line 151) | public void test_url_querystring_with_encoded_value() {
method test_url_querystring_without_value (line 162) | public void test_url_querystring_without_value() {
method test_url_starting_with_slash_with_params (line 172) | public void test_url_starting_with_slash_with_params() {
FILE: src/com/usepropeller/routable/Router.java
class Router (line 44) | public class Router {
method sharedRouter (line 51) | public static Router sharedRouter() {
class RouterCallback (line 59) | public static abstract class RouterCallback {
method run (line 60) | public abstract void run(RouteContext context);
class RouteContext (line 66) | public class RouteContext {
method RouteContext (line 71) | public RouteContext(Map<String, String> params, Bundle extras, Conte...
method getParams (line 80) | public Map<String, String> getParams() { return _params; }
method getExtras (line 85) | public Bundle getExtras() { return _extras; }
method getContext (line 90) | public Context getContext() { return _context; }
class RouterOptions (line 98) | public static class RouterOptions {
method RouterOptions (line 103) | public RouterOptions() {
method RouterOptions (line 107) | public RouterOptions(Class<? extends Activity> klass) {
method RouterOptions (line 111) | public RouterOptions(Map<String, String> defaultParams) {
method RouterOptions (line 115) | public RouterOptions(Map<String, String> defaultParams, Class<? exte...
method setOpenClass (line 120) | public void setOpenClass(Class<? extends Activity> klass) {
method getOpenClass (line 124) | public Class<? extends Activity> getOpenClass() {
method getCallback (line 128) | public RouterCallback getCallback() {
method setCallback (line 132) | public void setCallback(RouterCallback callback) {
method setDefaultParams (line 136) | public void setDefaultParams(Map<String, String> defaultParams) {
method getDefaultParams (line 140) | public Map<String, String> getDefaultParams() {
class RouterParams (line 145) | private static class RouterParams {
method Router (line 158) | public Router() {
method Router (line 166) | public Router(Context context) {
method setContext (line 173) | public void setContext(Context context) {
method getContext (line 180) | public Context getContext() {
method map (line 189) | public void map(String format, RouterCallback callback) {
method map (line 200) | public void map(String format, Class<? extends Activity> klass) {
method map (line 210) | public void map(String format, Class<? extends Activity> klass, Router...
method setRootUrl (line 222) | public void setRootUrl(String rootUrl) {
method getRootUrl (line 229) | public String getRootUrl() {
method openExternal (line 237) | public void openExternal(String url) {
method openExternal (line 246) | public void openExternal(String url, Context context) {
method openExternal (line 255) | public void openExternal(String url, Bundle extras) {
method openExternal (line 265) | public void openExternal(String url, Bundle extras, Context context) {
method open (line 283) | public void open(String url) {
method open (line 292) | public void open(String url, Bundle extras) {
method open (line 301) | public void open(String url, Context context) {
method open (line 311) | public void open(String url, Bundle extras, Context context) {
method addFlagsToIntent (line 340) | private void addFlagsToIntent(Intent intent, Context context) {
method intentFor (line 350) | public Intent intentFor(String url) {
method intentFor (line 356) | private Intent intentFor(RouterParams params) {
method isCallbackUrl (line 374) | public boolean isCallbackUrl(String url) {
method intentFor (line 386) | public Intent intentFor(Context context, String url) {
method intentFor (line 392) | private Intent intentFor(Context context, RouterParams params) {
method paramsForUrl (line 408) | private RouterParams paramsForUrl(String url) {
method urlToParamsMap (line 462) | private Map<String, String> urlToParamsMap(String[] givenUrlSegments, ...
method cleanUrl (line 487) | private String cleanUrl(String url) {
class RouteNotFoundException (line 497) | public static class RouteNotFoundException extends RuntimeException {
method RouteNotFoundException (line 500) | public RouteNotFoundException(String message) {
class ContextNotProvided (line 508) | public static class ContextNotProvided extends RuntimeException {
method ContextNotProvided (line 511) | public ContextNotProvided(String message) {
FILE: src/com/usepropeller/routable/RouterActivity.java
class RouterActivity (line 8) | public class RouterActivity extends Activity {
method onCreate (line 9) | @Override
Condensed preview — 31 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (60K chars).
[
{
"path": ".classpath",
"chars": 356,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<classpath>\n\t<classpathentry kind=\"src\" path=\"src\"/>\n\t<classpathentry kind=\"src\" "
},
{
"path": ".gitignore",
"chars": 183,
"preview": "_site\nMANIFEST.MF\n./*.jar\nbuild.num\nbuild\nlocal.properties\nbin/\ngen/\n_layouts\n.DS_Store\ngh-pages\nres/\n\n.gradle\n/local.pr"
},
{
"path": ".idea/.name",
"chars": 8,
"preview": "Routable"
},
{
"path": ".idea/compiler.xml",
"chars": 686,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project version=\"4\">\n <component name=\"CompilerConfiguration\">\n <resourceExt"
},
{
"path": ".idea/copyright/profiles_settings.xml",
"chars": 74,
"preview": "<component name=\"CopyrightManager\">\n <settings default=\"\" />\n</component>"
},
{
"path": ".idea/encodings.xml",
"chars": 159,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project version=\"4\">\n <component name=\"Encoding\">\n <file url=\"PROJECT\" chars"
},
{
"path": ".idea/gradle.xml",
"chars": 559,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project version=\"4\">\n <component name=\"GradleSettings\">\n <option name=\"linke"
},
{
"path": ".idea/misc.xml",
"chars": 972,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project version=\"4\">\n <component name=\"EntryPointsManager\">\n <entry_points v"
},
{
"path": ".idea/modules.xml",
"chars": 256,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project version=\"4\">\n <component name=\"ProjectModuleManager\">\n <modules>\n "
},
{
"path": ".idea/vcs.xml",
"chars": 167,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project version=\"4\">\n <component name=\"VcsDirectoryMappings\">\n <mapping dire"
},
{
"path": ".project",
"chars": 811,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<projectDescription>\n\t<name>Routable</name>\n\t<comment></comment>\n\t<projects>\n\t</p"
},
{
"path": "AndroidManifest.xml",
"chars": 316,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n pa"
},
{
"path": "LICENSE",
"chars": 1085,
"preview": "Copyright (c) 2013 Turboprop, Inc. (http://usepropeller.com/)\n\nPermission is hereby granted, free of charge, to any pers"
},
{
"path": "README.md",
"chars": 3347,
"preview": "# Routable\n\nRoutable is an in-app native URL router, for Android. Also available for [iOS](https://github.com/usepropell"
},
{
"path": "Routable.iml",
"chars": 7128,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<module external.linked.project.id=\"Routable\" external.linked.project.path=\"$MODU"
},
{
"path": "RoutableTestTest/.classpath",
"chars": 430,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<classpath>\n\t<classpathentry kind=\"src\" path=\"src\"/>\n\t<classpathentry kind=\"src\" "
},
{
"path": "RoutableTestTest/.project",
"chars": 845,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<projectDescription>\n\t<name>RoutableTest</name>\n\t<comment></comment>\n\t<projects>\n"
},
{
"path": "RoutableTestTest/AndroidManifest.xml",
"chars": 604,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package="
},
{
"path": "RoutableTestTest/proguard-project.txt",
"chars": 781,
"preview": "# To enable ProGuard in your project, edit project.properties\n# to define the proguard.config property as described in t"
},
{
"path": "RoutableTestTest/project.properties",
"chars": 593,
"preview": "# This file is automatically generated by Android Tools.\n# Do not modify this file -- YOUR CHANGES WILL BE ERASED!\n#\n# T"
},
{
"path": "RoutableTestTest/src/com/usepropeller/routable/test/RouterTest.java",
"chars": 5026,
"preview": "package com.usepropeller.routable.test;\n\nimport java.util.Map;\n\nimport com.usepropeller.routable.Router;\n\nimport junit.f"
},
{
"path": "build.gradle",
"chars": 611,
"preview": "buildscript {\n repositories {\n mavenCentral()\n }\n dependencies {\n classpath 'com.android.tools.bu"
},
{
"path": "build.xml",
"chars": 3919,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project name=\"library\" default=\"help\">\n\n <!-- The local.properties file is cr"
},
{
"path": "gradle/wrapper/gradle-wrapper.properties",
"chars": 232,
"preview": "#Wed Apr 10 15:27:10 PDT 2013\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_"
},
{
"path": "gradlew",
"chars": 5080,
"preview": "#!/usr/bin/env bash\n\n##############################################################################\n##\n## Gradle start "
},
{
"path": "gradlew.bat",
"chars": 2314,
"preview": "@if \"%DEBUG%\" == \"\" @echo off\n@rem ##########################################################################\n@rem\n@rem "
},
{
"path": "proguard-project.txt",
"chars": 781,
"preview": "# To enable ProGuard in your project, edit project.properties\n# to define the proguard.config property as described in t"
},
{
"path": "project.properties",
"chars": 584,
"preview": "# This file is automatically generated by Android Tools.\n# Do not modify this file -- YOUR CHANGES WILL BE ERASED!\n#\n# T"
},
{
"path": "src/com/usepropeller/routable/Router.java",
"chars": 16179,
"preview": "/*\n Routable for Android\n Copyright (c) 2013 Turboprop, Inc. <clay@usepropeller.com>\n http://usepropeller.com\n\n"
},
{
"path": "src/com/usepropeller/routable/RouterActivity.java",
"chars": 861,
"preview": "package com.usepropeller.routable;\n\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.net.Uri;\n"
}
]
// ... and 1 more files (download for full content)
About this extraction
This page contains the full source code of the clayallsopp/routable-android GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 31 files (53.7 KB), approximately 14.5k tokens, and a symbol index with 68 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.