Commit 7cb6e6b7 by Rémi Verschelde

Style: Apply clang-format to Java files

Only those from org/godotengine/godot though, not the thirdparty ones.
parent ce0f894b
......@@ -44,7 +44,6 @@ AllowShortIfStatementsOnASingleLine: true
BreakBeforeTernaryOperators: false
# BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: AfterColon
# BreakAfterJavaFieldAnnotations: false
# BreakStringLiterals: true
ColumnLimit: 0
# CommentPragmas: '^ IWYU pragma:'
......@@ -113,4 +112,8 @@ Language: ObjC
ObjCBlockIndentWidth: 4
# ObjCSpaceAfterProperty: false
# ObjCSpaceBeforeProtocolList: true
---
### Java specific config ###
Language: Java
# BreakAfterJavaFieldAnnotations: false
...
......@@ -31,7 +31,7 @@ PARSE_EXTS=true
# File types to parse. Only effective when PARSE_EXTS is true.
# FILE_EXTS=".c .h .cpp .hpp"
FILE_EXTS=".c .h .cpp .hpp .cc .hh .cxx .m .mm .inc"
FILE_EXTS=".c .h .cpp .hpp .cc .hh .cxx .m .mm .inc *.java"
# Use pygmentize instead of cat to parse diff with highlighting.
# Install it with `pip install pygments` (Linux) or `easy_install Pygments` (Mac)
......
......@@ -11,7 +11,7 @@ else
RANGE=HEAD
fi
FILES=$(git diff-tree --no-commit-id --name-only -r $RANGE | grep -v thirdparty/ | grep -E "\.(c|h|cpp|hpp|cc|hh|cxx|m|mm|inc)$")
FILES=$(git diff-tree --no-commit-id --name-only -r $RANGE | grep -v thirdparty/ | grep -E "\.(c|h|cpp|hpp|cc|hh|cxx|m|mm|inc|java)$")
echo "Checking files:\n$FILES"
# create a random filename to store our generated patch
......
......@@ -32,7 +32,6 @@ package org.godotengine.godot;
import java.util.HashMap;
import java.util.Set;
public class Dictionary extends HashMap<String, Object> {
protected String[] keys_cache;
......@@ -40,7 +39,7 @@ public class Dictionary extends HashMap<String, Object> {
public String[] get_keys() {
String[] ret = new String[size()];
int i=0;
int i = 0;
Set<String> keys = keySet();
for (String key : keys) {
......@@ -54,7 +53,7 @@ public class Dictionary extends HashMap<String, Object> {
public Object[] get_values() {
Object[] ret = new Object[size()];
int i=0;
int i = 0;
Set<String> keys = keySet();
for (String key : keys) {
......@@ -71,7 +70,7 @@ public class Dictionary extends HashMap<String, Object> {
public void set_values(Object[] vals) {
int i=0;
int i = 0;
for (String key : keys_cache) {
put(key, vals[i]);
i++;
......
......@@ -46,14 +46,14 @@ import android.util.Log;
*/
public class GodotDownloaderAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("GODOT", "Alarma recivida");
try {
DownloaderClientMarshaller.startDownloadServiceIfRequired(context, intent, GodotDownloaderService.class);
} catch (NameNotFoundException e) {
e.printStackTrace();
Log.d("GODOT", "Exception: " + e.getClass().getName() + ":" + e.getMessage());
@Override
public void onReceive(Context context, Intent intent) {
Log.d("GODOT", "Alarma recivida");
try {
DownloaderClientMarshaller.startDownloadServiceIfRequired(context, intent, GodotDownloaderService.class);
} catch (NameNotFoundException e) {
e.printStackTrace();
Log.d("GODOT", "Exception: " + e.getClass().getName() + ":" + e.getMessage());
}
}
}
}
......@@ -40,46 +40,45 @@ import com.google.android.vending.expansion.downloader.impl.DownloaderService;
* DownloaderService from the Downloader library.
*/
public class GodotDownloaderService extends DownloaderService {
// stuff for LVL -- MODIFY FOR YOUR APPLICATION!
private static final String BASE64_PUBLIC_KEY = "REPLACE THIS WITH YOUR PUBLIC KEY";
// used by the preference obfuscater
private static final byte[] SALT = new byte[] {
1, 43, -12, -1, 54, 98,
-100, -12, 43, 2, -8, -4, 9, 5, -106, -108, -33, 45, -1, 84
};
// stuff for LVL -- MODIFY FOR YOUR APPLICATION!
private static final String BASE64_PUBLIC_KEY = "REPLACE THIS WITH YOUR PUBLIC KEY";
// used by the preference obfuscater
private static final byte[] SALT = new byte[] {
1, 43, -12, -1, 54, 98,
-100, -12, 43, 2, -8, -4, 9, 5, -106, -108, -33, 45, -1, 84
};
/**
/**
* This public key comes from your Android Market publisher account, and it
* used by the LVL to validate responses from Market on your behalf.
*/
@Override
public String getPublicKey() {
SharedPreferences prefs = getApplicationContext().getSharedPreferences("app_data_keys", Context.MODE_PRIVATE);
Log.d("GODOT", "getting public key:" + prefs.getString("store_public_key", null));
return prefs.getString("store_public_key", null);
//return BASE64_PUBLIC_KEY;
}
@Override
public String getPublicKey() {
SharedPreferences prefs = getApplicationContext().getSharedPreferences("app_data_keys", Context.MODE_PRIVATE);
Log.d("GODOT", "getting public key:" + prefs.getString("store_public_key", null));
return prefs.getString("store_public_key", null);
/**
//return BASE64_PUBLIC_KEY;
}
/**
* This is used by the preference obfuscater to make sure that your
* obfuscated preferences are different than the ones used by other
* applications.
*/
@Override
public byte[] getSALT() {
return SALT;
}
@Override
public byte[] getSALT() {
return SALT;
}
/**
/**
* Fill this in with the class name for your alarm receiver. We do this
* because receivers must be unique across all of Android (it's a good idea
* to make sure that your receiver is in your unique package)
*/
@Override
public String getAlarmReceiverClassName() {
Log.d("GODOT", "getAlarmReceiverClassName()");
return GodotDownloaderAlarmReceiver.class.getName();
}
@Override
public String getAlarmReceiverClassName() {
Log.d("GODOT", "getAlarmReceiverClassName()");
return GodotDownloaderAlarmReceiver.class.getName();
}
}
......@@ -33,43 +33,41 @@ package org.godotengine.godot;
public class GodotLib {
public static GodotIO io;
public static GodotIO io;
static {
System.loadLibrary("godot_android");
}
static {
System.loadLibrary("godot_android");
}
/**
/**
* @param width the current view width
* @param height the current view height
*/
public static native void initialize(Godot p_instance,boolean need_reload_hook,Object p_asset_manager, boolean use_apk_expansion);
public static native void setup(String[] p_cmdline);
public static native void resize(int width, int height,boolean reload);
public static native void newcontext(boolean p_32_bits);
public static native void back();
public static native void step();
public static native void touch(int what,int pointer,int howmany, int[] arr);
public static native void accelerometer(float x, float y, float z);
public static native void gravity(float x, float y, float z);
public static native void magnetometer(float x, float y, float z);
public static native void gyroscope(float x, float y, float z);
public static native void key(int p_scancode, int p_unicode_char, boolean p_pressed);
public static native void joybutton(int p_device, int p_but, boolean p_pressed);
public static native void joyaxis(int p_device, int p_axis, float p_value);
public static native void joyhat(int p_device, int p_hat_x, int p_hat_y);
public static native void joyconnectionchanged(int p_device, boolean p_connected, String p_name);
public static native void focusin();
public static native void focusout();
public static native void audio();
public static native void singleton(String p_name,Object p_object);
public static native void method(String p_sname,String p_name,String p_ret,String[] p_params);
public static native String getGlobal(String p_key);
public static native void initialize(Godot p_instance, boolean need_reload_hook, Object p_asset_manager, boolean use_apk_expansion);
public static native void setup(String[] p_cmdline);
public static native void resize(int width, int height, boolean reload);
public static native void newcontext(boolean p_32_bits);
public static native void back();
public static native void step();
public static native void touch(int what, int pointer, int howmany, int[] arr);
public static native void accelerometer(float x, float y, float z);
public static native void gravity(float x, float y, float z);
public static native void magnetometer(float x, float y, float z);
public static native void gyroscope(float x, float y, float z);
public static native void key(int p_scancode, int p_unicode_char, boolean p_pressed);
public static native void joybutton(int p_device, int p_but, boolean p_pressed);
public static native void joyaxis(int p_device, int p_axis, float p_value);
public static native void joyhat(int p_device, int p_hat_x, int p_hat_y);
public static native void joyconnectionchanged(int p_device, boolean p_connected, String p_name);
public static native void focusin();
public static native void focusout();
public static native void audio();
public static native void singleton(String p_name, Object p_object);
public static native void method(String p_sname, String p_name, String p_ret, String[] p_params);
public static native String getGlobal(String p_key);
public static native void callobject(int p_ID, String p_method, Object[] p_params);
public static native void calldeferred(int p_ID, String p_method, Object[] p_params);
public static native void setVirtualKeyboardHeight(int p_height);
}
......@@ -40,7 +40,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GodotPaymentV3 extends Godot.SingletonBase {
private Godot activity;
......@@ -67,8 +66,8 @@ public class GodotPaymentV3 extends Godot.SingletonBase {
public GodotPaymentV3(Activity p_activity) {
registerClass("GodotPayments", new String[]{"purchase", "setPurchaseCallbackId", "setPurchaseValidationUrlPrefix", "setTransactionId", "getSignature", "consumeUnconsumedPurchases", "requestPurchased", "setAutoConsume", "consume", "querySkuDetails"});
activity = (Godot) p_activity;
registerClass("GodotPayments", new String[] { "purchase", "setPurchaseCallbackId", "setPurchaseValidationUrlPrefix", "setTransactionId", "getSignature", "consumeUnconsumedPurchases", "requestPurchased", "setAutoConsume", "consume", "querySkuDetails" });
activity = (Godot)p_activity;
mPaymentManager = activity.getPaymentsManager();
mPaymentManager.setBaseSingleton(this);
}
......@@ -89,32 +88,32 @@ public class GodotPaymentV3 extends Godot.SingletonBase {
}
public void callbackSuccess(String ticket, String signature, String sku) {
GodotLib.calldeferred(purchaseCallbackId, "purchase_success", new Object[]{ticket, signature, sku});
GodotLib.calldeferred(purchaseCallbackId, "purchase_success", new Object[] { ticket, signature, sku });
}
public void callbackSuccessProductMassConsumed(String ticket, String signature, String sku) {
Log.d(this.getClass().getName(), "callbackSuccessProductMassConsumed > " + ticket + "," + signature + "," + sku);
GodotLib.calldeferred(purchaseCallbackId, "consume_success", new Object[]{ticket, signature, sku});
GodotLib.calldeferred(purchaseCallbackId, "consume_success", new Object[] { ticket, signature, sku });
}
public void callbackSuccessNoUnconsumedPurchases() {
GodotLib.calldeferred(purchaseCallbackId, "consume_not_required", new Object[]{});
GodotLib.calldeferred(purchaseCallbackId, "consume_not_required", new Object[] {});
}
public void callbackFailConsume() {
GodotLib.calldeferred(purchaseCallbackId, "consume_fail", new Object[]{});
GodotLib.calldeferred(purchaseCallbackId, "consume_fail", new Object[] {});
}
public void callbackFail() {
GodotLib.calldeferred(purchaseCallbackId, "purchase_fail", new Object[]{});
GodotLib.calldeferred(purchaseCallbackId, "purchase_fail", new Object[] {});
}
public void callbackCancel() {
GodotLib.calldeferred(purchaseCallbackId, "purchase_cancel", new Object[]{});
GodotLib.calldeferred(purchaseCallbackId, "purchase_cancel", new Object[] {});
}
public void callbackAlreadyOwned(String sku) {
GodotLib.calldeferred(purchaseCallbackId, "purchase_owned", new Object[]{sku});
GodotLib.calldeferred(purchaseCallbackId, "purchase_owned", new Object[] { sku });
}
public int getPurchaseCallbackId() {
......@@ -161,7 +160,7 @@ public class GodotPaymentV3 extends Godot.SingletonBase {
// callback for requestPurchased()
public void callbackPurchased(String receipt, String signature, String sku) {
GodotLib.calldeferred(purchaseCallbackId, "has_purchased", new Object[]{receipt, signature, sku});
GodotLib.calldeferred(purchaseCallbackId, "has_purchased", new Object[] { receipt, signature, sku });
}
// consume item automatically after purchase. default is true.
......@@ -210,10 +209,10 @@ public class GodotPaymentV3 extends Godot.SingletonBase {
}
public void completeSkuDetail() {
GodotLib.calldeferred(purchaseCallbackId, "sku_details_complete", new Object[]{mSkuDetails});
GodotLib.calldeferred(purchaseCallbackId, "sku_details_complete", new Object[] { mSkuDetails });
}
public void errorSkuDetail(String errorMessage) {
GodotLib.calldeferred(purchaseCallbackId, "sku_details_error", new Object[]{errorMessage});
GodotLib.calldeferred(purchaseCallbackId, "sku_details_error", new Object[] { errorMessage });
}
}
......@@ -70,42 +70,37 @@ public class GodotEditText extends EditText {
super(context, attrs, defStyle);
this.initView();
}
protected void initView() {
this.setPadding(0, 0, 0, 0);
this.setPadding(0, 0, 0, 0);
this.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
sHandler = new Handler() {
@Override
public void handleMessage(final Message msg) {
switch (msg.what) {
case HANDLER_OPEN_IME_KEYBOARD:
{
GodotEditText edit = (GodotEditText) msg.obj;
String text = edit.mOriginText;
if (edit.requestFocus())
{
edit.removeTextChangedListener(edit.mInputWrapper);
edit.setText("");
edit.append(text);
edit.mInputWrapper.setOriginText(text);
edit.addTextChangedListener(edit.mInputWrapper);
final InputMethodManager imm = (InputMethodManager) mView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edit, 0);
}
case HANDLER_OPEN_IME_KEYBOARD: {
GodotEditText edit = (GodotEditText)msg.obj;
String text = edit.mOriginText;
if (edit.requestFocus()) {
edit.removeTextChangedListener(edit.mInputWrapper);
edit.setText("");
edit.append(text);
edit.mInputWrapper.setOriginText(text);
edit.addTextChangedListener(edit.mInputWrapper);
final InputMethodManager imm = (InputMethodManager)mView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edit, 0);
}
break;
case HANDLER_CLOSE_IME_KEYBOARD:
{
GodotEditText edit = (GodotEditText) msg.obj;
edit.removeTextChangedListener(mInputWrapper);
final InputMethodManager imm = (InputMethodManager) mView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edit.getWindowToken(), 0);
edit.mView.requestFocus();
}
break;
} break;
case HANDLER_CLOSE_IME_KEYBOARD: {
GodotEditText edit = (GodotEditText)msg.obj;
edit.removeTextChangedListener(mInputWrapper);
final InputMethodManager imm = (InputMethodManager)mView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edit.getWindowToken(), 0);
edit.mView.requestFocus();
} break;
}
}
};
......@@ -116,7 +111,7 @@ public class GodotEditText extends EditText {
// ===========================================================
public void setView(final GodotView view) {
this.mView = view;
if(mInputWrapper == null)
if (mInputWrapper == null)
mInputWrapper = new GodotTextInputWrapper(mView, this);
this.setOnEditorActionListener(mInputWrapper);
view.requestFocus();
......@@ -125,7 +120,7 @@ public class GodotEditText extends EditText {
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
@Override
public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) {
super.onKeyDown(keyCode, keyEvent);
......@@ -142,7 +137,7 @@ public class GodotEditText extends EditText {
// ===========================================================
public void showKeyboard(String p_existing_text) {
this.mOriginText = p_existing_text;
final Message msg = new Message();
msg.what = HANDLER_OPEN_IME_KEYBOARD;
msg.obj = this;
......@@ -155,7 +150,7 @@ public class GodotEditText extends EditText {
msg.obj = this;
sHandler.sendMessage(msg);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
......
......@@ -67,7 +67,7 @@ public class GodotTextInputWrapper implements TextWatcher, OnEditorActionListene
private boolean isFullScreenEdit() {
final TextView textField = this.mEdit;
final InputMethodManager imm = (InputMethodManager) textField.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
final InputMethodManager imm = (InputMethodManager)textField.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
return imm.isFullscreenMode();
}
......@@ -81,7 +81,6 @@ public class GodotTextInputWrapper implements TextWatcher, OnEditorActionListene
@Override
public void afterTextChanged(final Editable s) {
}
@Override
......
......@@ -23,118 +23,118 @@ import android.view.InputDevice;
import android.view.MotionEvent;
public interface InputManagerCompat {
/**
* Gets information about the input device with the specified id.
*
* @param id The device id
* @return The input device or null if not found
*/
public InputDevice getInputDevice(int id);
/**
* Gets information about the input device with the specified id.
*
* @param id The device id
* @return The input device or null if not found
*/
public InputDevice getInputDevice(int id);
/**
* Gets the ids of all input devices in the system.
*
* @return The input device ids.
*/
public int[] getInputDeviceIds();
/**
* Gets the ids of all input devices in the system.
*
* @return The input device ids.
*/
public int[] getInputDeviceIds();
/**
* Registers an input device listener to receive notifications about when
* input devices are added, removed or changed.
*
* @param listener The listener to register.
* @param handler The handler on which the listener should be invoked, or
* null if the listener should be invoked on the calling thread's
* looper.
*/
public void registerInputDeviceListener(InputManagerCompat.InputDeviceListener listener,
Handler handler);
/**
* Registers an input device listener to receive notifications about when
* input devices are added, removed or changed.
*
* @param listener The listener to register.
* @param handler The handler on which the listener should be invoked, or
* null if the listener should be invoked on the calling thread's
* looper.
*/
public void registerInputDeviceListener(InputManagerCompat.InputDeviceListener listener,
Handler handler);
/**
* Unregisters an input device listener.
*
* @param listener The listener to unregister.
*/
public void unregisterInputDeviceListener(InputManagerCompat.InputDeviceListener listener);
/**
* Unregisters an input device listener.
*
* @param listener The listener to unregister.
*/
public void unregisterInputDeviceListener(InputManagerCompat.InputDeviceListener listener);
/*
* The following three calls are to simulate V16 behavior on pre-Jellybean
* devices. If you don't call them, your callback will never be called
* pre-API 16.
*/
/*
* The following three calls are to simulate V16 behavior on pre-Jellybean
* devices. If you don't call them, your callback will never be called
* pre-API 16.
*/
/**
* Pass the motion events to the InputManagerCompat. This is used to
* optimize for polling for controllers. If you do not pass these events in,
* polling will cause regular object creation.
*
* @param event the motion event from the app
*/
public void onGenericMotionEvent(MotionEvent event);
/**
* Pass the motion events to the InputManagerCompat. This is used to
* optimize for polling for controllers. If you do not pass these events in,
* polling will cause regular object creation.
*
* @param event the motion event from the app
*/
public void onGenericMotionEvent(MotionEvent event);
/**
* Tell the V9 input manager that it should stop polling for disconnected
* devices. You can call this during onPause in your activity, although you
* might want to call it whenever your game is not active (or whenever you
* don't care about being notified of new input devices)
*/
public void onPause();
/**
* Tell the V9 input manager that it should stop polling for disconnected
* devices. You can call this during onPause in your activity, although you
* might want to call it whenever your game is not active (or whenever you
* don't care about being notified of new input devices)
*/
public void onPause();
/**
* Tell the V9 input manager that it should start polling for disconnected
* devices. You can call this during onResume in your activity, although you
* might want to call it less often (only when the gameplay is actually
* active)
*/
public void onResume();
/**
* Tell the V9 input manager that it should start polling for disconnected
* devices. You can call this during onResume in your activity, although you
* might want to call it less often (only when the gameplay is actually
* active)
*/
public void onResume();
public interface InputDeviceListener {
/**
* Called whenever the input manager detects that a device has been
* added. This will only be called in the V9 version when a motion event
* is detected.
*
* @param deviceId The id of the input device that was added.
*/
void onInputDeviceAdded(int deviceId);
public interface InputDeviceListener {
/**
* Called whenever the input manager detects that a device has been
* added. This will only be called in the V9 version when a motion event
* is detected.
*
* @param deviceId The id of the input device that was added.
*/
void onInputDeviceAdded(int deviceId);
/**
* Called whenever the properties of an input device have changed since
* they were last queried. This will not be called for the V9 version of
* the API.
*
* @param deviceId The id of the input device that changed.
*/
void onInputDeviceChanged(int deviceId);
/**
* Called whenever the properties of an input device have changed since
* they were last queried. This will not be called for the V9 version of
* the API.
*
* @param deviceId The id of the input device that changed.
*/
void onInputDeviceChanged(int deviceId);
/**
* Called whenever the input manager detects that a device has been
* removed. For the V9 version, this can take some time depending on the
* poll rate.
*
* @param deviceId The id of the input device that was removed.
*/
void onInputDeviceRemoved(int deviceId);
}
/**
* Called whenever the input manager detects that a device has been
* removed. For the V9 version, this can take some time depending on the
* poll rate.
*
* @param deviceId The id of the input device that was removed.
*/
void onInputDeviceRemoved(int deviceId);
}
/**
* Use this to construct a compatible InputManager.
*/
public static class Factory {
/**
* Use this to construct a compatible InputManager.
*/
public static class Factory {
/**
* Constructs and returns a compatible InputManger
*
* @param context the Context that will be used to get the system
* service from
* @return a compatible implementation of InputManager
*/
public static InputManagerCompat getInputManager(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
return new InputManagerV16(context);
} else {
return new InputManagerV9();
}
}
}
/**
* Constructs and returns a compatible InputManger
*
* @param context the Context that will be used to get the system
* service from
* @return a compatible implementation of InputManager
*/
public static InputManagerCompat getInputManager(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
return new InputManagerV16(context);
} else {
return new InputManagerV9();
}
}
}
}
......@@ -30,78 +30,74 @@ import java.util.Map;
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class InputManagerV16 implements InputManagerCompat {
private final InputManager mInputManager;
private final Map<InputManagerCompat.InputDeviceListener, V16InputDeviceListener> mListeners;
public InputManagerV16(Context context) {
mInputManager = (InputManager) context.getSystemService(Context.INPUT_SERVICE);
mListeners = new HashMap<InputManagerCompat.InputDeviceListener, V16InputDeviceListener>();
}
@Override
public InputDevice getInputDevice(int id) {
return mInputManager.getInputDevice(id);
}
@Override
public int[] getInputDeviceIds() {
return mInputManager.getInputDeviceIds();
}
static class V16InputDeviceListener implements InputManager.InputDeviceListener {
final InputManagerCompat.InputDeviceListener mIDL;
public V16InputDeviceListener(InputDeviceListener idl) {
mIDL = idl;
}
@Override
public void onInputDeviceAdded(int deviceId) {
mIDL.onInputDeviceAdded(deviceId);
}
@Override
public void onInputDeviceChanged(int deviceId) {
mIDL.onInputDeviceChanged(deviceId);
}
@Override
public void onInputDeviceRemoved(int deviceId) {
mIDL.onInputDeviceRemoved(deviceId);
}
}
@Override
public void registerInputDeviceListener(InputDeviceListener listener, Handler handler) {
V16InputDeviceListener v16Listener = new V16InputDeviceListener(listener);
mInputManager.registerInputDeviceListener(v16Listener, handler);
mListeners.put(listener, v16Listener);
}
@Override
public void unregisterInputDeviceListener(InputDeviceListener listener) {
V16InputDeviceListener curListener = mListeners.remove(listener);
if (null != curListener)
{
mInputManager.unregisterInputDeviceListener(curListener);
}
}
@Override
public void onGenericMotionEvent(MotionEvent event) {
// unused in V16
}
@Override
public void onPause() {
// unused in V16
}
@Override
public void onResume() {
// unused in V16
}
private final InputManager mInputManager;
private final Map<InputManagerCompat.InputDeviceListener, V16InputDeviceListener> mListeners;
public InputManagerV16(Context context) {
mInputManager = (InputManager)context.getSystemService(Context.INPUT_SERVICE);
mListeners = new HashMap<InputManagerCompat.InputDeviceListener, V16InputDeviceListener>();
}
@Override
public InputDevice getInputDevice(int id) {
return mInputManager.getInputDevice(id);
}
@Override
public int[] getInputDeviceIds() {
return mInputManager.getInputDeviceIds();
}
static class V16InputDeviceListener implements InputManager.InputDeviceListener {
final InputManagerCompat.InputDeviceListener mIDL;
public V16InputDeviceListener(InputDeviceListener idl) {
mIDL = idl;
}
@Override
public void onInputDeviceAdded(int deviceId) {
mIDL.onInputDeviceAdded(deviceId);
}
@Override
public void onInputDeviceChanged(int deviceId) {
mIDL.onInputDeviceChanged(deviceId);
}
@Override
public void onInputDeviceRemoved(int deviceId) {
mIDL.onInputDeviceRemoved(deviceId);
}
}
@Override
public void registerInputDeviceListener(InputDeviceListener listener, Handler handler) {
V16InputDeviceListener v16Listener = new V16InputDeviceListener(listener);
mInputManager.registerInputDeviceListener(v16Listener, handler);
mListeners.put(listener, v16Listener);
}
@Override
public void unregisterInputDeviceListener(InputDeviceListener listener) {
V16InputDeviceListener curListener = mListeners.remove(listener);
if (null != curListener) {
mInputManager.unregisterInputDeviceListener(curListener);
}
}
@Override
public void onGenericMotionEvent(MotionEvent event) {
// unused in V16
}
@Override
public void onPause() {
// unused in V16
}
@Override
public void onResume() {
// unused in V16
}
}
......@@ -39,33 +39,32 @@ import android.util.Log;
abstract public class ConsumeTask {
private Context context;
private IInAppBillingService mService;
public ConsumeTask(IInAppBillingService mService, Context context ){
public ConsumeTask(IInAppBillingService mService, Context context) {
this.context = context;
this.mService = mService;
}
public void consume(final String sku){
public void consume(final String sku) {
//Log.d("XXX", "Consuming product " + sku);
PaymentsCache pc = new PaymentsCache(context);
Boolean isBlocked = pc.getConsumableFlag("block", sku);
String _token = pc.getConsumableValue("token", sku);
//Log.d("XXX", "token " + _token);
if(!isBlocked && _token == null){
//Log.d("XXX", "token " + _token);
if (!isBlocked && _token == null) {
//_token = "inapp:"+context.getPackageName()+":android.test.purchased";
//Log.d("XXX", "Consuming product " + sku + " with token " + _token);
}else if(!isBlocked){
} else if (!isBlocked) {
//Log.d("XXX", "It is not blocked ¿?");
return;
}else if(_token == null){
} else if (_token == null) {
//Log.d("XXX", "No token available");
this.error("No token for sku:" + sku);
return;
}
final String token = _token;
new AsyncTask<String, String, String>(){
new AsyncTask<String, String, String>() {
@Override
protected String doInBackground(String... params) {
......@@ -73,28 +72,27 @@ abstract public class ConsumeTask {
//Log.d("XXX", "Requesting to release item.");
int response = mService.consumePurchase(3, context.getPackageName(), token);
//Log.d("XXX", "release response code: " + response);
if(response == 0 || response == 8){
if (response == 0 || response == 8) {
return null;
}
} catch (RemoteException e) {
return e.getMessage();
}
return "Some error";
}
protected void onPostExecute(String param){
if(param == null){
success( new PaymentsCache(context).getConsumableValue("ticket", sku) );
}else{
protected void onPostExecute(String param) {
if (param == null) {
success(new PaymentsCache(context).getConsumableValue("ticket", sku));
} else {
error(param);
}
}
}.execute();
}
.execute();
}
abstract protected void success(String ticket);
abstract protected void error(String message);
}
......@@ -36,15 +36,12 @@ import android.os.AsyncTask;
import android.os.RemoteException;
import android.util.Log;
abstract public class GenericConsumeTask extends AsyncTask<String, String, String>{
abstract public class GenericConsumeTask extends AsyncTask<String, String, String> {
private Context context;
private IInAppBillingService mService;
public GenericConsumeTask(Context context, IInAppBillingService mService, String sku, String receipt, String signature, String token){
public GenericConsumeTask(Context context, IInAppBillingService mService, String sku, String receipt, String signature, String token) {
this.context = context;
this.mService = mService;
this.sku = sku;
......@@ -52,19 +49,19 @@ abstract public class GenericConsumeTask extends AsyncTask<String, String, Strin
this.signature = signature;
this.token = token;
}
private String sku;
private String receipt;
private String signature;
private String token;
@Override
protected String doInBackground(String... params) {
try {
//Log.d("godot", "Requesting to consume an item with token ." + token);
int response = mService.consumePurchase(3, context.getPackageName(), token);
//Log.d("godot", "consumePurchase response: " + response);
if(response == 0 || response == 8){
if (response == 0 || response == 8) {
return null;
}
} catch (Exception e) {
......@@ -72,11 +69,10 @@ abstract public class GenericConsumeTask extends AsyncTask<String, String, Strin
}
return null;
}
protected void onPostExecute(String sarasa){
protected void onPostExecute(String sarasa) {
onSuccess(sku, receipt, signature, token);
}
abstract public void onSuccess(String sku, String receipt, String signature, String token);
abstract public void onSuccess(String sku, String receipt, String signature, String token);
}
......@@ -50,28 +50,26 @@ import android.util.Log;
abstract public class HandlePurchaseTask {
private Activity context;
public HandlePurchaseTask(Activity context ){
public HandlePurchaseTask(Activity context) {
this.context = context;
}
public void handlePurchaseRequest(int resultCode, Intent data){
public void handlePurchaseRequest(int resultCode, Intent data) {
//Log.d("XXX", "Handling purchase response");
//int responseCode = data.getIntExtra("RESPONSE_CODE", 0);
PaymentsCache pc = new PaymentsCache(context);
String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
//Log.d("XXX", "Purchase data:" + purchaseData);
String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");
//Log.d("XXX", "Purchase signature:" + dataSignature);
if (resultCode == Activity.RESULT_OK) {
try {
//Log.d("SARLANGA", purchaseData);
JSONObject jo = new JSONObject(purchaseData);
//String sku = jo.getString("productId");
//alert("You have bought the " + sku + ". Excellent choice, aventurer!");
......@@ -82,8 +80,8 @@ abstract public class HandlePurchaseTask {
//Integer state = jo.getInt("purchaseState");
String developerPayload = jo.getString("developerPayload");
String purchaseToken = jo.getString("purchaseToken");
if(! pc.getConsumableValue("validation_hash", productId).equals(developerPayload) ) {
if (!pc.getConsumableValue("validation_hash", productId).equals(developerPayload)) {
error("Untrusted callback");
return;
}
......@@ -92,13 +90,13 @@ abstract public class HandlePurchaseTask {
pc.setConsumableValue("ticket", productId, purchaseData);
pc.setConsumableFlag("block", productId, true);
pc.setConsumableValue("token", productId, purchaseToken);
success(productId, dataSignature, purchaseData);
return;
} catch (JSONException e) {
} catch (JSONException e) {
error(e.getMessage());
}
}else if( resultCode == Activity.RESULT_CANCELED){
} else if (resultCode == Activity.RESULT_CANCELED) {
canceled();
}
}
......@@ -106,6 +104,4 @@ abstract public class HandlePurchaseTask {
abstract protected void success(String sku, String signature, String ticket);
abstract protected void error(String message);
abstract protected void canceled();
}
......@@ -34,41 +34,38 @@ import android.content.SharedPreferences;
import android.util.Log;
public class PaymentsCache {
public Context context;
public PaymentsCache(Context context){
public PaymentsCache(Context context) {
this.context = context;
}
public void setConsumableFlag(String set, String sku, Boolean flag){
SharedPreferences sharedPref = context.getSharedPreferences("consumables_" + set, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(sku, flag);
editor.commit();
}
public boolean getConsumableFlag(String set, String sku){
SharedPreferences sharedPref = context.getSharedPreferences(
"consumables_" + set, Context.MODE_PRIVATE);
return sharedPref.getBoolean(sku, false);
public void setConsumableFlag(String set, String sku, Boolean flag) {
SharedPreferences sharedPref = context.getSharedPreferences("consumables_" + set, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(sku, flag);
editor.commit();
}
public boolean getConsumableFlag(String set, String sku) {
SharedPreferences sharedPref = context.getSharedPreferences(
"consumables_" + set, Context.MODE_PRIVATE);
return sharedPref.getBoolean(sku, false);
}
public void setConsumableValue(String set, String sku, String value){
SharedPreferences sharedPref = context.getSharedPreferences("consumables_" + set, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(sku, value);
public void setConsumableValue(String set, String sku, String value) {
SharedPreferences sharedPref = context.getSharedPreferences("consumables_" + set, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(sku, value);
//Log.d("XXX", "Setting asset: consumables_" + set + ":" + sku);
editor.commit();
editor.commit();
}
public String getConsumableValue(String set, String sku){
SharedPreferences sharedPref = context.getSharedPreferences(
"consumables_" + set, Context.MODE_PRIVATE);
public String getConsumableValue(String set, String sku) {
SharedPreferences sharedPref = context.getSharedPreferences(
"consumables_" + set, Context.MODE_PRIVATE);
//Log.d("XXX", "Getting asset: consumables_" + set + ":" + sku);
return sharedPref.getString(sku, null);
return sharedPref.getString(sku, null);
}
}
......@@ -106,7 +106,6 @@ public class PaymentsManager {
@Override
protected void error(String message) {
godotPaymentV3.callbackFail();
}
@Override
......@@ -119,8 +118,8 @@ public class PaymentsManager {
godotPaymentV3.callbackAlreadyOwned(sku);
}
}.purchase(sku, transactionId);
}
.purchase(sku, transactionId);
}
public void consumeUnconsumedPurchases() {
......@@ -135,16 +134,15 @@ public class PaymentsManager {
protected void error(String message) {
Log.d("godot", "consumeUnconsumedPurchases :" + message);
godotPaymentV3.callbackFailConsume();
}
@Override
protected void notRequired() {
Log.d("godot", "callbackSuccessNoUnconsumedPurchases :");
godotPaymentV3.callbackSuccessNoUnconsumedPurchases();
}
}.consumeItAll();
}
.consumeItAll();
}
public void requestPurchased() {
......@@ -210,9 +208,9 @@ public class PaymentsManager {
@Override
protected void error(String message) {
godotPaymentV3.callbackFail();
}
}.consume(sku);
}
.consume(sku);
}
}
......@@ -225,7 +223,8 @@ public class PaymentsManager {
protected void canceled() {
godotPaymentV3.callbackCancel();
}
}.handlePurchaseRequest(resultCode, data);
}
.handlePurchaseRequest(resultCode, data);
}
public void validatePurchase(String purchaseToken, final String sku) {
......@@ -246,8 +245,8 @@ public class PaymentsManager {
protected void error(String message) {
godotPaymentV3.callbackFail();
}
}.consume(sku);
}
.consume(sku);
}
@Override
......@@ -259,7 +258,8 @@ public class PaymentsManager {
protected void canceled() {
godotPaymentV3.callbackCancel();
}
}.validatePurchase(sku);
}
.validatePurchase(sku);
}
public void setAutoConsume(boolean autoConsume) {
......@@ -278,7 +278,8 @@ public class PaymentsManager {
protected void error(String message) {
godotPaymentV3.callbackFailConsume();
}
}.consume(sku);
}
.consume(sku);
}
// Workaround to bug where sometimes response codes come as Long instead of Integer
......@@ -287,8 +288,10 @@ public class PaymentsManager {
if (o == null) {
//logDebug("Bundle with null response code, assuming OK (known issue)");
return BILLING_RESPONSE_RESULT_OK;
} else if (o instanceof Integer) return ((Integer) o).intValue();
else if (o instanceof Long) return (int) ((Long) o).longValue();
} else if (o instanceof Integer)
return ((Integer)o).intValue();
else if (o instanceof Long)
return (int)((Long)o).longValue();
else {
//logError("Unexpected type for bundle response code.");
//logError(o.getClass().getName());
......@@ -304,25 +307,41 @@ public class PaymentsManager {
* It also includes the result code numerically.
*/
public static String getResponseDesc(int code) {
String[] iab_msgs = ("0:OK/1:User Canceled/2:Unknown/" +
"3:Billing Unavailable/4:Item unavailable/" +
"5:Developer Error/6:Error/7:Item Already Owned/" +
"8:Item not owned").split("/");
String[] iabhelper_msgs = ("0:OK/-1001:Remote exception during initialization/" +
"-1002:Bad response received/" +
"-1003:Purchase signature verification failed/" +
"-1004:Send intent failed/" +
"-1005:User cancelled/" +
"-1006:Unknown purchase response/" +
"-1007:Missing token/" +
"-1008:Unknown error/" +
"-1009:Subscriptions not available/" +
"-1010:Invalid consumption attempt").split("/");
String[] iab_msgs = ("0:OK/1:User Canceled/2:Unknown/"
+
"3:Billing Unavailable/4:Item unavailable/"
+
"5:Developer Error/6:Error/7:Item Already Owned/"
+
"8:Item not owned")
.split("/");
String[] iabhelper_msgs = ("0:OK/-1001:Remote exception during initialization/"
+
"-1002:Bad response received/"
+
"-1003:Purchase signature verification failed/"
+
"-1004:Send intent failed/"
+
"-1005:User cancelled/"
+
"-1006:Unknown purchase response/"
+
"-1007:Missing token/"
+
"-1008:Unknown error/"
+
"-1009:Subscriptions not available/"
+
"-1010:Invalid consumption attempt")
.split("/");
if (code <= -1000) {
int index = -1000 - code;
if (index >= 0 && index < iabhelper_msgs.length) return iabhelper_msgs[index];
else return String.valueOf(code) + ":Unknown IAB Helper Error";
if (index >= 0 && index < iabhelper_msgs.length)
return iabhelper_msgs[index];
else
return String.valueOf(code) + ":Unknown IAB Helper Error";
} else if (code < 0 || code >= iab_msgs.length)
return String.valueOf(code) + ":Unknown";
else
......@@ -375,7 +394,7 @@ public class PaymentsManager {
ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST");
for (String thisResponse : responseList) {
Log.d("godot", "response = "+thisResponse);
Log.d("godot", "response = " + thisResponse);
godotPaymentV3.addSkuDetail(thisResponse);
}
} catch (RemoteException e) {
......@@ -385,7 +404,8 @@ public class PaymentsManager {
}
godotPaymentV3.completeSkuDetail();
}
})).start();
}))
.start();
}
private GodotPaymentV3 godotPaymentV3;
......@@ -393,5 +413,4 @@ public class PaymentsManager {
public void setBaseSingleton(GodotPaymentV3 godotPaymentV3) {
this.godotPaymentV3 = godotPaymentV3;
}
}
......@@ -50,17 +50,16 @@ import android.util.Log;
abstract public class PurchaseTask {
private Activity context;
private IInAppBillingService mService;
public PurchaseTask(IInAppBillingService mService, Activity context ){
public PurchaseTask(IInAppBillingService mService, Activity context) {
this.context = context;
this.mService = mService;
}
private boolean isLooping = false;
public void purchase(final String sku, final String transactionId){
public void purchase(final String sku, final String transactionId) {
Log.d("XXX", "Starting purchase for: " + sku);
PaymentsCache pc = new PaymentsCache(context);
Boolean isBlocked = pc.getConsumableFlag("block", sku);
......@@ -75,7 +74,7 @@ abstract public class PurchaseTask {
Bundle buyIntentBundle;
try {
buyIntentBundle = mService.getBuyIntent(3, context.getApplicationContext().getPackageName(), sku, "inapp", hash );
buyIntentBundle = mService.getBuyIntent(3, context.getApplicationContext().getPackageName(), sku, "inapp", hash);
} catch (RemoteException e) {
//Log.d("XXX", "Error: " + e.getMessage());
error(e.getMessage());
......@@ -83,50 +82,45 @@ abstract public class PurchaseTask {
}
Object rc = buyIntentBundle.get("RESPONSE_CODE");
int responseCode = 0;
if(rc == null){
if (rc == null) {
responseCode = PaymentsManager.BILLING_RESPONSE_RESULT_OK;
}else if( rc instanceof Integer){
} else if (rc instanceof Integer) {
responseCode = ((Integer)rc).intValue();
}else if( rc instanceof Long){
} else if (rc instanceof Long) {
responseCode = (int)((Long)rc).longValue();
}
//Log.d("XXX", "Buy intent response code: " + responseCode);
if(responseCode == 1 || responseCode == 3 || responseCode == 4){
if (responseCode == 1 || responseCode == 3 || responseCode == 4) {
canceled();
return;
}
if(responseCode == 7){
if (responseCode == 7) {
alreadyOwned();
return;
}
PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
pc.setConsumableValue("validation_hash", sku, hash);
try {
if(context == null){
if (context == null) {
//Log.d("XXX", "No context!");
}
if(pendingIntent == null){
if (pendingIntent == null) {
//Log.d("XXX", "No pending intent");
}
//Log.d("XXX", "Starting activity for purchase!");
context.startIntentSenderForResult(
pendingIntent.getIntentSender(),
PaymentsManager.REQUEST_CODE_FOR_PURCHASE,
new Intent(),
PaymentsManager.REQUEST_CODE_FOR_PURCHASE,
new Intent(),
Integer.valueOf(0), Integer.valueOf(0),
Integer.valueOf(0));
Integer.valueOf(0));
} catch (SendIntentException e) {
error(e.getMessage());
}
}
abstract protected void error(String message);
abstract protected void canceled();
abstract protected void alreadyOwned();
}
......@@ -48,69 +48,63 @@ abstract public class ReleaseAllConsumablesTask {
private Context context;
private IInAppBillingService mService;
public ReleaseAllConsumablesTask(IInAppBillingService mService, Context context ){
public ReleaseAllConsumablesTask(IInAppBillingService mService, Context context) {
this.context = context;
this.mService = mService;
}
public void consumeItAll(){
try{
public void consumeItAll() {
try {
//Log.d("godot", "consumeItall for " + context.getPackageName());
Bundle bundle = mService.getPurchases(3, context.getPackageName(), "inapp",null);
Bundle bundle = mService.getPurchases(3, context.getPackageName(), "inapp", null);
for (String key : bundle.keySet()) {
Object value = bundle.get(key);
//Log.d("godot", String.format("%s %s (%s)", key,
//value.toString(), value.getClass().getName()));
}
if (bundle.getInt("RESPONSE_CODE") == 0){
if (bundle.getInt("RESPONSE_CODE") == 0) {
final ArrayList<String> myPurchases = bundle.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
final ArrayList<String> mySignatures = bundle.getStringArrayList("INAPP_DATA_SIGNATURE_LIST");
if (myPurchases == null || myPurchases.size() == 0){
if (myPurchases == null || myPurchases.size() == 0) {
//Log.d("godot", "No purchases!");
notRequired();
return;
}
//Log.d("godot", "# products to be consumed:" + myPurchases.size());
for (int i=0;i<myPurchases.size();i++)
{
try{
for (int i = 0; i < myPurchases.size(); i++) {
try {
String receipt = myPurchases.get(i);
JSONObject inappPurchaseData = new JSONObject(receipt);
String sku = inappPurchaseData.getString("productId");
String token = inappPurchaseData.getString("purchaseToken");
String signature = mySignatures.get(i);
//Log.d("godot", "A punto de consumir un item con token:" + token + "\n" + receipt);
new GenericConsumeTask(context, mService, sku, receipt,signature, token) {
new GenericConsumeTask(context, mService, sku, receipt, signature, token) {
@Override
public void onSuccess(String sku, String receipt, String signature, String token) {
ReleaseAllConsumablesTask.this.success(sku, receipt, signature, token);
}
}.execute();
}
.execute();
} catch (JSONException e) {
}
}
}
}catch(Exception e){
} catch (Exception e) {
Log.d("godot", "Error releasing products:" + e.getClass().getName() + ":" + e.getMessage());
}
}
abstract protected void success(String sku, String receipt, String signature, String token);
abstract protected void error(String message);
abstract protected void notRequired();
}
......@@ -55,22 +55,21 @@ abstract public class ValidateTask {
private Activity context;
private GodotPaymentV3 godotPaymentsV3;
public ValidateTask(Activity context, GodotPaymentV3 godotPaymentsV3){
public ValidateTask(Activity context, GodotPaymentV3 godotPaymentsV3) {
this.context = context;
this.godotPaymentsV3 = godotPaymentsV3;
}
public void validatePurchase(final String sku){
new AsyncTask<String, String, String>(){
public void validatePurchase(final String sku) {
new AsyncTask<String, String, String>() {
private ProgressDialog dialog;
@Override
protected void onPreExecute(){
protected void onPreExecute() {
dialog = ProgressDialog.show(context, null, "Please wait...");
}
@Override
protected String doInBackground(String... params) {
PaymentsCache pc = new PaymentsCache(context);
......@@ -90,37 +89,34 @@ abstract public class ValidateTask {
//Log.d("XXX", "Validation response:\n"+jsonResponse);
return jsonResponse;
}
@Override
protected void onPostExecute(String response){
if(dialog != null){
protected void onPostExecute(String response) {
if (dialog != null) {
dialog.dismiss();
}
JSONObject j;
try {
j = new JSONObject(response);
if(j.getString("status").equals("OK")){
if (j.getString("status").equals("OK")) {
success();
return;
}else if(j.getString("status") != null){
} else if (j.getString("status") != null) {
error(j.getString("message"));
}else{
} else {
error("Connection error");
}
} catch (JSONException e) {
error(e.getMessage());
}catch (Exception e){
} catch (Exception e) {
error(e.getMessage());
}
}
}.execute();
}
.execute();
}
abstract protected void success();
abstract protected void error(String message);
abstract protected void canceled();
}
......@@ -34,34 +34,34 @@ import java.util.Random;
public class Crypt {
public static String md5(String input){
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(input.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
for (int i=0; i<messageDigest.length; i++)
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
return hexString.toString();
} catch (Exception e) {
e.printStackTrace();
}
return "";
public static String md5(String input) {
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(input.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++)
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
return hexString.toString();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static String createRandomHash(){
public static String createRandomHash() {
return md5(Long.toString(createRandomLong()));
}
public static long createAbsRandomLong(){
public static long createAbsRandomLong() {
return Math.abs(createRandomLong());
}
public static long createRandomLong(){
public static long createRandomLong() {
Random r = new Random();
return r.nextLong();
}
......
......@@ -42,30 +42,29 @@ import javax.net.ssl.TrustManagerFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
/**
*
* @author Luis Linietsky <luis.linietsky@gmail.com>
*/
public class CustomSSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
SSLContext sslContext = SSLContext.getInstance("TLS");
public CustomSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
public CustomSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(truststore);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(truststore);
sslContext.init(null, tmf.getTrustManagers(), null);
}
sslContext.init(null, tmf.getTrustManagers(), null);
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}
......@@ -43,33 +43,33 @@ import org.apache.http.message.BasicNameValuePair;
*/
public class RequestParams {
private HashMap<String,String> params;
private HashMap<String, String> params;
private String url;
public RequestParams(){
params = new HashMap<String,String>();
public RequestParams() {
params = new HashMap<String, String>();
}
public void put(String key, String value){
public void put(String key, String value) {
params.put(key, value);
}
public String get(String key){
public String get(String key) {
return params.get(key);
}
public void remove(Object key){
public void remove(Object key) {
params.remove(key);
}
public boolean has(String key){
public boolean has(String key) {
return params.containsKey(key);
}
public List<NameValuePair> toPairsList(){
List<NameValuePair> fields = new ArrayList<NameValuePair>();
for(String key : params.keySet()){
public List<NameValuePair> toPairsList() {
List<NameValuePair> fields = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
fields.add(new BasicNameValuePair(key, this.get(key)));
}
return fields;
......@@ -82,6 +82,4 @@ public class RequestParams {
public void setUrl(String url) {
this.url = url;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment