Commit afadd295 authored by Paul Bird's avatar Paul Bird

Initial commit

parents
*.iml
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build
/captures
.externalNativeBuild
<?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>
\ No newline at end of file
<component name="CopyrightManager">
<settings default="" />
</component>
\ No newline at end of file
<?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="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
</set>
</option>
<option name="resolveModulePerSourceSet" value="false" />
</GradleProjectSettings>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="NullableNotNullManager">
<option name="myDefaultNullable" value="android.support.annotation.Nullable" />
<option name="myDefaultNotNull" value="android.support.annotation.NonNull" />
<option name="myNullables">
<value>
<list size="4">
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.Nullable" />
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nullable" />
<item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.Nullable" />
<item index="3" class="java.lang.String" itemvalue="android.support.annotation.Nullable" />
</list>
</value>
</option>
<option name="myNotNulls">
<value>
<list size="4">
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.NotNull" />
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nonnull" />
<item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.NonNull" />
<item index="3" class="java.lang.String" itemvalue="android.support.annotation.NonNull" />
</list>
</value>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
<module fileurl="file://$PROJECT_DIR$/operateAPIExampleKotlin.iml" filepath="$PROJECT_DIR$/operateAPIExampleKotlin.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RunConfigurationProducerService">
<option name="ignoredProducers">
<set>
<option value="org.jetbrains.plugins.gradle.execution.test.runner.AllInPackageGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestClassGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestMethodGradleConfigurationProducer" />
</set>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
android {
compileSdkVersion 26
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "tech.essensys.operateapiexample"
minSdkVersion 22
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:design:26.+'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
testCompile 'junit:junit:4.12'
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
}
repositories {
mavenCentral()
}
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /Users/paul/Library/Android/sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# 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 *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
package tech.essensys.operateapiexample;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("tech.essensys.operateapiexample", appContext.getPackageName());
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="tech.essensys.operateapiexample">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
\ No newline at end of file
package tech.essensys.operateapiexample
import android.content.Context
import android.util.Log
import okhttp3.*
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
/**
* Created by paul on 22/08/2017.
*/
class Authenticate(context: Context) {
private val oauth2URL = "https://api.occupie.com/oauth2/token"
private val clientSecret = ""
private val sharedPrefs: SharedPrefs
init {
sharedPrefs = SharedPrefs(context)
}
fun login(username: String, password: String) {
val postBody = "grant_type=password" + "&client_id=trustedclient" + "&client_secret=" + clientSecret + "&scope=hubapi" + "&username=" + username + "&password=" + password
Log.d("postBody", postBody)
try {
postRequest(oauth2URL, postBody)
} catch (e: IOException) {
e.printStackTrace()
}
}
@Throws(IOException::class)
internal fun postRequest(postUrl: String, postBody: String) {
val client = OkHttpClient()
val body = RequestBody.create(FORM_ENCODED, postBody)
val request = Request.Builder()
.url(postUrl)
.post(body)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
call.cancel()
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
val theResponse = response.body().string()
Log.d("theResponse", theResponse)
try {
val json = JSONObject(theResponse)
val accesstoken = json.getString("access_token")
val refreshtoken = json.getString("refresh_token")
saveTheTokens(accesstoken, refreshtoken)
} catch (e: JSONException) {
e.printStackTrace()
}
}
})
}
internal fun saveTheTokens(accessToken: String, refreshToken: String) {
sharedPrefs.accessToken = accessToken
sharedPrefs.setRefreshToken(refreshToken)
}
internal fun checkToken(): String {
Log.d("checkToken", "was called")
val get = sharedPrefs.accessToken
if (get === "") {
Log.d("checkToken", "sharedPrefs.getAccessToken returned empty")
}
return sharedPrefs.accessToken
}
companion object {
val JSON = MediaType.parse("application/json; charset=utf-8")
val FORM_ENCODED = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8")
}
}
\ No newline at end of file
package tech.essensys.operateapiexample
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.View
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
val button = findViewById(R.id.loginButton) as Button
button.setOnClickListener { login() }
val getArea1 = findViewById(R.id.getArea1) as Button
getArea1.setOnClickListener { getArea() }
val putAccount1 = findViewById(R.id.putAccount1) as Button
putAccount1.setOnClickListener { putAccount() }
val deleteAccount1 = findViewById(R.id.deleteAccount1) as Button
deleteAccount1.setOnClickListener {
//deleteAccount();
deleteArea()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.itemId
if (id == R.id.action_settings) {
return true
}
return super.onOptionsItemSelected(item)
}
private fun login() {
val authenticate = Authenticate(this)
authenticate.login("account@domain.com", "")
}
private fun getArea() {
val operateAPI1 = OperateAPI1(this)
operateAPI1["area", ""]
}
private fun putAccount() {
val operateAPI1 = OperateAPI1(this)
val data = "data={\"accounts\": [{\"clientname\": \"The Client Name\",\"clienttype\": \"2\",\"enddate\": \"22/10/2013\",\"startdate\": \"22/10/2013\"}]}"
operateAPI1.put("account", data)
}
private fun deleteAccount() {
val operateAPI1 = OperateAPI1(this)
operateAPI1.delete("account", 775785)
}
private fun deleteArea() {
val operateAPI1 = OperateAPI1(this)
operateAPI1.delete("area", 12)
}
}
package tech.essensys.operateapiexample
import android.content.Context
import android.util.Log
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import okhttp3.Call
import okhttp3.Callback
import okhttp3.FormBody
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
/**
* Created by paul on 17/08/2017.
*/
class OperateAPI1(context: Context) {
private val baseAPI = "https://api.occupie.com/api/1.0/"
private val sharedPrefs: SharedPrefs
private val accessToken: String
private val JSON = MediaType.parse("application/json; charset=utf-8")
private val FORM_ENCODED = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8")
init {
sharedPrefs = SharedPrefs(context)
accessToken = sharedPrefs.accessToken
}
operator fun get(endpoint: String, query: String) {
try {
getRequest(baseAPI + endpoint + query)
} catch (e: IOException) {
e.printStackTrace()
}
}
fun put(endpoint: String, data: String) {
try {
putRequest(baseAPI + "account", data)
} catch (e: IOException) {
e.printStackTrace()
}
}
fun delete(endpoint: String, item: Int) {
try {
deleteRequest( "account", item)
} catch (e: IOException) {
e.printStackTrace()
}
}
@Throws(IOException::class)
private fun deleteRequest(endpoint: String, item: Int) {
val client = OkHttpClient()
val itemid = String.format("%d", item)
val formBody = FormBody.Builder()
.add("itemid", itemid)
.build()
val request = Request.Builder()
.url(baseAPI + endpoint)
.addHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8")
.addHeader("Authorization", "Bearer " + accessToken)
.delete(formBody)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
call.cancel()
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
Log.d("deleteReq",request.toString())
val theResponse = response.body().string()
try {
val json = JSONObject(theResponse)
Log.d("DELETE Response", json.toString())
} catch (e: JSONException) {
e.printStackTrace()
}
}
})
}
@Throws(IOException::class)
private fun getRequest(getUrl: String) {
val client = OkHttpClient()
val request = Request.Builder()
.url(getUrl)
.addHeader("Authorization", "Bearer " + accessToken)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
call.cancel()
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
val theResponse = response.body().string()
try {
val json = JSONObject(theResponse)
Log.d("GET Response", json.toString())
} catch (e: JSONException) {
e.printStackTrace()
}
}
})
}
@Throws(IOException::class)
private fun putRequest(getUrl: String, data: String) {
val client = OkHttpClient()
val body = RequestBody.create(JSON, data)
val request = Request.Builder()
.url(getUrl)
.put(body)
.addHeader("Authorization", "Bearer " + accessToken)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
call.cancel()
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
val theResponse = response.body().string()
try {
val json = JSONObject(theResponse)
Log.d("PUT Response", json.toString())
} catch (e: JSONException) {
e.printStackTrace()
}
}
})
}
}
\ No newline at end of file
package tech.essensys.operateapiexample
import android.app.Activity
import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager
/**
* Created by paul on 15/08/2017.
*/
class SharedPrefs(context: Context) : Activity() {
private val preferences: SharedPreferences
init {
preferences = PreferenceManager.getDefaultSharedPreferences(context)
}
fun setRefreshToken(refreshtoken: String) {
val editor = preferences.edit()
editor.putString("refreshToken", refreshtoken)
editor.apply()
}
var accessToken: String
get() = preferences.getString("accessToken", "")
set(accesstoken) {
val editor = preferences.edit()
editor.putString("accessToken", accesstoken)
editor.apply()
}
companion object {
private val PREFS_NAME = "MyPrefsFile"
}
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="tech.essensys.operateapiexample.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="tech.essensys.operateapiexample.MainActivity"
tools:showIn="@layout/activity_main">
<Button
android:id="@+id/loginButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"