Commit 5555db35 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="EntryPointsManager">
<entry_points version="2.0" />
</component>
<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="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_8" default="true" assert-keyword="true" jdk-15="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$/operateAPIExample.iml" filepath="$PROJECT_DIR$/operateAPIExample.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
apply plugin: 'com.android.application'
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'
}
# 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 org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by paul on 15/08/2017.
*/
public class Authenticate {
private String oauth2URL = "https://api.occupie.com/oauth2/token";
private String clientSecret = "";
private SharedPrefs sharedPrefs;
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
public static final MediaType FORM_ENCODED = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
public Authenticate(Context context) {
sharedPrefs = new SharedPrefs(context);
}
public void login(String username, String password) {
String 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 (IOException e) {
e.printStackTrace();
}
}
void postRequest(String postUrl, String postBody) throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(FORM_ENCODED, postBody);
Request request = new Request.Builder()
.url(postUrl)
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
call.cancel();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String theResponse = response.body().string();
Log.d("theResponse",theResponse);
try {
JSONObject json = new JSONObject(theResponse);
final String accesstoken = json.getString("access_token");
final String refreshtoken = json.getString("refresh_token");
saveTheTokens(accesstoken, refreshtoken);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
void saveTheTokens(String accessToken, String refreshToken) {
sharedPrefs.setAccessToken(accessToken);
sharedPrefs.setRefreshToken(refreshToken);
}
String checkToken() {
Log.d("checkToken","was called");
String get = sharedPrefs.getAccessToken();
if (get == "") {
Log.d("checkToken","sharedPrefs.getAccessToken returned empty");
}
return sharedPrefs.getAccessToken();
}
}
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;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
final Button button = (Button) findViewById(R.id.loginButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
login();
}
});
final Button getArea1 = (Button) findViewById(R.id.getArea1);
getArea1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getArea();
}
});
final Button putAccount1 = (Button) findViewById(R.id.putAccount1);
putAccount1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
putAccount();
}
});
final Button deleteAccount1 = (Button) findViewById(R.id.deleteAccount1);
deleteAccount1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//deleteAccount();
deleteArea();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// 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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void login() {
Authenticate authenticate = new Authenticate(this);
authenticate.login("user@domain.com", "yourpassword");
}
private void getArea() {
OperateAPI1 operateAPI1 = new OperateAPI1(this);
operateAPI1.get("area","");
}
private void putAccount() {
OperateAPI1 operateAPI1 = new OperateAPI1(this);
String data = "data={\"accounts\": [{\"clientname\": \"The Client Name\",\"clienttype\": \"2\",\"enddate\": \"22/10/2013\",\"startdate\": \"22/10/2013\"}]}";
operateAPI1.put("account",data);
}
private void deleteAccount() {
OperateAPI1 operateAPI1 = new OperateAPI1(this);
operateAPI1.delete("account",775785);
}
private void deleteArea() {
OperateAPI1 operateAPI1 = new 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 22/08/2017.
*/
public class OperateAPI1 {
private String baseAPI = "https://api.occupie.com/api/1.0/";
private SharedPrefs sharedPrefs;
private String accessToken;
private MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private MediaType FORM_ENCODED = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
public OperateAPI1(Context context) {
sharedPrefs = new SharedPrefs(context);
accessToken = sharedPrefs.getAccessToken();
}
public void get(String endpoint, String query) {
try {
getRequest(baseAPI + endpoint + query);
} catch(IOException e) {
e.printStackTrace();
}
}
public void put(String endpoint, String data) {
try {
putRequest(baseAPI + "account", data);
} catch(IOException e) {
e.printStackTrace();
}
}
public void delete(String endpoint, int item) {
try {
deleteRequest( "account", item);
} catch(IOException e) {
e.printStackTrace();
}
}
private void deleteRequest(String endpoint, int item) throws IOException {
OkHttpClient client = new OkHttpClient();
String itemid = String.format("%d",item);
RequestBody formBody = new FormBody.Builder()
.add("itemid", itemid)
.build();
Request request = new 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(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
call.cancel();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String theResponse = response.body().string();
try {
JSONObject json = new JSONObject(theResponse);
Log.d("DELETE Response",json.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
private void getRequest(String getUrl) throws IOException {
OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder()
.url(getUrl)
.addHeader("Authorization","Bearer " + accessToken)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
call.cancel();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String theResponse = response.body().string();
try {
JSONObject json = new JSONObject(theResponse);
Log.d("GET Response",json.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
private void putRequest(String getUrl, String data) throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, data);
Request request = new Request.Builder()
.url(getUrl)
.put(body)
.addHeader("Authorization","Bearer " + accessToken)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
call.cancel();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String theResponse = response.body().string();
try {
JSONObject json = new JSONObject(theResponse);
Log.d("PUT Response",json.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
package tech.essensys.operateapiexample;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
/**
* Created by paul on 15/08/2017.
*/
public class SharedPrefs extends Activity {
private static final String PREFS_NAME = "MyPrefsFile";
private final SharedPreferences preferences;
public SharedPrefs(Context context) {
preferences = PreferenceManager.getDefaultSharedPreferences(context);
}
public void setAccessToken(String accesstoken) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString("accessToken", accesstoken);
editor.apply();
}
public void setRefreshToken(String refreshtoken) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString("refreshToken", refreshtoken);
editor.apply();
}
public String getAccessToken() {
return preferences.getString("accessToken","");
}
}
<?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