repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
captain-miao/bleYan
example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/fragment/OpenSourceFragment.java
// Path: example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/constant/AppConstants.java // public class AppConstants { // // public static final String KEY_MODEL = "key_model"; // public static final String KEY_STATUS = "key_status"; // public static final String KEY_TITLE = "key_title"; // public static final String KEY_ID = "key_id"; // public static final String KEY_IS_BOOLEAN = "key_boolean"; // // public static final String KEY_BLE_DEVICE = "key_ble_device"; // public static final String KEY_BLE_SERVICE = "key_ble_service"; // public static final String KEY_BLE_CHARACTERISTIC = "key_ble_characteristic"; // // public static final int PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 69; // } // // Path: supportsdk/src/main/java/com/github/captain_miao/android/supportsdk/utils/DeviceUtilsLite.java // public class DeviceUtilsLite { // // public static String getDeviceUniqueId(Context context) { // String uid = ""; // if (context != null) { // try { // TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); // String did = tm.getDeviceId(); // String sid = tm.getSubscriberId(); // // if (did != null && !did.equals("")) { // uid += did; // } // if (sid != null && !sid.equals("")) { // uid += "_" + sid; // } // if (uid.equals("")) { // uid = "unknown"; // } // } catch (Exception e) { // // } // } // return uid; // } // // public static int getAppVersionCode(Context context, String filePath) { // int versionCode = 0; // if (context != null) { // try { // PackageInfo pi = context.getPackageManager().getPackageArchiveInfo(filePath, 0); // versionCode = pi.versionCode; // } catch (Exception e) { // // } // } // return versionCode; // } // // public static int getAppVersionCode(Context context) { // return getAppVersionCode(context, (ApplicationInfo) null); // } // // public static int getAppVersionCode(Context context, ApplicationInfo info) { // int versionCode = 0; // if (context != null) { // String packageName = ""; // if (info != null) { // packageName = info.packageName; // } else { // packageName = context.getPackageName(); // } // try { // PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, 0); // versionCode = pi.versionCode; // } catch (Exception e) { // // } // } // return versionCode; // } // // public static String getAppVersionName(Context context) { // return getAppVersionName(context, null); // } // // public static String getAppVersionName(Context context, ApplicationInfo info) { // String versionName = ""; // if (context != null) { // String packageName = ""; // if (info != null) { // packageName = info.packageName; // } else { // packageName = context.getPackageName(); // } // try { // PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, 0); // versionName = pi.versionName; // // } catch (Exception e) { // // } // } // return versionName; // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.github.captain_miao.android.bluetoothletutorial.R; import com.github.captain_miao.android.bluetoothletutorial.constant.AppConstants; import com.github.captain_miao.android.supportsdk.utils.DeviceUtilsLite;
public static OpenSourceFragment newInstance(String title) { OpenSourceFragment f = new OpenSourceFragment(); Bundle args = new Bundle(); args.putString(AppConstants.KEY_TITLE, title); f.setArguments(args); return (f); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(getArguments() != null) { mTitle = getArguments().getString(AppConstants.KEY_TITLE); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.frg_about, null); mTvTitle = (TextView) rootView.findViewById(R.id.tvVersion); return rootView; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mTvTitle.setText(getString(R.string.app_version_about,
// Path: example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/constant/AppConstants.java // public class AppConstants { // // public static final String KEY_MODEL = "key_model"; // public static final String KEY_STATUS = "key_status"; // public static final String KEY_TITLE = "key_title"; // public static final String KEY_ID = "key_id"; // public static final String KEY_IS_BOOLEAN = "key_boolean"; // // public static final String KEY_BLE_DEVICE = "key_ble_device"; // public static final String KEY_BLE_SERVICE = "key_ble_service"; // public static final String KEY_BLE_CHARACTERISTIC = "key_ble_characteristic"; // // public static final int PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 69; // } // // Path: supportsdk/src/main/java/com/github/captain_miao/android/supportsdk/utils/DeviceUtilsLite.java // public class DeviceUtilsLite { // // public static String getDeviceUniqueId(Context context) { // String uid = ""; // if (context != null) { // try { // TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); // String did = tm.getDeviceId(); // String sid = tm.getSubscriberId(); // // if (did != null && !did.equals("")) { // uid += did; // } // if (sid != null && !sid.equals("")) { // uid += "_" + sid; // } // if (uid.equals("")) { // uid = "unknown"; // } // } catch (Exception e) { // // } // } // return uid; // } // // public static int getAppVersionCode(Context context, String filePath) { // int versionCode = 0; // if (context != null) { // try { // PackageInfo pi = context.getPackageManager().getPackageArchiveInfo(filePath, 0); // versionCode = pi.versionCode; // } catch (Exception e) { // // } // } // return versionCode; // } // // public static int getAppVersionCode(Context context) { // return getAppVersionCode(context, (ApplicationInfo) null); // } // // public static int getAppVersionCode(Context context, ApplicationInfo info) { // int versionCode = 0; // if (context != null) { // String packageName = ""; // if (info != null) { // packageName = info.packageName; // } else { // packageName = context.getPackageName(); // } // try { // PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, 0); // versionCode = pi.versionCode; // } catch (Exception e) { // // } // } // return versionCode; // } // // public static String getAppVersionName(Context context) { // return getAppVersionName(context, null); // } // // public static String getAppVersionName(Context context, ApplicationInfo info) { // String versionName = ""; // if (context != null) { // String packageName = ""; // if (info != null) { // packageName = info.packageName; // } else { // packageName = context.getPackageName(); // } // try { // PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, 0); // versionName = pi.versionName; // // } catch (Exception e) { // // } // } // return versionName; // } // } // Path: example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/fragment/OpenSourceFragment.java import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.github.captain_miao.android.bluetoothletutorial.R; import com.github.captain_miao.android.bluetoothletutorial.constant.AppConstants; import com.github.captain_miao.android.supportsdk.utils.DeviceUtilsLite; public static OpenSourceFragment newInstance(String title) { OpenSourceFragment f = new OpenSourceFragment(); Bundle args = new Bundle(); args.putString(AppConstants.KEY_TITLE, title); f.setArguments(args); return (f); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(getArguments() != null) { mTitle = getArguments().getString(AppConstants.KEY_TITLE); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.frg_about, null); mTvTitle = (TextView) rootView.findViewById(R.id.tvVersion); return rootView; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mTvTitle.setText(getString(R.string.app_version_about,
DeviceUtilsLite.getAppVersionName(getActivity())));
captain-miao/bleYan
example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/fragment/ConfigFragment.java
// Path: example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/constant/AppConstants.java // public class AppConstants { // // public static final String KEY_MODEL = "key_model"; // public static final String KEY_STATUS = "key_status"; // public static final String KEY_TITLE = "key_title"; // public static final String KEY_ID = "key_id"; // public static final String KEY_IS_BOOLEAN = "key_boolean"; // // public static final String KEY_BLE_DEVICE = "key_ble_device"; // public static final String KEY_BLE_SERVICE = "key_ble_service"; // public static final String KEY_BLE_CHARACTERISTIC = "key_ble_characteristic"; // // public static final int PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 69; // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.github.captain_miao.android.bluetoothletutorial.R; import com.github.captain_miao.android.bluetoothletutorial.constant.AppConstants; import java.util.ArrayList; import java.util.List;
package com.github.captain_miao.android.bluetoothletutorial.fragment; /** * @author Yan Lu * @since 2015-10-08 */ public class ConfigFragment extends BaseFragment { private static final String TAG = ConfigFragment.class.getSimpleName(); private String mTitle; public ConfigFragment() { } public static ConfigFragment newInstance(String title) { ConfigFragment f = new ConfigFragment(); Bundle args = new Bundle();
// Path: example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/constant/AppConstants.java // public class AppConstants { // // public static final String KEY_MODEL = "key_model"; // public static final String KEY_STATUS = "key_status"; // public static final String KEY_TITLE = "key_title"; // public static final String KEY_ID = "key_id"; // public static final String KEY_IS_BOOLEAN = "key_boolean"; // // public static final String KEY_BLE_DEVICE = "key_ble_device"; // public static final String KEY_BLE_SERVICE = "key_ble_service"; // public static final String KEY_BLE_CHARACTERISTIC = "key_ble_characteristic"; // // public static final int PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 69; // } // Path: example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/fragment/ConfigFragment.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.github.captain_miao.android.bluetoothletutorial.R; import com.github.captain_miao.android.bluetoothletutorial.constant.AppConstants; import java.util.ArrayList; import java.util.List; package com.github.captain_miao.android.bluetoothletutorial.fragment; /** * @author Yan Lu * @since 2015-10-08 */ public class ConfigFragment extends BaseFragment { private static final String TAG = ConfigFragment.class.getSimpleName(); private String mTitle; public ConfigFragment() { } public static ConfigFragment newInstance(String title) { ConfigFragment f = new ConfigFragment(); Bundle args = new Bundle();
args.putString(AppConstants.KEY_TITLE, title);
captain-miao/bleYan
blelibrary/src/main/java/com/github/captain_miao/android/ble/BleServiceHandle.java
// Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/constant/BleConstants.java // public class BleConstants { // // //ble response message id // public static final int MSG_BLE_ID_CHARACTERISTIC_WRITE = 20000; // public static final int MSG_BLE_ID_DESCRIPTOR_WRITE = 20001; // public static final int MSG_BLE_ID_CHARACTERISTIC_NOTIFICATION = 20002; // public static final int MSG_BLE_ID_CHARACTERISTIC_READ = 20003; // public static final int MSG_BLE_ID_DESCRIPTOR_READ = 20004; // public static final int MSG_BLE_ID_RELIABLE_WRITE_COMPLETED = 20005; // public static final int MSG_BLE_ID_READ_REMOTE_RSSI = 20006; // public static final int MSG_BLE_ID_MTU_CHANGED = 20007; // public static final int MSG_BLE_ID_SERVICES_DISCOVERED = 20008; // // // //ble control message id // public static final int MSG_CONTROL_ID_REGISTER = 30000; // public static final int MSG_CONTROL_ID_UNREGISTER = 30001; // public static final int MSG_CONTROL_ID_CONNECT_DEVICE = 30002; // public static final int MSG_CONTROL_ID_CONNECT_MAC = 30003; // public static final int MSG_CONTROL_ID_START_SCAN = 30004; // public static final int MSG_CONTROL_ID_STOP_SCAN = 30005; // // // //ble read message id // public static final int MSG_CONTROL_ID_WRITE_CHARACTERISTIC = 40000; // public static final int MSG_CONTROL_ID_DESCRIPTOR_NOTIFICATION = 40001; // public static final int MSG_CONTROL_ID_READ_CHARACTERISTIC = 40002; // // // // // // // //用ζ₯εŒΊεˆ†δΈεŒη±»εž‹ηš„ζΆˆζ― // public static final int BLE_MSG_ID_CONNECTION_STATE_CHANGED = 10000;//θ“η‰™θΏžζŽ₯ηŠΆζ€ε˜εŒ– // // // public static final String BLE_MSG_SERVICE_UUID_KEY = "service_uuid"; // public static final String BLE_MSG_CHARACTERISTIC_UUID_KEY = "characteristic_uuid"; // public static final String BLE_MSG_DESCRIPTOR_UUID_KEY = "descriptor_uuid"; // public static final String BLE_MSG_VALUE_KEY = "ble_value"; // public static final String BLE_MSG_ENABLE_KEY = "ble_enable"; // public static final String BLE_MSG_BLE_DEVICE_KEY = "ble_device"; // public static final String BLE_MSG_BLE_GATT_KEY = "ble_gatt"; // } // // Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/utils/BleLog.java // public class BleLog { // private static boolean isPrintLog = true; // // private BleLog() {} // // public static boolean isPrintLog() { // return isPrintLog; // } // // public static void setPrintLog(boolean isPrintLog) { // BleLog.isPrintLog = isPrintLog; // } // // public static void v(String tag, String msg) { // if (isPrintLog) { // Log.v(tag, msg); // } // } // // public static void d(String tag, String msg) { // if (isPrintLog) { // Log.d(tag, msg); // } // } // // public static void i(String tag, String msg) { // if (isPrintLog) { // Log.i(tag, msg); // } // } // // public static void w(String tag, String msg) { // if (isPrintLog) { // Log.w(tag, msg); // } // } // // public static void e(String tag, String msg) { // if (isPrintLog) { // Log.e(tag, msg); // } // } // }
import android.bluetooth.BluetoothDevice; import android.os.Bundle; import android.os.Message; import com.github.captain_miao.android.ble.constant.BleConstants; import com.github.captain_miao.android.ble.utils.BleLog; import java.util.UUID;
package com.github.captain_miao.android.ble; /** * @author YanLu * @since 2015-09-14 * * handle ble commend */ public class BleServiceHandle extends AppHandler<BaseBleService> { private final static String TAG = BleServiceHandle.class.getName(); public BleServiceHandle(BaseBleService reference) { super(reference); mMessageListener = new HandleMessageListener<BaseBleService>() { @Override public void onHandleMessage(BaseBleService reference, Message msg) { onBleServiceMessage(reference, msg); } }; } public void onBleServiceMessage(BaseBleService reference, Message msg) { if (msg != null) { Bundle data = msg.getData(); switch (msg.what) {
// Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/constant/BleConstants.java // public class BleConstants { // // //ble response message id // public static final int MSG_BLE_ID_CHARACTERISTIC_WRITE = 20000; // public static final int MSG_BLE_ID_DESCRIPTOR_WRITE = 20001; // public static final int MSG_BLE_ID_CHARACTERISTIC_NOTIFICATION = 20002; // public static final int MSG_BLE_ID_CHARACTERISTIC_READ = 20003; // public static final int MSG_BLE_ID_DESCRIPTOR_READ = 20004; // public static final int MSG_BLE_ID_RELIABLE_WRITE_COMPLETED = 20005; // public static final int MSG_BLE_ID_READ_REMOTE_RSSI = 20006; // public static final int MSG_BLE_ID_MTU_CHANGED = 20007; // public static final int MSG_BLE_ID_SERVICES_DISCOVERED = 20008; // // // //ble control message id // public static final int MSG_CONTROL_ID_REGISTER = 30000; // public static final int MSG_CONTROL_ID_UNREGISTER = 30001; // public static final int MSG_CONTROL_ID_CONNECT_DEVICE = 30002; // public static final int MSG_CONTROL_ID_CONNECT_MAC = 30003; // public static final int MSG_CONTROL_ID_START_SCAN = 30004; // public static final int MSG_CONTROL_ID_STOP_SCAN = 30005; // // // //ble read message id // public static final int MSG_CONTROL_ID_WRITE_CHARACTERISTIC = 40000; // public static final int MSG_CONTROL_ID_DESCRIPTOR_NOTIFICATION = 40001; // public static final int MSG_CONTROL_ID_READ_CHARACTERISTIC = 40002; // // // // // // // //用ζ₯εŒΊεˆ†δΈεŒη±»εž‹ηš„ζΆˆζ― // public static final int BLE_MSG_ID_CONNECTION_STATE_CHANGED = 10000;//θ“η‰™θΏžζŽ₯ηŠΆζ€ε˜εŒ– // // // public static final String BLE_MSG_SERVICE_UUID_KEY = "service_uuid"; // public static final String BLE_MSG_CHARACTERISTIC_UUID_KEY = "characteristic_uuid"; // public static final String BLE_MSG_DESCRIPTOR_UUID_KEY = "descriptor_uuid"; // public static final String BLE_MSG_VALUE_KEY = "ble_value"; // public static final String BLE_MSG_ENABLE_KEY = "ble_enable"; // public static final String BLE_MSG_BLE_DEVICE_KEY = "ble_device"; // public static final String BLE_MSG_BLE_GATT_KEY = "ble_gatt"; // } // // Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/utils/BleLog.java // public class BleLog { // private static boolean isPrintLog = true; // // private BleLog() {} // // public static boolean isPrintLog() { // return isPrintLog; // } // // public static void setPrintLog(boolean isPrintLog) { // BleLog.isPrintLog = isPrintLog; // } // // public static void v(String tag, String msg) { // if (isPrintLog) { // Log.v(tag, msg); // } // } // // public static void d(String tag, String msg) { // if (isPrintLog) { // Log.d(tag, msg); // } // } // // public static void i(String tag, String msg) { // if (isPrintLog) { // Log.i(tag, msg); // } // } // // public static void w(String tag, String msg) { // if (isPrintLog) { // Log.w(tag, msg); // } // } // // public static void e(String tag, String msg) { // if (isPrintLog) { // Log.e(tag, msg); // } // } // } // Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/BleServiceHandle.java import android.bluetooth.BluetoothDevice; import android.os.Bundle; import android.os.Message; import com.github.captain_miao.android.ble.constant.BleConstants; import com.github.captain_miao.android.ble.utils.BleLog; import java.util.UUID; package com.github.captain_miao.android.ble; /** * @author YanLu * @since 2015-09-14 * * handle ble commend */ public class BleServiceHandle extends AppHandler<BaseBleService> { private final static String TAG = BleServiceHandle.class.getName(); public BleServiceHandle(BaseBleService reference) { super(reference); mMessageListener = new HandleMessageListener<BaseBleService>() { @Override public void onHandleMessage(BaseBleService reference, Message msg) { onBleServiceMessage(reference, msg); } }; } public void onBleServiceMessage(BaseBleService reference, Message msg) { if (msg != null) { Bundle data = msg.getData(); switch (msg.what) {
case BleConstants.MSG_CONTROL_ID_REGISTER:
captain-miao/bleYan
blelibrary/src/main/java/com/github/captain_miao/android/ble/BleServiceHandle.java
// Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/constant/BleConstants.java // public class BleConstants { // // //ble response message id // public static final int MSG_BLE_ID_CHARACTERISTIC_WRITE = 20000; // public static final int MSG_BLE_ID_DESCRIPTOR_WRITE = 20001; // public static final int MSG_BLE_ID_CHARACTERISTIC_NOTIFICATION = 20002; // public static final int MSG_BLE_ID_CHARACTERISTIC_READ = 20003; // public static final int MSG_BLE_ID_DESCRIPTOR_READ = 20004; // public static final int MSG_BLE_ID_RELIABLE_WRITE_COMPLETED = 20005; // public static final int MSG_BLE_ID_READ_REMOTE_RSSI = 20006; // public static final int MSG_BLE_ID_MTU_CHANGED = 20007; // public static final int MSG_BLE_ID_SERVICES_DISCOVERED = 20008; // // // //ble control message id // public static final int MSG_CONTROL_ID_REGISTER = 30000; // public static final int MSG_CONTROL_ID_UNREGISTER = 30001; // public static final int MSG_CONTROL_ID_CONNECT_DEVICE = 30002; // public static final int MSG_CONTROL_ID_CONNECT_MAC = 30003; // public static final int MSG_CONTROL_ID_START_SCAN = 30004; // public static final int MSG_CONTROL_ID_STOP_SCAN = 30005; // // // //ble read message id // public static final int MSG_CONTROL_ID_WRITE_CHARACTERISTIC = 40000; // public static final int MSG_CONTROL_ID_DESCRIPTOR_NOTIFICATION = 40001; // public static final int MSG_CONTROL_ID_READ_CHARACTERISTIC = 40002; // // // // // // // //用ζ₯εŒΊεˆ†δΈεŒη±»εž‹ηš„ζΆˆζ― // public static final int BLE_MSG_ID_CONNECTION_STATE_CHANGED = 10000;//θ“η‰™θΏžζŽ₯ηŠΆζ€ε˜εŒ– // // // public static final String BLE_MSG_SERVICE_UUID_KEY = "service_uuid"; // public static final String BLE_MSG_CHARACTERISTIC_UUID_KEY = "characteristic_uuid"; // public static final String BLE_MSG_DESCRIPTOR_UUID_KEY = "descriptor_uuid"; // public static final String BLE_MSG_VALUE_KEY = "ble_value"; // public static final String BLE_MSG_ENABLE_KEY = "ble_enable"; // public static final String BLE_MSG_BLE_DEVICE_KEY = "ble_device"; // public static final String BLE_MSG_BLE_GATT_KEY = "ble_gatt"; // } // // Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/utils/BleLog.java // public class BleLog { // private static boolean isPrintLog = true; // // private BleLog() {} // // public static boolean isPrintLog() { // return isPrintLog; // } // // public static void setPrintLog(boolean isPrintLog) { // BleLog.isPrintLog = isPrintLog; // } // // public static void v(String tag, String msg) { // if (isPrintLog) { // Log.v(tag, msg); // } // } // // public static void d(String tag, String msg) { // if (isPrintLog) { // Log.d(tag, msg); // } // } // // public static void i(String tag, String msg) { // if (isPrintLog) { // Log.i(tag, msg); // } // } // // public static void w(String tag, String msg) { // if (isPrintLog) { // Log.w(tag, msg); // } // } // // public static void e(String tag, String msg) { // if (isPrintLog) { // Log.e(tag, msg); // } // } // }
import android.bluetooth.BluetoothDevice; import android.os.Bundle; import android.os.Message; import com.github.captain_miao.android.ble.constant.BleConstants; import com.github.captain_miao.android.ble.utils.BleLog; import java.util.UUID;
package com.github.captain_miao.android.ble; /** * @author YanLu * @since 2015-09-14 * * handle ble commend */ public class BleServiceHandle extends AppHandler<BaseBleService> { private final static String TAG = BleServiceHandle.class.getName(); public BleServiceHandle(BaseBleService reference) { super(reference); mMessageListener = new HandleMessageListener<BaseBleService>() { @Override public void onHandleMessage(BaseBleService reference, Message msg) { onBleServiceMessage(reference, msg); } }; } public void onBleServiceMessage(BaseBleService reference, Message msg) { if (msg != null) { Bundle data = msg.getData(); switch (msg.what) { case BleConstants.MSG_CONTROL_ID_REGISTER:
// Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/constant/BleConstants.java // public class BleConstants { // // //ble response message id // public static final int MSG_BLE_ID_CHARACTERISTIC_WRITE = 20000; // public static final int MSG_BLE_ID_DESCRIPTOR_WRITE = 20001; // public static final int MSG_BLE_ID_CHARACTERISTIC_NOTIFICATION = 20002; // public static final int MSG_BLE_ID_CHARACTERISTIC_READ = 20003; // public static final int MSG_BLE_ID_DESCRIPTOR_READ = 20004; // public static final int MSG_BLE_ID_RELIABLE_WRITE_COMPLETED = 20005; // public static final int MSG_BLE_ID_READ_REMOTE_RSSI = 20006; // public static final int MSG_BLE_ID_MTU_CHANGED = 20007; // public static final int MSG_BLE_ID_SERVICES_DISCOVERED = 20008; // // // //ble control message id // public static final int MSG_CONTROL_ID_REGISTER = 30000; // public static final int MSG_CONTROL_ID_UNREGISTER = 30001; // public static final int MSG_CONTROL_ID_CONNECT_DEVICE = 30002; // public static final int MSG_CONTROL_ID_CONNECT_MAC = 30003; // public static final int MSG_CONTROL_ID_START_SCAN = 30004; // public static final int MSG_CONTROL_ID_STOP_SCAN = 30005; // // // //ble read message id // public static final int MSG_CONTROL_ID_WRITE_CHARACTERISTIC = 40000; // public static final int MSG_CONTROL_ID_DESCRIPTOR_NOTIFICATION = 40001; // public static final int MSG_CONTROL_ID_READ_CHARACTERISTIC = 40002; // // // // // // // //用ζ₯εŒΊεˆ†δΈεŒη±»εž‹ηš„ζΆˆζ― // public static final int BLE_MSG_ID_CONNECTION_STATE_CHANGED = 10000;//θ“η‰™θΏžζŽ₯ηŠΆζ€ε˜εŒ– // // // public static final String BLE_MSG_SERVICE_UUID_KEY = "service_uuid"; // public static final String BLE_MSG_CHARACTERISTIC_UUID_KEY = "characteristic_uuid"; // public static final String BLE_MSG_DESCRIPTOR_UUID_KEY = "descriptor_uuid"; // public static final String BLE_MSG_VALUE_KEY = "ble_value"; // public static final String BLE_MSG_ENABLE_KEY = "ble_enable"; // public static final String BLE_MSG_BLE_DEVICE_KEY = "ble_device"; // public static final String BLE_MSG_BLE_GATT_KEY = "ble_gatt"; // } // // Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/utils/BleLog.java // public class BleLog { // private static boolean isPrintLog = true; // // private BleLog() {} // // public static boolean isPrintLog() { // return isPrintLog; // } // // public static void setPrintLog(boolean isPrintLog) { // BleLog.isPrintLog = isPrintLog; // } // // public static void v(String tag, String msg) { // if (isPrintLog) { // Log.v(tag, msg); // } // } // // public static void d(String tag, String msg) { // if (isPrintLog) { // Log.d(tag, msg); // } // } // // public static void i(String tag, String msg) { // if (isPrintLog) { // Log.i(tag, msg); // } // } // // public static void w(String tag, String msg) { // if (isPrintLog) { // Log.w(tag, msg); // } // } // // public static void e(String tag, String msg) { // if (isPrintLog) { // Log.e(tag, msg); // } // } // } // Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/BleServiceHandle.java import android.bluetooth.BluetoothDevice; import android.os.Bundle; import android.os.Message; import com.github.captain_miao.android.ble.constant.BleConstants; import com.github.captain_miao.android.ble.utils.BleLog; import java.util.UUID; package com.github.captain_miao.android.ble; /** * @author YanLu * @since 2015-09-14 * * handle ble commend */ public class BleServiceHandle extends AppHandler<BaseBleService> { private final static String TAG = BleServiceHandle.class.getName(); public BleServiceHandle(BaseBleService reference) { super(reference); mMessageListener = new HandleMessageListener<BaseBleService>() { @Override public void onHandleMessage(BaseBleService reference, Message msg) { onBleServiceMessage(reference, msg); } }; } public void onBleServiceMessage(BaseBleService reference, Message msg) { if (msg != null) { Bundle data = msg.getData(); switch (msg.what) { case BleConstants.MSG_CONTROL_ID_REGISTER:
BleLog.i(TAG, "BleService Registered");
captain-miao/bleYan
blelibrary/src/main/java/com/github/captain_miao/android/ble/JellyBeanBleScanner.java
// Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/constant/BleScanState.java // public enum BleScanState { // // SCAN_TIMEOUT(-2, "SCAN_SUCCESS_TIME_OUT"), // BLUETOOTH_OFF(-1, "BLUETOOTH_OFF"), // SCAN_SUCCESS(0, "SCAN_SUCCESS"), // SCAN_FAILED_ALREADY_STARTED(1, "SCAN_FAILED_ALREADY_STARTED"), // SCAN_FAILED_APPLICATION_REGISTRATION_FAILED(2, "SCAN_FAILED_APPLICATION_REGISTRATION_FAILED"), // SCAN_FAILED_INTERNAL_ERROR(3, "SCAN_FAILED_INTERNAL_ERROR"), // SCAN_FAILED_FEATURE_UNSUPPORTED(4, "SCAN_FAILED_FEATURE_UNSUPPORTED"), // SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES(5, "SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES"); // // // BleScanState(int code, String message) { // this.code = code; // this.message = message; // } // // private int code; // private String message; // // public int getCode() { // return code; // } // // // public String getMessage() { // return message; // } // // public static BleScanState newInstance(int code) { // switch (code) { // case -2: // return BleScanState.SCAN_TIMEOUT; // case -1: // return BleScanState.BLUETOOTH_OFF; // // case 1: // return BleScanState.SCAN_FAILED_ALREADY_STARTED; // case 2: // return BleScanState.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED; // case 3: // return BleScanState.SCAN_FAILED_INTERNAL_ERROR; // case 4: // return BleScanState.SCAN_FAILED_FEATURE_UNSUPPORTED; // case 5: // return BleScanState.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES; // default: // return BleScanState.SCAN_SUCCESS; // } // } // } // // Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/utils/BleLog.java // public class BleLog { // private static boolean isPrintLog = true; // // private BleLog() {} // // public static boolean isPrintLog() { // return isPrintLog; // } // // public static void setPrintLog(boolean isPrintLog) { // BleLog.isPrintLog = isPrintLog; // } // // public static void v(String tag, String msg) { // if (isPrintLog) { // Log.v(tag, msg); // } // } // // public static void d(String tag, String msg) { // if (isPrintLog) { // Log.d(tag, msg); // } // } // // public static void i(String tag, String msg) { // if (isPrintLog) { // Log.i(tag, msg); // } // } // // public static void w(String tag, String msg) { // if (isPrintLog) { // Log.w(tag, msg); // } // } // // public static void e(String tag, String msg) { // if (isPrintLog) { // Log.e(tag, msg); // } // } // }
import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.content.Context; import com.github.captain_miao.android.ble.constant.BleScanState; import com.github.captain_miao.android.ble.utils.BleLog;
package com.github.captain_miao.android.ble; /** * @author YanLu * @since 15/9/14 * * Android4.3 and 4.4 scan bluetooth */ public class JellyBeanBleScanner extends BaseBleScanner { private final static String TAG = JellyBeanBleScanner.class.getName(); public BluetoothAdapter mBluetooth = null; private SimpleScanCallback mScanCallback = null; public JellyBeanBleScanner(Context context,SimpleScanCallback callback) { mScanCallback = callback; BluetoothManager bluetoothMgr = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); mBluetooth = bluetoothMgr.getAdapter(); } private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) { mScanCallback.onBleScan(device, rssi, scanRecord); } }; @SuppressWarnings(value={"deprecation"}) @Override public void onStartBleScan(long timeoutMillis) { long delay = timeoutMillis == 0 ? defaultTimeout : timeoutMillis; if(mBluetooth != null) { isScanning = mBluetooth.startLeScan(leScanCallback); timeoutHandler.postDelayed(timeoutRunnable, delay);
// Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/constant/BleScanState.java // public enum BleScanState { // // SCAN_TIMEOUT(-2, "SCAN_SUCCESS_TIME_OUT"), // BLUETOOTH_OFF(-1, "BLUETOOTH_OFF"), // SCAN_SUCCESS(0, "SCAN_SUCCESS"), // SCAN_FAILED_ALREADY_STARTED(1, "SCAN_FAILED_ALREADY_STARTED"), // SCAN_FAILED_APPLICATION_REGISTRATION_FAILED(2, "SCAN_FAILED_APPLICATION_REGISTRATION_FAILED"), // SCAN_FAILED_INTERNAL_ERROR(3, "SCAN_FAILED_INTERNAL_ERROR"), // SCAN_FAILED_FEATURE_UNSUPPORTED(4, "SCAN_FAILED_FEATURE_UNSUPPORTED"), // SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES(5, "SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES"); // // // BleScanState(int code, String message) { // this.code = code; // this.message = message; // } // // private int code; // private String message; // // public int getCode() { // return code; // } // // // public String getMessage() { // return message; // } // // public static BleScanState newInstance(int code) { // switch (code) { // case -2: // return BleScanState.SCAN_TIMEOUT; // case -1: // return BleScanState.BLUETOOTH_OFF; // // case 1: // return BleScanState.SCAN_FAILED_ALREADY_STARTED; // case 2: // return BleScanState.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED; // case 3: // return BleScanState.SCAN_FAILED_INTERNAL_ERROR; // case 4: // return BleScanState.SCAN_FAILED_FEATURE_UNSUPPORTED; // case 5: // return BleScanState.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES; // default: // return BleScanState.SCAN_SUCCESS; // } // } // } // // Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/utils/BleLog.java // public class BleLog { // private static boolean isPrintLog = true; // // private BleLog() {} // // public static boolean isPrintLog() { // return isPrintLog; // } // // public static void setPrintLog(boolean isPrintLog) { // BleLog.isPrintLog = isPrintLog; // } // // public static void v(String tag, String msg) { // if (isPrintLog) { // Log.v(tag, msg); // } // } // // public static void d(String tag, String msg) { // if (isPrintLog) { // Log.d(tag, msg); // } // } // // public static void i(String tag, String msg) { // if (isPrintLog) { // Log.i(tag, msg); // } // } // // public static void w(String tag, String msg) { // if (isPrintLog) { // Log.w(tag, msg); // } // } // // public static void e(String tag, String msg) { // if (isPrintLog) { // Log.e(tag, msg); // } // } // } // Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/JellyBeanBleScanner.java import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.content.Context; import com.github.captain_miao.android.ble.constant.BleScanState; import com.github.captain_miao.android.ble.utils.BleLog; package com.github.captain_miao.android.ble; /** * @author YanLu * @since 15/9/14 * * Android4.3 and 4.4 scan bluetooth */ public class JellyBeanBleScanner extends BaseBleScanner { private final static String TAG = JellyBeanBleScanner.class.getName(); public BluetoothAdapter mBluetooth = null; private SimpleScanCallback mScanCallback = null; public JellyBeanBleScanner(Context context,SimpleScanCallback callback) { mScanCallback = callback; BluetoothManager bluetoothMgr = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); mBluetooth = bluetoothMgr.getAdapter(); } private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) { mScanCallback.onBleScan(device, rssi, scanRecord); } }; @SuppressWarnings(value={"deprecation"}) @Override public void onStartBleScan(long timeoutMillis) { long delay = timeoutMillis == 0 ? defaultTimeout : timeoutMillis; if(mBluetooth != null) { isScanning = mBluetooth.startLeScan(leScanCallback); timeoutHandler.postDelayed(timeoutRunnable, delay);
BleLog.i(TAG, "mBluetooth.startLeScan() " + isScanning);
captain-miao/bleYan
blelibrary/src/main/java/com/github/captain_miao/android/ble/JellyBeanBleScanner.java
// Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/constant/BleScanState.java // public enum BleScanState { // // SCAN_TIMEOUT(-2, "SCAN_SUCCESS_TIME_OUT"), // BLUETOOTH_OFF(-1, "BLUETOOTH_OFF"), // SCAN_SUCCESS(0, "SCAN_SUCCESS"), // SCAN_FAILED_ALREADY_STARTED(1, "SCAN_FAILED_ALREADY_STARTED"), // SCAN_FAILED_APPLICATION_REGISTRATION_FAILED(2, "SCAN_FAILED_APPLICATION_REGISTRATION_FAILED"), // SCAN_FAILED_INTERNAL_ERROR(3, "SCAN_FAILED_INTERNAL_ERROR"), // SCAN_FAILED_FEATURE_UNSUPPORTED(4, "SCAN_FAILED_FEATURE_UNSUPPORTED"), // SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES(5, "SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES"); // // // BleScanState(int code, String message) { // this.code = code; // this.message = message; // } // // private int code; // private String message; // // public int getCode() { // return code; // } // // // public String getMessage() { // return message; // } // // public static BleScanState newInstance(int code) { // switch (code) { // case -2: // return BleScanState.SCAN_TIMEOUT; // case -1: // return BleScanState.BLUETOOTH_OFF; // // case 1: // return BleScanState.SCAN_FAILED_ALREADY_STARTED; // case 2: // return BleScanState.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED; // case 3: // return BleScanState.SCAN_FAILED_INTERNAL_ERROR; // case 4: // return BleScanState.SCAN_FAILED_FEATURE_UNSUPPORTED; // case 5: // return BleScanState.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES; // default: // return BleScanState.SCAN_SUCCESS; // } // } // } // // Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/utils/BleLog.java // public class BleLog { // private static boolean isPrintLog = true; // // private BleLog() {} // // public static boolean isPrintLog() { // return isPrintLog; // } // // public static void setPrintLog(boolean isPrintLog) { // BleLog.isPrintLog = isPrintLog; // } // // public static void v(String tag, String msg) { // if (isPrintLog) { // Log.v(tag, msg); // } // } // // public static void d(String tag, String msg) { // if (isPrintLog) { // Log.d(tag, msg); // } // } // // public static void i(String tag, String msg) { // if (isPrintLog) { // Log.i(tag, msg); // } // } // // public static void w(String tag, String msg) { // if (isPrintLog) { // Log.w(tag, msg); // } // } // // public static void e(String tag, String msg) { // if (isPrintLog) { // Log.e(tag, msg); // } // } // }
import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.content.Context; import com.github.captain_miao.android.ble.constant.BleScanState; import com.github.captain_miao.android.ble.utils.BleLog;
package com.github.captain_miao.android.ble; /** * @author YanLu * @since 15/9/14 * * Android4.3 and 4.4 scan bluetooth */ public class JellyBeanBleScanner extends BaseBleScanner { private final static String TAG = JellyBeanBleScanner.class.getName(); public BluetoothAdapter mBluetooth = null; private SimpleScanCallback mScanCallback = null; public JellyBeanBleScanner(Context context,SimpleScanCallback callback) { mScanCallback = callback; BluetoothManager bluetoothMgr = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); mBluetooth = bluetoothMgr.getAdapter(); } private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) { mScanCallback.onBleScan(device, rssi, scanRecord); } }; @SuppressWarnings(value={"deprecation"}) @Override public void onStartBleScan(long timeoutMillis) { long delay = timeoutMillis == 0 ? defaultTimeout : timeoutMillis; if(mBluetooth != null) { isScanning = mBluetooth.startLeScan(leScanCallback); timeoutHandler.postDelayed(timeoutRunnable, delay); BleLog.i(TAG, "mBluetooth.startLeScan() " + isScanning); } else {
// Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/constant/BleScanState.java // public enum BleScanState { // // SCAN_TIMEOUT(-2, "SCAN_SUCCESS_TIME_OUT"), // BLUETOOTH_OFF(-1, "BLUETOOTH_OFF"), // SCAN_SUCCESS(0, "SCAN_SUCCESS"), // SCAN_FAILED_ALREADY_STARTED(1, "SCAN_FAILED_ALREADY_STARTED"), // SCAN_FAILED_APPLICATION_REGISTRATION_FAILED(2, "SCAN_FAILED_APPLICATION_REGISTRATION_FAILED"), // SCAN_FAILED_INTERNAL_ERROR(3, "SCAN_FAILED_INTERNAL_ERROR"), // SCAN_FAILED_FEATURE_UNSUPPORTED(4, "SCAN_FAILED_FEATURE_UNSUPPORTED"), // SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES(5, "SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES"); // // // BleScanState(int code, String message) { // this.code = code; // this.message = message; // } // // private int code; // private String message; // // public int getCode() { // return code; // } // // // public String getMessage() { // return message; // } // // public static BleScanState newInstance(int code) { // switch (code) { // case -2: // return BleScanState.SCAN_TIMEOUT; // case -1: // return BleScanState.BLUETOOTH_OFF; // // case 1: // return BleScanState.SCAN_FAILED_ALREADY_STARTED; // case 2: // return BleScanState.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED; // case 3: // return BleScanState.SCAN_FAILED_INTERNAL_ERROR; // case 4: // return BleScanState.SCAN_FAILED_FEATURE_UNSUPPORTED; // case 5: // return BleScanState.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES; // default: // return BleScanState.SCAN_SUCCESS; // } // } // } // // Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/utils/BleLog.java // public class BleLog { // private static boolean isPrintLog = true; // // private BleLog() {} // // public static boolean isPrintLog() { // return isPrintLog; // } // // public static void setPrintLog(boolean isPrintLog) { // BleLog.isPrintLog = isPrintLog; // } // // public static void v(String tag, String msg) { // if (isPrintLog) { // Log.v(tag, msg); // } // } // // public static void d(String tag, String msg) { // if (isPrintLog) { // Log.d(tag, msg); // } // } // // public static void i(String tag, String msg) { // if (isPrintLog) { // Log.i(tag, msg); // } // } // // public static void w(String tag, String msg) { // if (isPrintLog) { // Log.w(tag, msg); // } // } // // public static void e(String tag, String msg) { // if (isPrintLog) { // Log.e(tag, msg); // } // } // } // Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/JellyBeanBleScanner.java import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.content.Context; import com.github.captain_miao.android.ble.constant.BleScanState; import com.github.captain_miao.android.ble.utils.BleLog; package com.github.captain_miao.android.ble; /** * @author YanLu * @since 15/9/14 * * Android4.3 and 4.4 scan bluetooth */ public class JellyBeanBleScanner extends BaseBleScanner { private final static String TAG = JellyBeanBleScanner.class.getName(); public BluetoothAdapter mBluetooth = null; private SimpleScanCallback mScanCallback = null; public JellyBeanBleScanner(Context context,SimpleScanCallback callback) { mScanCallback = callback; BluetoothManager bluetoothMgr = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); mBluetooth = bluetoothMgr.getAdapter(); } private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) { mScanCallback.onBleScan(device, rssi, scanRecord); } }; @SuppressWarnings(value={"deprecation"}) @Override public void onStartBleScan(long timeoutMillis) { long delay = timeoutMillis == 0 ? defaultTimeout : timeoutMillis; if(mBluetooth != null) { isScanning = mBluetooth.startLeScan(leScanCallback); timeoutHandler.postDelayed(timeoutRunnable, delay); BleLog.i(TAG, "mBluetooth.startLeScan() " + isScanning); } else {
mScanCallback.onBleScanFailed(BleScanState.BLUETOOTH_OFF);//bluetooth is off
captain-miao/bleYan
example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/fragment/AboutFragment.java
// Path: example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/constant/AppConstants.java // public class AppConstants { // // public static final String KEY_MODEL = "key_model"; // public static final String KEY_STATUS = "key_status"; // public static final String KEY_TITLE = "key_title"; // public static final String KEY_ID = "key_id"; // public static final String KEY_IS_BOOLEAN = "key_boolean"; // // public static final String KEY_BLE_DEVICE = "key_ble_device"; // public static final String KEY_BLE_SERVICE = "key_ble_service"; // public static final String KEY_BLE_CHARACTERISTIC = "key_ble_characteristic"; // // public static final int PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 69; // } // // Path: supportsdk/src/main/java/com/github/captain_miao/android/supportsdk/utils/DeviceUtilsLite.java // public class DeviceUtilsLite { // // public static String getDeviceUniqueId(Context context) { // String uid = ""; // if (context != null) { // try { // TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); // String did = tm.getDeviceId(); // String sid = tm.getSubscriberId(); // // if (did != null && !did.equals("")) { // uid += did; // } // if (sid != null && !sid.equals("")) { // uid += "_" + sid; // } // if (uid.equals("")) { // uid = "unknown"; // } // } catch (Exception e) { // // } // } // return uid; // } // // public static int getAppVersionCode(Context context, String filePath) { // int versionCode = 0; // if (context != null) { // try { // PackageInfo pi = context.getPackageManager().getPackageArchiveInfo(filePath, 0); // versionCode = pi.versionCode; // } catch (Exception e) { // // } // } // return versionCode; // } // // public static int getAppVersionCode(Context context) { // return getAppVersionCode(context, (ApplicationInfo) null); // } // // public static int getAppVersionCode(Context context, ApplicationInfo info) { // int versionCode = 0; // if (context != null) { // String packageName = ""; // if (info != null) { // packageName = info.packageName; // } else { // packageName = context.getPackageName(); // } // try { // PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, 0); // versionCode = pi.versionCode; // } catch (Exception e) { // // } // } // return versionCode; // } // // public static String getAppVersionName(Context context) { // return getAppVersionName(context, null); // } // // public static String getAppVersionName(Context context, ApplicationInfo info) { // String versionName = ""; // if (context != null) { // String packageName = ""; // if (info != null) { // packageName = info.packageName; // } else { // packageName = context.getPackageName(); // } // try { // PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, 0); // versionName = pi.versionName; // // } catch (Exception e) { // // } // } // return versionName; // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.github.captain_miao.android.bluetoothletutorial.R; import com.github.captain_miao.android.bluetoothletutorial.constant.AppConstants; import com.github.captain_miao.android.supportsdk.utils.DeviceUtilsLite;
package com.github.captain_miao.android.bluetoothletutorial.fragment; /** * @author Yan Lu * @since 2015-07-23 */ public class AboutFragment extends BaseFragment { private static final String TAG = AboutFragment.class.getSimpleName(); private String mTitle; private TextView mTvTitle; public AboutFragment() { } public static AboutFragment newInstance(String title) { AboutFragment f = new AboutFragment(); Bundle args = new Bundle();
// Path: example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/constant/AppConstants.java // public class AppConstants { // // public static final String KEY_MODEL = "key_model"; // public static final String KEY_STATUS = "key_status"; // public static final String KEY_TITLE = "key_title"; // public static final String KEY_ID = "key_id"; // public static final String KEY_IS_BOOLEAN = "key_boolean"; // // public static final String KEY_BLE_DEVICE = "key_ble_device"; // public static final String KEY_BLE_SERVICE = "key_ble_service"; // public static final String KEY_BLE_CHARACTERISTIC = "key_ble_characteristic"; // // public static final int PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 69; // } // // Path: supportsdk/src/main/java/com/github/captain_miao/android/supportsdk/utils/DeviceUtilsLite.java // public class DeviceUtilsLite { // // public static String getDeviceUniqueId(Context context) { // String uid = ""; // if (context != null) { // try { // TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); // String did = tm.getDeviceId(); // String sid = tm.getSubscriberId(); // // if (did != null && !did.equals("")) { // uid += did; // } // if (sid != null && !sid.equals("")) { // uid += "_" + sid; // } // if (uid.equals("")) { // uid = "unknown"; // } // } catch (Exception e) { // // } // } // return uid; // } // // public static int getAppVersionCode(Context context, String filePath) { // int versionCode = 0; // if (context != null) { // try { // PackageInfo pi = context.getPackageManager().getPackageArchiveInfo(filePath, 0); // versionCode = pi.versionCode; // } catch (Exception e) { // // } // } // return versionCode; // } // // public static int getAppVersionCode(Context context) { // return getAppVersionCode(context, (ApplicationInfo) null); // } // // public static int getAppVersionCode(Context context, ApplicationInfo info) { // int versionCode = 0; // if (context != null) { // String packageName = ""; // if (info != null) { // packageName = info.packageName; // } else { // packageName = context.getPackageName(); // } // try { // PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, 0); // versionCode = pi.versionCode; // } catch (Exception e) { // // } // } // return versionCode; // } // // public static String getAppVersionName(Context context) { // return getAppVersionName(context, null); // } // // public static String getAppVersionName(Context context, ApplicationInfo info) { // String versionName = ""; // if (context != null) { // String packageName = ""; // if (info != null) { // packageName = info.packageName; // } else { // packageName = context.getPackageName(); // } // try { // PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, 0); // versionName = pi.versionName; // // } catch (Exception e) { // // } // } // return versionName; // } // } // Path: example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/fragment/AboutFragment.java import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.github.captain_miao.android.bluetoothletutorial.R; import com.github.captain_miao.android.bluetoothletutorial.constant.AppConstants; import com.github.captain_miao.android.supportsdk.utils.DeviceUtilsLite; package com.github.captain_miao.android.bluetoothletutorial.fragment; /** * @author Yan Lu * @since 2015-07-23 */ public class AboutFragment extends BaseFragment { private static final String TAG = AboutFragment.class.getSimpleName(); private String mTitle; private TextView mTvTitle; public AboutFragment() { } public static AboutFragment newInstance(String title) { AboutFragment f = new AboutFragment(); Bundle args = new Bundle();
args.putString(AppConstants.KEY_TITLE, title);
captain-miao/bleYan
example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/fragment/AboutFragment.java
// Path: example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/constant/AppConstants.java // public class AppConstants { // // public static final String KEY_MODEL = "key_model"; // public static final String KEY_STATUS = "key_status"; // public static final String KEY_TITLE = "key_title"; // public static final String KEY_ID = "key_id"; // public static final String KEY_IS_BOOLEAN = "key_boolean"; // // public static final String KEY_BLE_DEVICE = "key_ble_device"; // public static final String KEY_BLE_SERVICE = "key_ble_service"; // public static final String KEY_BLE_CHARACTERISTIC = "key_ble_characteristic"; // // public static final int PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 69; // } // // Path: supportsdk/src/main/java/com/github/captain_miao/android/supportsdk/utils/DeviceUtilsLite.java // public class DeviceUtilsLite { // // public static String getDeviceUniqueId(Context context) { // String uid = ""; // if (context != null) { // try { // TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); // String did = tm.getDeviceId(); // String sid = tm.getSubscriberId(); // // if (did != null && !did.equals("")) { // uid += did; // } // if (sid != null && !sid.equals("")) { // uid += "_" + sid; // } // if (uid.equals("")) { // uid = "unknown"; // } // } catch (Exception e) { // // } // } // return uid; // } // // public static int getAppVersionCode(Context context, String filePath) { // int versionCode = 0; // if (context != null) { // try { // PackageInfo pi = context.getPackageManager().getPackageArchiveInfo(filePath, 0); // versionCode = pi.versionCode; // } catch (Exception e) { // // } // } // return versionCode; // } // // public static int getAppVersionCode(Context context) { // return getAppVersionCode(context, (ApplicationInfo) null); // } // // public static int getAppVersionCode(Context context, ApplicationInfo info) { // int versionCode = 0; // if (context != null) { // String packageName = ""; // if (info != null) { // packageName = info.packageName; // } else { // packageName = context.getPackageName(); // } // try { // PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, 0); // versionCode = pi.versionCode; // } catch (Exception e) { // // } // } // return versionCode; // } // // public static String getAppVersionName(Context context) { // return getAppVersionName(context, null); // } // // public static String getAppVersionName(Context context, ApplicationInfo info) { // String versionName = ""; // if (context != null) { // String packageName = ""; // if (info != null) { // packageName = info.packageName; // } else { // packageName = context.getPackageName(); // } // try { // PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, 0); // versionName = pi.versionName; // // } catch (Exception e) { // // } // } // return versionName; // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.github.captain_miao.android.bluetoothletutorial.R; import com.github.captain_miao.android.bluetoothletutorial.constant.AppConstants; import com.github.captain_miao.android.supportsdk.utils.DeviceUtilsLite;
public static AboutFragment newInstance(String title) { AboutFragment f = new AboutFragment(); Bundle args = new Bundle(); args.putString(AppConstants.KEY_TITLE, title); f.setArguments(args); return (f); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(getArguments() != null) { mTitle = getArguments().getString(AppConstants.KEY_TITLE); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.frg_about, null); mTvTitle = (TextView) rootView.findViewById(R.id.tvVersion); return rootView; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mTvTitle.setText(getString(R.string.app_version_about,
// Path: example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/constant/AppConstants.java // public class AppConstants { // // public static final String KEY_MODEL = "key_model"; // public static final String KEY_STATUS = "key_status"; // public static final String KEY_TITLE = "key_title"; // public static final String KEY_ID = "key_id"; // public static final String KEY_IS_BOOLEAN = "key_boolean"; // // public static final String KEY_BLE_DEVICE = "key_ble_device"; // public static final String KEY_BLE_SERVICE = "key_ble_service"; // public static final String KEY_BLE_CHARACTERISTIC = "key_ble_characteristic"; // // public static final int PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 69; // } // // Path: supportsdk/src/main/java/com/github/captain_miao/android/supportsdk/utils/DeviceUtilsLite.java // public class DeviceUtilsLite { // // public static String getDeviceUniqueId(Context context) { // String uid = ""; // if (context != null) { // try { // TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); // String did = tm.getDeviceId(); // String sid = tm.getSubscriberId(); // // if (did != null && !did.equals("")) { // uid += did; // } // if (sid != null && !sid.equals("")) { // uid += "_" + sid; // } // if (uid.equals("")) { // uid = "unknown"; // } // } catch (Exception e) { // // } // } // return uid; // } // // public static int getAppVersionCode(Context context, String filePath) { // int versionCode = 0; // if (context != null) { // try { // PackageInfo pi = context.getPackageManager().getPackageArchiveInfo(filePath, 0); // versionCode = pi.versionCode; // } catch (Exception e) { // // } // } // return versionCode; // } // // public static int getAppVersionCode(Context context) { // return getAppVersionCode(context, (ApplicationInfo) null); // } // // public static int getAppVersionCode(Context context, ApplicationInfo info) { // int versionCode = 0; // if (context != null) { // String packageName = ""; // if (info != null) { // packageName = info.packageName; // } else { // packageName = context.getPackageName(); // } // try { // PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, 0); // versionCode = pi.versionCode; // } catch (Exception e) { // // } // } // return versionCode; // } // // public static String getAppVersionName(Context context) { // return getAppVersionName(context, null); // } // // public static String getAppVersionName(Context context, ApplicationInfo info) { // String versionName = ""; // if (context != null) { // String packageName = ""; // if (info != null) { // packageName = info.packageName; // } else { // packageName = context.getPackageName(); // } // try { // PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, 0); // versionName = pi.versionName; // // } catch (Exception e) { // // } // } // return versionName; // } // } // Path: example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/fragment/AboutFragment.java import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.github.captain_miao.android.bluetoothletutorial.R; import com.github.captain_miao.android.bluetoothletutorial.constant.AppConstants; import com.github.captain_miao.android.supportsdk.utils.DeviceUtilsLite; public static AboutFragment newInstance(String title) { AboutFragment f = new AboutFragment(); Bundle args = new Bundle(); args.putString(AppConstants.KEY_TITLE, title); f.setArguments(args); return (f); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(getArguments() != null) { mTitle = getArguments().getString(AppConstants.KEY_TITLE); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.frg_about, null); mTvTitle = (TextView) rootView.findViewById(R.id.tvVersion); return rootView; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mTvTitle.setText(getString(R.string.app_version_about,
DeviceUtilsLite.getAppVersionName(getActivity())));
captain-miao/bleYan
example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/expandablerecyclerview/VerticalExpandableAdapter.java
// Path: example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/app/AppLog.java // public class AppLog { // private static boolean isPrintLog = true; // // private AppLog() {} // // public static boolean isPrintLog() { // return isPrintLog; // } // // public static void setPrintLog(boolean isPrintLog) { // AppLog.isPrintLog = isPrintLog; // } // // public static void v(String tag, String msg) { // if (isPrintLog) { // Log.v(tag, msg); // } // } // // public static void d(String tag, String msg) { // if (isPrintLog) { // Log.d(tag, msg); // } // } // // public static void i(String tag, String msg) { // if (isPrintLog) { // Log.i(tag, msg); // } // } // // public static void w(String tag, String msg) { // if (isPrintLog) { // Log.w(tag, msg); // } // } // // public static void e(String tag, String msg) { // if (isPrintLog) { // Log.e(tag, msg); // } // } // }
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.bignerdranch.expandablerecyclerview.Model.ParentListItem; import com.github.captain_miao.android.bluetoothletutorial.R; import com.github.captain_miao.android.bluetoothletutorial.app.AppLog; import java.util.List;
package com.github.captain_miao.android.bluetoothletutorial.expandablerecyclerview; /** * An example custom implementation of the ExpandableRecyclerAdapter. * * @author YanLu * @version 1.0 * @since 19/9/2015 */ public abstract class VerticalExpandableAdapter extends ExpandableRecyclerAdapter2<VerticalParentViewHolder, VerticalChildViewHolder> { private static final String TAG = VerticalExpandableAdapter.class.getSimpleName(); private LayoutInflater mInflater; protected abstract void onClickCharacteristic(String serviceUUID, String characteristicUUID); /** * Public primary constructor. * * @param context for inflating views * @param parentItemList the list of parent items to be displayed in the RecyclerView */ public VerticalExpandableAdapter(Context context, List<ParentListItem> parentItemList) { super(context, parentItemList); mInflater = LayoutInflater.from(context); } @Override public void onListItemExpanded(int position) { } @Override public void onListItemCollapsed(int position) { } /** * OnCreateViewHolder implementation for parent items. The desired ParentViewHolder should * be inflated here * * @param parent for inflating the View * @return the user's custom parent ViewHolder that must extend ParentViewHolder */ @Override public VerticalParentViewHolder onCreateParentViewHolder(ViewGroup parent) { View view = mInflater.inflate(R.layout.list_item_parent_vertical, parent, false); return new VerticalParentViewHolder(view); } /** * OnCreateViewHolder implementation for child items. The desired ChildViewHolder should * be inflated here * * @param parent for inflating the View * @return the user's custom parent ViewHolder that must extend ParentViewHolder */ @Override public VerticalChildViewHolder onCreateChildViewHolder(ViewGroup parent) { View view = mInflater.inflate(R.layout.list_item_child_vertical, parent, false); return new VerticalChildViewHolder(view) { @Override void onClickChildView(int position) { int parentPositon = position - getExpandedItemCount2(position); //int childPositon = getExpandedItemCount(parentPositon); Object parentItem = getParentItem(parentPositon); Object helperItem = getHelperItem(position); if(helperItem instanceof VerticalChildObject && parentItem instanceof VerticalParentObject){
// Path: example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/app/AppLog.java // public class AppLog { // private static boolean isPrintLog = true; // // private AppLog() {} // // public static boolean isPrintLog() { // return isPrintLog; // } // // public static void setPrintLog(boolean isPrintLog) { // AppLog.isPrintLog = isPrintLog; // } // // public static void v(String tag, String msg) { // if (isPrintLog) { // Log.v(tag, msg); // } // } // // public static void d(String tag, String msg) { // if (isPrintLog) { // Log.d(tag, msg); // } // } // // public static void i(String tag, String msg) { // if (isPrintLog) { // Log.i(tag, msg); // } // } // // public static void w(String tag, String msg) { // if (isPrintLog) { // Log.w(tag, msg); // } // } // // public static void e(String tag, String msg) { // if (isPrintLog) { // Log.e(tag, msg); // } // } // } // Path: example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/expandablerecyclerview/VerticalExpandableAdapter.java import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.bignerdranch.expandablerecyclerview.Model.ParentListItem; import com.github.captain_miao.android.bluetoothletutorial.R; import com.github.captain_miao.android.bluetoothletutorial.app.AppLog; import java.util.List; package com.github.captain_miao.android.bluetoothletutorial.expandablerecyclerview; /** * An example custom implementation of the ExpandableRecyclerAdapter. * * @author YanLu * @version 1.0 * @since 19/9/2015 */ public abstract class VerticalExpandableAdapter extends ExpandableRecyclerAdapter2<VerticalParentViewHolder, VerticalChildViewHolder> { private static final String TAG = VerticalExpandableAdapter.class.getSimpleName(); private LayoutInflater mInflater; protected abstract void onClickCharacteristic(String serviceUUID, String characteristicUUID); /** * Public primary constructor. * * @param context for inflating views * @param parentItemList the list of parent items to be displayed in the RecyclerView */ public VerticalExpandableAdapter(Context context, List<ParentListItem> parentItemList) { super(context, parentItemList); mInflater = LayoutInflater.from(context); } @Override public void onListItemExpanded(int position) { } @Override public void onListItemCollapsed(int position) { } /** * OnCreateViewHolder implementation for parent items. The desired ParentViewHolder should * be inflated here * * @param parent for inflating the View * @return the user's custom parent ViewHolder that must extend ParentViewHolder */ @Override public VerticalParentViewHolder onCreateParentViewHolder(ViewGroup parent) { View view = mInflater.inflate(R.layout.list_item_parent_vertical, parent, false); return new VerticalParentViewHolder(view); } /** * OnCreateViewHolder implementation for child items. The desired ChildViewHolder should * be inflated here * * @param parent for inflating the View * @return the user's custom parent ViewHolder that must extend ParentViewHolder */ @Override public VerticalChildViewHolder onCreateChildViewHolder(ViewGroup parent) { View view = mInflater.inflate(R.layout.list_item_child_vertical, parent, false); return new VerticalChildViewHolder(view) { @Override void onClickChildView(int position) { int parentPositon = position - getExpandedItemCount2(position); //int childPositon = getExpandedItemCount(parentPositon); Object parentItem = getParentItem(parentPositon); Object helperItem = getHelperItem(position); if(helperItem instanceof VerticalChildObject && parentItem instanceof VerticalParentObject){
AppLog.i(TAG, helperItem.toString());
captain-miao/bleYan
example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/app/AppHolder.java
// Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/utils/BleLog.java // public class BleLog { // private static boolean isPrintLog = true; // // private BleLog() {} // // public static boolean isPrintLog() { // return isPrintLog; // } // // public static void setPrintLog(boolean isPrintLog) { // BleLog.isPrintLog = isPrintLog; // } // // public static void v(String tag, String msg) { // if (isPrintLog) { // Log.v(tag, msg); // } // } // // public static void d(String tag, String msg) { // if (isPrintLog) { // Log.d(tag, msg); // } // } // // public static void i(String tag, String msg) { // if (isPrintLog) { // Log.i(tag, msg); // } // } // // public static void w(String tag, String msg) { // if (isPrintLog) { // Log.w(tag, msg); // } // } // // public static void e(String tag, String msg) { // if (isPrintLog) { // Log.e(tag, msg); // } // } // }
import android.app.Application; import android.content.Context; import com.activeandroid.ActiveAndroid; import com.github.captain_miao.android.ble.utils.BleLog;
package com.github.captain_miao.android.bluetoothletutorial.app; public class AppHolder extends Application { private static final String TAG = "AppHolder"; private static AppHolder _instance; public static AppHolder getInstance() { return _instance; } public static Context getContext() { return _instance.getApplicationContext(); } @Override public void onCreate() { super.onCreate(); ActiveAndroid.initialize(this);
// Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/utils/BleLog.java // public class BleLog { // private static boolean isPrintLog = true; // // private BleLog() {} // // public static boolean isPrintLog() { // return isPrintLog; // } // // public static void setPrintLog(boolean isPrintLog) { // BleLog.isPrintLog = isPrintLog; // } // // public static void v(String tag, String msg) { // if (isPrintLog) { // Log.v(tag, msg); // } // } // // public static void d(String tag, String msg) { // if (isPrintLog) { // Log.d(tag, msg); // } // } // // public static void i(String tag, String msg) { // if (isPrintLog) { // Log.i(tag, msg); // } // } // // public static void w(String tag, String msg) { // if (isPrintLog) { // Log.w(tag, msg); // } // } // // public static void e(String tag, String msg) { // if (isPrintLog) { // Log.e(tag, msg); // } // } // } // Path: example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/app/AppHolder.java import android.app.Application; import android.content.Context; import com.activeandroid.ActiveAndroid; import com.github.captain_miao.android.ble.utils.BleLog; package com.github.captain_miao.android.bluetoothletutorial.app; public class AppHolder extends Application { private static final String TAG = "AppHolder"; private static AppHolder _instance; public static AppHolder getInstance() { return _instance; } public static Context getContext() { return _instance.getApplicationContext(); } @Override public void onCreate() { super.onCreate(); ActiveAndroid.initialize(this);
BleLog.setPrintLog(true);
captain-miao/bleYan
example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/model/BleLogInfo.java
// Path: example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/constant/BleLogLevel.java // public class BleLogLevel { // // public static final int VERBOSE = Log.VERBOSE; // public static final int DEBUG = Log.DEBUG; // public static final int INFO = Log.INFO; // public static final int WARN = Log.WARN; // public static final int ERROR = Log.ERROR; // public static final int ASSERT = Log.ASSERT; // }
import com.activeandroid.Model; import com.activeandroid.annotation.Column; import com.activeandroid.query.Select; import com.github.captain_miao.android.bluetoothletutorial.constant.BleLogLevel;
package com.github.captain_miao.android.bluetoothletutorial.model; /** * @author Yan Lu * @since 2016-08-28 */ public class BleLogInfo extends Model { @Column(unique = true, onUniqueConflict = Column.ConflictAction.REPLACE) public long logTime; @Column() public String log; @Column() public int logLevel; public BleLogInfo() { } public BleLogInfo(String log, int logLevel) { this.logTime = System.currentTimeMillis(); this.log = log == null ? "" : log; this.logLevel = logLevel; } public BleLogInfo(long logTime, String log, int logLevel) { this.logTime = logTime; this.log = log; this.logLevel = logLevel; } public static BleLogInfo getLogs(long beginTime, long endTime) { BleLogInfo logs = new Select() .from(BleLogInfo.class) .where("logTime >=?", beginTime) .and("logTime <=?", endTime) .executeSingle(); if(logs == null) {
// Path: example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/constant/BleLogLevel.java // public class BleLogLevel { // // public static final int VERBOSE = Log.VERBOSE; // public static final int DEBUG = Log.DEBUG; // public static final int INFO = Log.INFO; // public static final int WARN = Log.WARN; // public static final int ERROR = Log.ERROR; // public static final int ASSERT = Log.ASSERT; // } // Path: example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/model/BleLogInfo.java import com.activeandroid.Model; import com.activeandroid.annotation.Column; import com.activeandroid.query.Select; import com.github.captain_miao.android.bluetoothletutorial.constant.BleLogLevel; package com.github.captain_miao.android.bluetoothletutorial.model; /** * @author Yan Lu * @since 2016-08-28 */ public class BleLogInfo extends Model { @Column(unique = true, onUniqueConflict = Column.ConflictAction.REPLACE) public long logTime; @Column() public String log; @Column() public int logLevel; public BleLogInfo() { } public BleLogInfo(String log, int logLevel) { this.logTime = System.currentTimeMillis(); this.log = log == null ? "" : log; this.logLevel = logLevel; } public BleLogInfo(long logTime, String log, int logLevel) { this.logTime = logTime; this.log = log; this.logLevel = logLevel; } public static BleLogInfo getLogs(long beginTime, long endTime) { BleLogInfo logs = new Select() .from(BleLogInfo.class) .where("logTime >=?", beginTime) .and("logTime <=?", endTime) .executeSingle(); if(logs == null) {
logs = new BleLogInfo("", BleLogLevel.VERBOSE);
captain-miao/bleYan
blelibrary/src/main/java/com/github/captain_miao/android/ble/SimpleScanCallback.java
// Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/constant/BleScanState.java // public enum BleScanState { // // SCAN_TIMEOUT(-2, "SCAN_SUCCESS_TIME_OUT"), // BLUETOOTH_OFF(-1, "BLUETOOTH_OFF"), // SCAN_SUCCESS(0, "SCAN_SUCCESS"), // SCAN_FAILED_ALREADY_STARTED(1, "SCAN_FAILED_ALREADY_STARTED"), // SCAN_FAILED_APPLICATION_REGISTRATION_FAILED(2, "SCAN_FAILED_APPLICATION_REGISTRATION_FAILED"), // SCAN_FAILED_INTERNAL_ERROR(3, "SCAN_FAILED_INTERNAL_ERROR"), // SCAN_FAILED_FEATURE_UNSUPPORTED(4, "SCAN_FAILED_FEATURE_UNSUPPORTED"), // SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES(5, "SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES"); // // // BleScanState(int code, String message) { // this.code = code; // this.message = message; // } // // private int code; // private String message; // // public int getCode() { // return code; // } // // // public String getMessage() { // return message; // } // // public static BleScanState newInstance(int code) { // switch (code) { // case -2: // return BleScanState.SCAN_TIMEOUT; // case -1: // return BleScanState.BLUETOOTH_OFF; // // case 1: // return BleScanState.SCAN_FAILED_ALREADY_STARTED; // case 2: // return BleScanState.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED; // case 3: // return BleScanState.SCAN_FAILED_INTERNAL_ERROR; // case 4: // return BleScanState.SCAN_FAILED_FEATURE_UNSUPPORTED; // case 5: // return BleScanState.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES; // default: // return BleScanState.SCAN_SUCCESS; // } // } // }
import android.bluetooth.BluetoothDevice; import com.github.captain_miao.android.ble.constant.BleScanState;
package com.github.captain_miao.android.ble; /** * @author YanLu * @since 15/9/14 */ public interface SimpleScanCallback { /** * Callback reporting an LE device found during a device scan initiated * by the BluetoothAdapter#startLeScan function. * * @param device Identifies the remote device * @param rssi The RSSI value for the remote device as reported by the * Bluetooth hardware. 0 if no RSSI value is available. * @param scanRecord The content of the advertisement record offered by * the remote device. */ void onBleScan(BluetoothDevice device, int rssi, byte[] scanRecord); /** * Callback when scan could not be started. * * @param scanState Error code (one of SCAN_FAILED_*) for scan failure. */
// Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/constant/BleScanState.java // public enum BleScanState { // // SCAN_TIMEOUT(-2, "SCAN_SUCCESS_TIME_OUT"), // BLUETOOTH_OFF(-1, "BLUETOOTH_OFF"), // SCAN_SUCCESS(0, "SCAN_SUCCESS"), // SCAN_FAILED_ALREADY_STARTED(1, "SCAN_FAILED_ALREADY_STARTED"), // SCAN_FAILED_APPLICATION_REGISTRATION_FAILED(2, "SCAN_FAILED_APPLICATION_REGISTRATION_FAILED"), // SCAN_FAILED_INTERNAL_ERROR(3, "SCAN_FAILED_INTERNAL_ERROR"), // SCAN_FAILED_FEATURE_UNSUPPORTED(4, "SCAN_FAILED_FEATURE_UNSUPPORTED"), // SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES(5, "SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES"); // // // BleScanState(int code, String message) { // this.code = code; // this.message = message; // } // // private int code; // private String message; // // public int getCode() { // return code; // } // // // public String getMessage() { // return message; // } // // public static BleScanState newInstance(int code) { // switch (code) { // case -2: // return BleScanState.SCAN_TIMEOUT; // case -1: // return BleScanState.BLUETOOTH_OFF; // // case 1: // return BleScanState.SCAN_FAILED_ALREADY_STARTED; // case 2: // return BleScanState.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED; // case 3: // return BleScanState.SCAN_FAILED_INTERNAL_ERROR; // case 4: // return BleScanState.SCAN_FAILED_FEATURE_UNSUPPORTED; // case 5: // return BleScanState.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES; // default: // return BleScanState.SCAN_SUCCESS; // } // } // } // Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/SimpleScanCallback.java import android.bluetooth.BluetoothDevice; import com.github.captain_miao.android.ble.constant.BleScanState; package com.github.captain_miao.android.ble; /** * @author YanLu * @since 15/9/14 */ public interface SimpleScanCallback { /** * Callback reporting an LE device found during a device scan initiated * by the BluetoothAdapter#startLeScan function. * * @param device Identifies the remote device * @param rssi The RSSI value for the remote device as reported by the * Bluetooth hardware. 0 if no RSSI value is available. * @param scanRecord The content of the advertisement record offered by * the remote device. */ void onBleScan(BluetoothDevice device, int rssi, byte[] scanRecord); /** * Callback when scan could not be started. * * @param scanState Error code (one of SCAN_FAILED_*) for scan failure. */
void onBleScanFailed(BleScanState scanState);
captain-miao/bleYan
blelibrary/src/main/java/com/github/captain_miao/android/ble/ConnectCallback.java
// Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/constant/ConnectError.java // public enum ConnectError { // // ConnectTimeout(-3, "CONNECT_TIME_OUT"), // InvalidStatus(-6, "BLUETOOTH_INVALID_STATUS"); // // // ConnectError(int code, String message) { // this.code = code; // this.message = message; // } // // private int code; // private String message; // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // }
import com.github.captain_miao.android.ble.constant.ConnectError;
package com.github.captain_miao.android.ble; public abstract class ConnectCallback { public abstract void onConnectSuccess();
// Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/constant/ConnectError.java // public enum ConnectError { // // ConnectTimeout(-3, "CONNECT_TIME_OUT"), // InvalidStatus(-6, "BLUETOOTH_INVALID_STATUS"); // // // ConnectError(int code, String message) { // this.code = code; // this.message = message; // } // // private int code; // private String message; // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // } // Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/ConnectCallback.java import com.github.captain_miao.android.ble.constant.ConnectError; package com.github.captain_miao.android.ble; public abstract class ConnectCallback { public abstract void onConnectSuccess();
public abstract void onConnectFailed(ConnectError error);
Techjar/VivecraftForgeExtensions_110
src/main/java/com/techjar/vivecraftforge/network/packet/PacketMoveMode.java
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // }
import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP;
package com.techjar.vivecraftforge.network.packet; public class PacketMoveMode implements IPacket { public boolean freeMove; public PacketMoveMode() { } public PacketMoveMode(boolean freeMove) { this.freeMove = freeMove; } @Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeBoolean(freeMove); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { freeMove = buffer.readBoolean(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // } // Path: src/main/java/com/techjar/vivecraftforge/network/packet/PacketMoveMode.java import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP; package com.techjar.vivecraftforge.network.packet; public class PacketMoveMode implements IPacket { public boolean freeMove; public PacketMoveMode() { } public PacketMoveMode(boolean freeMove) { this.freeMove = freeMove; } @Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeBoolean(freeMove); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { freeMove = buffer.readBoolean(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
VRPlayerData data = PlayerTracker.getPlayerData(player);
Techjar/VivecraftForgeExtensions_110
src/main/java/com/techjar/vivecraftforge/network/packet/PacketMoveMode.java
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // }
import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP;
package com.techjar.vivecraftforge.network.packet; public class PacketMoveMode implements IPacket { public boolean freeMove; public PacketMoveMode() { } public PacketMoveMode(boolean freeMove) { this.freeMove = freeMove; } @Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeBoolean(freeMove); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { freeMove = buffer.readBoolean(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // } // Path: src/main/java/com/techjar/vivecraftforge/network/packet/PacketMoveMode.java import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP; package com.techjar.vivecraftforge.network.packet; public class PacketMoveMode implements IPacket { public boolean freeMove; public PacketMoveMode() { } public PacketMoveMode(boolean freeMove) { this.freeMove = freeMove; } @Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeBoolean(freeMove); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { freeMove = buffer.readBoolean(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
VRPlayerData data = PlayerTracker.getPlayerData(player);
Techjar/VivecraftForgeExtensions_110
src/main/java/com/techjar/vivecraftforge/network/packet/PacketDraw.java
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // }
import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP;
package com.techjar.vivecraftforge.network.packet; public class PacketDraw implements IPacket { public float drawDist; public PacketDraw() { } public PacketDraw(float drawDist) { this.drawDist = drawDist; } @Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeFloat(drawDist); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { drawDist = buffer.readFloat(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // } // Path: src/main/java/com/techjar/vivecraftforge/network/packet/PacketDraw.java import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP; package com.techjar.vivecraftforge.network.packet; public class PacketDraw implements IPacket { public float drawDist; public PacketDraw() { } public PacketDraw(float drawDist) { this.drawDist = drawDist; } @Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeFloat(drawDist); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { drawDist = buffer.readFloat(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
VRPlayerData data = PlayerTracker.getPlayerData(player);
Techjar/VivecraftForgeExtensions_110
src/main/java/com/techjar/vivecraftforge/network/packet/PacketDraw.java
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // }
import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP;
package com.techjar.vivecraftforge.network.packet; public class PacketDraw implements IPacket { public float drawDist; public PacketDraw() { } public PacketDraw(float drawDist) { this.drawDist = drawDist; } @Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeFloat(drawDist); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { drawDist = buffer.readFloat(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // } // Path: src/main/java/com/techjar/vivecraftforge/network/packet/PacketDraw.java import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP; package com.techjar.vivecraftforge.network.packet; public class PacketDraw implements IPacket { public float drawDist; public PacketDraw() { } public PacketDraw(float drawDist) { this.drawDist = drawDist; } @Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeFloat(drawDist); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { drawDist = buffer.readFloat(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
VRPlayerData data = PlayerTracker.getPlayerData(player);
Techjar/VivecraftForgeExtensions_110
src/main/java/com/techjar/vivecraftforge/core/asm/ASMClassHandler.java
// Path: src/main/java/com/techjar/vivecraftforge/util/VivecraftForgeLog.java // public class VivecraftForgeLog { // public static void info(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.INFO, message, data); // } // // public static void warning(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.WARN, message, data); // } // // public static void severe(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.ERROR, message, data); // } // // public static void debug(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.DEBUG, message, data); // } // }
import java.util.ArrayList; import java.util.Iterator; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; import com.techjar.vivecraftforge.util.VivecraftForgeLog;
package com.techjar.vivecraftforge.core.asm; public abstract class ASMClassHandler { public abstract ClassTuple getDesiredClass(); public abstract ASMMethodHandler[] getMethodHandlers(); public abstract boolean getComputeFrames(); public boolean shouldPatchClass() { return true; } protected void patchClass(ClassNode node, boolean obfuscated) { } public final byte[] patchClass(byte[] bytes, boolean obfuscated) { ClassNode classNode = new ClassNode(); ClassReader classReader = new ClassReader(bytes); classReader.accept(classNode, 0); patchClass(classNode, obfuscated); ASMMethodHandler[] handlers = getMethodHandlers(); ArrayList<MethodNode> methodsCopy = new ArrayList<MethodNode>(classNode.methods); for (Iterator<MethodNode> methods = methodsCopy.iterator(); methods.hasNext(); ) { MethodNode method = methods.next(); for (ASMMethodHandler handler : handlers) { MethodTuple tuple = handler.getDesiredMethod(); if ((method.name.equals(tuple.methodName) && method.desc.equals(tuple.methodDesc)) || (method.name.equals(tuple.methodNameObf) && method.desc.equals(tuple.methodDescObf))) {
// Path: src/main/java/com/techjar/vivecraftforge/util/VivecraftForgeLog.java // public class VivecraftForgeLog { // public static void info(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.INFO, message, data); // } // // public static void warning(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.WARN, message, data); // } // // public static void severe(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.ERROR, message, data); // } // // public static void debug(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.DEBUG, message, data); // } // } // Path: src/main/java/com/techjar/vivecraftforge/core/asm/ASMClassHandler.java import java.util.ArrayList; import java.util.Iterator; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; import com.techjar.vivecraftforge.util.VivecraftForgeLog; package com.techjar.vivecraftforge.core.asm; public abstract class ASMClassHandler { public abstract ClassTuple getDesiredClass(); public abstract ASMMethodHandler[] getMethodHandlers(); public abstract boolean getComputeFrames(); public boolean shouldPatchClass() { return true; } protected void patchClass(ClassNode node, boolean obfuscated) { } public final byte[] patchClass(byte[] bytes, boolean obfuscated) { ClassNode classNode = new ClassNode(); ClassReader classReader = new ClassReader(bytes); classReader.accept(classNode, 0); patchClass(classNode, obfuscated); ASMMethodHandler[] handlers = getMethodHandlers(); ArrayList<MethodNode> methodsCopy = new ArrayList<MethodNode>(classNode.methods); for (Iterator<MethodNode> methods = methodsCopy.iterator(); methods.hasNext(); ) { MethodNode method = methods.next(); for (ASMMethodHandler handler : handlers) { MethodTuple tuple = handler.getDesiredMethod(); if ((method.name.equals(tuple.methodName) && method.desc.equals(tuple.methodDesc)) || (method.name.equals(tuple.methodNameObf) && method.desc.equals(tuple.methodDescObf))) {
VivecraftForgeLog.debug("Patching method: " + method.name + method.desc + (obfuscated ? " (" + tuple.methodName + tuple.methodDesc + ")" : ""));
Techjar/VivecraftForgeExtensions_110
src/main/java/com/techjar/vivecraftforge/core/asm/ClassTransformer.java
// Path: src/main/java/com/techjar/vivecraftforge/util/VivecraftForgeLog.java // public class VivecraftForgeLog { // public static void info(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.INFO, message, data); // } // // public static void warning(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.WARN, message, data); // } // // public static void severe(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.ERROR, message, data); // } // // public static void debug(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.DEBUG, message, data); // } // }
import java.util.ArrayList; import java.util.List; import com.techjar.vivecraftforge.core.asm.handler.*; import com.techjar.vivecraftforge.util.VivecraftForgeLog; import net.minecraft.launchwrapper.IClassTransformer;
package com.techjar.vivecraftforge.core.asm; public class ClassTransformer implements IClassTransformer { private static final List<ASMClassHandler> asmHandlers = new ArrayList<ASMClassHandler>(); static { asmHandlers.add(new ASMHandlerIncreaseReachDistance()); asmHandlers.add(new ASMHandlerCreeperRadius()); asmHandlers.add(new ASMHandlerEndermanLook()); asmHandlers.add(new ASMHandlerRubberBanding()); } @Override public byte[] transform(String name, String transformedName, byte[] bytes) { for (ASMClassHandler handler : asmHandlers) { if (!handler.shouldPatchClass()) continue; ClassTuple tuple = handler.getDesiredClass(); if (name.equals(tuple.classNameObf)) {
// Path: src/main/java/com/techjar/vivecraftforge/util/VivecraftForgeLog.java // public class VivecraftForgeLog { // public static void info(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.INFO, message, data); // } // // public static void warning(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.WARN, message, data); // } // // public static void severe(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.ERROR, message, data); // } // // public static void debug(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.DEBUG, message, data); // } // } // Path: src/main/java/com/techjar/vivecraftforge/core/asm/ClassTransformer.java import java.util.ArrayList; import java.util.List; import com.techjar.vivecraftforge.core.asm.handler.*; import com.techjar.vivecraftforge.util.VivecraftForgeLog; import net.minecraft.launchwrapper.IClassTransformer; package com.techjar.vivecraftforge.core.asm; public class ClassTransformer implements IClassTransformer { private static final List<ASMClassHandler> asmHandlers = new ArrayList<ASMClassHandler>(); static { asmHandlers.add(new ASMHandlerIncreaseReachDistance()); asmHandlers.add(new ASMHandlerCreeperRadius()); asmHandlers.add(new ASMHandlerEndermanLook()); asmHandlers.add(new ASMHandlerRubberBanding()); } @Override public byte[] transform(String name, String transformedName, byte[] bytes) { for (ASMClassHandler handler : asmHandlers) { if (!handler.shouldPatchClass()) continue; ClassTuple tuple = handler.getDesiredClass(); if (name.equals(tuple.classNameObf)) {
VivecraftForgeLog.debug("Patching class: " + name + " (" + tuple.className + ") using " + handler.getClass().getSimpleName());
Techjar/VivecraftForgeExtensions_110
src/main/java/com/techjar/vivecraftforge/core/FMLPlugin.java
// Path: src/main/java/com/techjar/vivecraftforge/core/asm/ClassTransformer.java // public class ClassTransformer implements IClassTransformer { // private static final List<ASMClassHandler> asmHandlers = new ArrayList<ASMClassHandler>(); // static { // asmHandlers.add(new ASMHandlerIncreaseReachDistance()); // asmHandlers.add(new ASMHandlerCreeperRadius()); // asmHandlers.add(new ASMHandlerEndermanLook()); // asmHandlers.add(new ASMHandlerRubberBanding()); // } // // @Override // public byte[] transform(String name, String transformedName, byte[] bytes) { // for (ASMClassHandler handler : asmHandlers) { // if (!handler.shouldPatchClass()) continue; // ClassTuple tuple = handler.getDesiredClass(); // if (name.equals(tuple.classNameObf)) { // VivecraftForgeLog.debug("Patching class: " + name + " (" + tuple.className + ") using " + handler.getClass().getSimpleName()); // bytes = handler.patchClass(bytes, true); // } else if (name.equals(tuple.className)) { // VivecraftForgeLog.debug("Patching class: " + name + " using " + handler.getClass().getSimpleName()); // bytes = handler.patchClass(bytes, false); // } // } // return bytes; // } // }
import java.io.File; import java.util.Map; import com.techjar.vivecraftforge.core.asm.ClassTransformer; import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin;
package com.techjar.vivecraftforge.core; @IFMLLoadingPlugin.Name("Vivecraft Forge Extensions Core") @IFMLLoadingPlugin.MCVersion("1.10.2") @IFMLLoadingPlugin.TransformerExclusions("com.techjar.vivecraftforge.core") //@SortingIndex(1001) public class FMLPlugin implements IFMLLoadingPlugin { public static File location; @Override public String[] getASMTransformerClass() {
// Path: src/main/java/com/techjar/vivecraftforge/core/asm/ClassTransformer.java // public class ClassTransformer implements IClassTransformer { // private static final List<ASMClassHandler> asmHandlers = new ArrayList<ASMClassHandler>(); // static { // asmHandlers.add(new ASMHandlerIncreaseReachDistance()); // asmHandlers.add(new ASMHandlerCreeperRadius()); // asmHandlers.add(new ASMHandlerEndermanLook()); // asmHandlers.add(new ASMHandlerRubberBanding()); // } // // @Override // public byte[] transform(String name, String transformedName, byte[] bytes) { // for (ASMClassHandler handler : asmHandlers) { // if (!handler.shouldPatchClass()) continue; // ClassTuple tuple = handler.getDesiredClass(); // if (name.equals(tuple.classNameObf)) { // VivecraftForgeLog.debug("Patching class: " + name + " (" + tuple.className + ") using " + handler.getClass().getSimpleName()); // bytes = handler.patchClass(bytes, true); // } else if (name.equals(tuple.className)) { // VivecraftForgeLog.debug("Patching class: " + name + " using " + handler.getClass().getSimpleName()); // bytes = handler.patchClass(bytes, false); // } // } // return bytes; // } // } // Path: src/main/java/com/techjar/vivecraftforge/core/FMLPlugin.java import java.io.File; import java.util.Map; import com.techjar.vivecraftforge.core.asm.ClassTransformer; import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin; package com.techjar.vivecraftforge.core; @IFMLLoadingPlugin.Name("Vivecraft Forge Extensions Core") @IFMLLoadingPlugin.MCVersion("1.10.2") @IFMLLoadingPlugin.TransformerExclusions("com.techjar.vivecraftforge.core") //@SortingIndex(1001) public class FMLPlugin implements IFMLLoadingPlugin { public static File location; @Override public String[] getASMTransformerClass() {
return new String[]{ClassTransformer.class.getName()};
Techjar/VivecraftForgeExtensions_110
src/main/java/com/techjar/vivecraftforge/network/packet/PacketController1Data.java
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // }
import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP;
@Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeBoolean(handsReversed); buffer.writeFloat(posX); buffer.writeFloat(posY); buffer.writeFloat(posZ); buffer.writeFloat(rotW); buffer.writeFloat(rotX); buffer.writeFloat(rotY); buffer.writeFloat(rotZ); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { handsReversed = buffer.readBoolean(); posX = buffer.readFloat(); posY = buffer.readFloat(); posZ = buffer.readFloat(); rotW = buffer.readFloat(); rotX = buffer.readFloat(); rotY = buffer.readFloat(); rotZ = buffer.readFloat(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // } // Path: src/main/java/com/techjar/vivecraftforge/network/packet/PacketController1Data.java import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP; @Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeBoolean(handsReversed); buffer.writeFloat(posX); buffer.writeFloat(posY); buffer.writeFloat(posZ); buffer.writeFloat(rotW); buffer.writeFloat(rotX); buffer.writeFloat(rotY); buffer.writeFloat(rotZ); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { handsReversed = buffer.readBoolean(); posX = buffer.readFloat(); posY = buffer.readFloat(); posZ = buffer.readFloat(); rotW = buffer.readFloat(); rotX = buffer.readFloat(); rotY = buffer.readFloat(); rotZ = buffer.readFloat(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
VRPlayerData data = PlayerTracker.getPlayerData(player);
Techjar/VivecraftForgeExtensions_110
src/main/java/com/techjar/vivecraftforge/network/packet/PacketController1Data.java
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // }
import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP;
@Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeBoolean(handsReversed); buffer.writeFloat(posX); buffer.writeFloat(posY); buffer.writeFloat(posZ); buffer.writeFloat(rotW); buffer.writeFloat(rotX); buffer.writeFloat(rotY); buffer.writeFloat(rotZ); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { handsReversed = buffer.readBoolean(); posX = buffer.readFloat(); posY = buffer.readFloat(); posZ = buffer.readFloat(); rotW = buffer.readFloat(); rotX = buffer.readFloat(); rotY = buffer.readFloat(); rotZ = buffer.readFloat(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // } // Path: src/main/java/com/techjar/vivecraftforge/network/packet/PacketController1Data.java import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP; @Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeBoolean(handsReversed); buffer.writeFloat(posX); buffer.writeFloat(posY); buffer.writeFloat(posZ); buffer.writeFloat(rotW); buffer.writeFloat(rotX); buffer.writeFloat(rotY); buffer.writeFloat(rotZ); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { handsReversed = buffer.readBoolean(); posX = buffer.readFloat(); posY = buffer.readFloat(); posZ = buffer.readFloat(); rotW = buffer.readFloat(); rotX = buffer.readFloat(); rotY = buffer.readFloat(); rotZ = buffer.readFloat(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
VRPlayerData data = PlayerTracker.getPlayerData(player);
Techjar/VivecraftForgeExtensions_110
src/main/java/com/techjar/vivecraftforge/network/PacketHandlerClient.java
// Path: src/main/java/com/techjar/vivecraftforge/util/VivecraftForgeLog.java // public class VivecraftForgeLog { // public static void info(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.INFO, message, data); // } // // public static void warning(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.WARN, message, data); // } // // public static void severe(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.ERROR, message, data); // } // // public static void debug(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.DEBUG, message, data); // } // }
import com.techjar.vivecraftforge.util.VivecraftForgeLog; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.relauncher.Side;
package com.techjar.vivecraftforge.network; @Sharable public class PacketHandlerClient extends SimpleChannelInboundHandler<IPacket> { @Override protected void channelRead0(ChannelHandlerContext ctx, IPacket msg) throws Exception { if (ctx.channel().attr(NetworkRegistry.CHANNEL_SOURCE).get() != Side.CLIENT) return;
// Path: src/main/java/com/techjar/vivecraftforge/util/VivecraftForgeLog.java // public class VivecraftForgeLog { // public static void info(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.INFO, message, data); // } // // public static void warning(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.WARN, message, data); // } // // public static void severe(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.ERROR, message, data); // } // // public static void debug(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.DEBUG, message, data); // } // } // Path: src/main/java/com/techjar/vivecraftforge/network/PacketHandlerClient.java import com.techjar.vivecraftforge.util.VivecraftForgeLog; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.relauncher.Side; package com.techjar.vivecraftforge.network; @Sharable public class PacketHandlerClient extends SimpleChannelInboundHandler<IPacket> { @Override protected void channelRead0(ChannelHandlerContext ctx, IPacket msg) throws Exception { if (ctx.channel().attr(NetworkRegistry.CHANNEL_SOURCE).get() != Side.CLIENT) return;
VivecraftForgeLog.warning("Should never receive a client packet!");
Techjar/VivecraftForgeExtensions_110
src/main/java/com/techjar/vivecraftforge/Config.java
// Path: src/main/java/com/techjar/vivecraftforge/util/BlockListMode.java // public enum BlockListMode { // DISABLED, // WHITELIST, // BLACKLIST; // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VivecraftForgeLog.java // public class VivecraftForgeLog { // public static void info(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.INFO, message, data); // } // // public static void warning(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.WARN, message, data); // } // // public static void severe(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.ERROR, message, data); // } // // public static void debug(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.DEBUG, message, data); // } // }
import com.google.common.collect.Lists; import com.google.common.primitives.Ints; import com.techjar.vivecraftforge.util.BlockListMode; import com.techjar.vivecraftforge.util.VivecraftForgeLog; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; import java.io.File; import java.util.ArrayList; import java.util.Iterator;
package com.techjar.vivecraftforge; public class Config { public static Configuration config; public static boolean vrOnly; public static double vrOnlyKickDelay; public static boolean printMoney; public static String vrOnlyKickMessage; public static boolean enableJoinMessages; public static String joinMessageVR; public static String joinMessageCompanion; public static double creeperSwellDistance; public static float movedTooQuicklyThreshold; public static double movedWronglyThreshold; public static boolean vrVsVR; public static boolean vrVsSeatedVR; public static boolean vrVsNonVR; public static boolean seatedVrVsSeatedVR; public static boolean seatedVrVsNonVR; public static float bowStandingMul; public static float bowSeatedMul; public static float bowStandingHeadshotMul; public static float bowSeatedHeadshotMul; public static boolean climbeyEnabled;
// Path: src/main/java/com/techjar/vivecraftforge/util/BlockListMode.java // public enum BlockListMode { // DISABLED, // WHITELIST, // BLACKLIST; // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VivecraftForgeLog.java // public class VivecraftForgeLog { // public static void info(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.INFO, message, data); // } // // public static void warning(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.WARN, message, data); // } // // public static void severe(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.ERROR, message, data); // } // // public static void debug(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.DEBUG, message, data); // } // } // Path: src/main/java/com/techjar/vivecraftforge/Config.java import com.google.common.collect.Lists; import com.google.common.primitives.Ints; import com.techjar.vivecraftforge.util.BlockListMode; import com.techjar.vivecraftforge.util.VivecraftForgeLog; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; import java.io.File; import java.util.ArrayList; import java.util.Iterator; package com.techjar.vivecraftforge; public class Config { public static Configuration config; public static boolean vrOnly; public static double vrOnlyKickDelay; public static boolean printMoney; public static String vrOnlyKickMessage; public static boolean enableJoinMessages; public static String joinMessageVR; public static String joinMessageCompanion; public static double creeperSwellDistance; public static float movedTooQuicklyThreshold; public static double movedWronglyThreshold; public static boolean vrVsVR; public static boolean vrVsSeatedVR; public static boolean vrVsNonVR; public static boolean seatedVrVsSeatedVR; public static boolean seatedVrVsNonVR; public static float bowStandingMul; public static float bowSeatedMul; public static float bowStandingHeadshotMul; public static float bowSeatedHeadshotMul; public static boolean climbeyEnabled;
public static BlockListMode blockListMode;
Techjar/VivecraftForgeExtensions_110
src/main/java/com/techjar/vivecraftforge/Config.java
// Path: src/main/java/com/techjar/vivecraftforge/util/BlockListMode.java // public enum BlockListMode { // DISABLED, // WHITELIST, // BLACKLIST; // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VivecraftForgeLog.java // public class VivecraftForgeLog { // public static void info(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.INFO, message, data); // } // // public static void warning(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.WARN, message, data); // } // // public static void severe(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.ERROR, message, data); // } // // public static void debug(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.DEBUG, message, data); // } // }
import com.google.common.collect.Lists; import com.google.common.primitives.Ints; import com.techjar.vivecraftforge.util.BlockListMode; import com.techjar.vivecraftforge.util.VivecraftForgeLog; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; import java.io.File; import java.util.ArrayList; import java.util.Iterator;
// VR Changes creeperSwellDistance = config.get("vrchanges", "creeperswelldistance", 1.75, "Distance at which creepers swell and explode for VR players. Default: 1.75, Vanilla: 3").getDouble(); movedTooQuicklyThreshold = (float)config.get("vrchanges", "movedtooquicklythreshold", 64.0, "Increase this if you experience rubber banding when teleporting.").getDouble(); movedWronglyThreshold = config.get("vrchanges", "movedwronglythreshold", 15.0, "Increase this if you experience rubber banding when teleporting.").getDouble(); // PvP vrVsVR = config.get("pvp", "vrvsvr", true, "Allows standing VR players to attack standing VR players.").getBoolean(); vrVsSeatedVR = config.get("pvp", "vrvsseatedvr", true, "Allows standing VR players to attack seated VR players.").getBoolean(); vrVsNonVR = config.get("pvp", "vrvsnonvr", true, "Allows standing VR players to attack non-VR players.").getBoolean(); seatedVrVsSeatedVR = config.get("pvp", "seatedvrvsseatedvr", true, "Allows seated VR players to attack seated VR players.").getBoolean(); seatedVrVsNonVR = config.get("pvp", "seatedvrvsnonvr", true, "Allows seated VR players to attack non-VR players.").getBoolean(); // Bow bowStandingMul = (float)config.get("bow", "standingmultiplier", 2.0, "Archery damage multiplier for standing VR players. Default: 2.0").getDouble(); bowSeatedMul = (float)config.get("bow", "seatedmultiplier", 1.0, "Archery damage multiplier for seated VR players. Default: 1.0").getDouble(); bowStandingHeadshotMul = (float)config.get("bow", "standingheadshotmultiplier", 3.0, "Archery headshot damage multiplier for standing VR players. Default: 3.0").getDouble(); bowSeatedHeadshotMul = (float)config.get("bow", "seatedheadshotmultiplier", 2.0, "Archery headshot damage multiplier for seated VR players. Default: 2.0").getDouble(); // Climbey climbeyEnabled = config.get("climbey", "enabled", true, "Whether or not climbey is allowed on this server.").getBoolean(); { Property prop = config.get("climbey", "blocklist", new String[]{"minecraft:wool:0", "minecraft:dirt", "grass"}, "List of blocks to whitelist or blacklist, in format blockname, blockname:meta, blockid or blockid:meta."); blockList = Lists.newArrayList(prop.getStringList()); boolean changed = false; for (Iterator<String> it = blockList.iterator(); it.hasNext();) { String str = it.next(); String fullStr = str; int colon = str.lastIndexOf(':'); if (colon != -1) { String meta = str.substring(colon + 1); str = str.substring(0, colon); if (Ints.tryParse(meta) == null) { if (str.indexOf(':') != -1) { // Extra colons, must be meta
// Path: src/main/java/com/techjar/vivecraftforge/util/BlockListMode.java // public enum BlockListMode { // DISABLED, // WHITELIST, // BLACKLIST; // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VivecraftForgeLog.java // public class VivecraftForgeLog { // public static void info(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.INFO, message, data); // } // // public static void warning(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.WARN, message, data); // } // // public static void severe(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.ERROR, message, data); // } // // public static void debug(String message, Object... data) { // FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.DEBUG, message, data); // } // } // Path: src/main/java/com/techjar/vivecraftforge/Config.java import com.google.common.collect.Lists; import com.google.common.primitives.Ints; import com.techjar.vivecraftforge.util.BlockListMode; import com.techjar.vivecraftforge.util.VivecraftForgeLog; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; import java.io.File; import java.util.ArrayList; import java.util.Iterator; // VR Changes creeperSwellDistance = config.get("vrchanges", "creeperswelldistance", 1.75, "Distance at which creepers swell and explode for VR players. Default: 1.75, Vanilla: 3").getDouble(); movedTooQuicklyThreshold = (float)config.get("vrchanges", "movedtooquicklythreshold", 64.0, "Increase this if you experience rubber banding when teleporting.").getDouble(); movedWronglyThreshold = config.get("vrchanges", "movedwronglythreshold", 15.0, "Increase this if you experience rubber banding when teleporting.").getDouble(); // PvP vrVsVR = config.get("pvp", "vrvsvr", true, "Allows standing VR players to attack standing VR players.").getBoolean(); vrVsSeatedVR = config.get("pvp", "vrvsseatedvr", true, "Allows standing VR players to attack seated VR players.").getBoolean(); vrVsNonVR = config.get("pvp", "vrvsnonvr", true, "Allows standing VR players to attack non-VR players.").getBoolean(); seatedVrVsSeatedVR = config.get("pvp", "seatedvrvsseatedvr", true, "Allows seated VR players to attack seated VR players.").getBoolean(); seatedVrVsNonVR = config.get("pvp", "seatedvrvsnonvr", true, "Allows seated VR players to attack non-VR players.").getBoolean(); // Bow bowStandingMul = (float)config.get("bow", "standingmultiplier", 2.0, "Archery damage multiplier for standing VR players. Default: 2.0").getDouble(); bowSeatedMul = (float)config.get("bow", "seatedmultiplier", 1.0, "Archery damage multiplier for seated VR players. Default: 1.0").getDouble(); bowStandingHeadshotMul = (float)config.get("bow", "standingheadshotmultiplier", 3.0, "Archery headshot damage multiplier for standing VR players. Default: 3.0").getDouble(); bowSeatedHeadshotMul = (float)config.get("bow", "seatedheadshotmultiplier", 2.0, "Archery headshot damage multiplier for seated VR players. Default: 2.0").getDouble(); // Climbey climbeyEnabled = config.get("climbey", "enabled", true, "Whether or not climbey is allowed on this server.").getBoolean(); { Property prop = config.get("climbey", "blocklist", new String[]{"minecraft:wool:0", "minecraft:dirt", "grass"}, "List of blocks to whitelist or blacklist, in format blockname, blockname:meta, blockid or blockid:meta."); blockList = Lists.newArrayList(prop.getStringList()); boolean changed = false; for (Iterator<String> it = blockList.iterator(); it.hasNext();) { String str = it.next(); String fullStr = str; int colon = str.lastIndexOf(':'); if (colon != -1) { String meta = str.substring(colon + 1); str = str.substring(0, colon); if (Ints.tryParse(meta) == null) { if (str.indexOf(':') != -1) { // Extra colons, must be meta
VivecraftForgeLog.warning("Invalid meta for blocklist item: %s", fullStr);
Techjar/VivecraftForgeExtensions_110
src/main/java/com/techjar/vivecraftforge/network/packet/PacketHeadData.java
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // }
import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP;
@Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeBoolean(seated); buffer.writeFloat(posX); buffer.writeFloat(posY); buffer.writeFloat(posZ); buffer.writeFloat(rotW); buffer.writeFloat(rotX); buffer.writeFloat(rotY); buffer.writeFloat(rotZ); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { seated = buffer.readBoolean(); posX = buffer.readFloat(); posY = buffer.readFloat(); posZ = buffer.readFloat(); rotW = buffer.readFloat(); rotX = buffer.readFloat(); rotY = buffer.readFloat(); rotZ = buffer.readFloat(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // } // Path: src/main/java/com/techjar/vivecraftforge/network/packet/PacketHeadData.java import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP; @Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeBoolean(seated); buffer.writeFloat(posX); buffer.writeFloat(posY); buffer.writeFloat(posZ); buffer.writeFloat(rotW); buffer.writeFloat(rotX); buffer.writeFloat(rotY); buffer.writeFloat(rotZ); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { seated = buffer.readBoolean(); posX = buffer.readFloat(); posY = buffer.readFloat(); posZ = buffer.readFloat(); rotW = buffer.readFloat(); rotX = buffer.readFloat(); rotY = buffer.readFloat(); rotZ = buffer.readFloat(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
VRPlayerData data = PlayerTracker.getPlayerData(player);
Techjar/VivecraftForgeExtensions_110
src/main/java/com/techjar/vivecraftforge/network/packet/PacketHeadData.java
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // }
import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP;
@Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeBoolean(seated); buffer.writeFloat(posX); buffer.writeFloat(posY); buffer.writeFloat(posZ); buffer.writeFloat(rotW); buffer.writeFloat(rotX); buffer.writeFloat(rotY); buffer.writeFloat(rotZ); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { seated = buffer.readBoolean(); posX = buffer.readFloat(); posY = buffer.readFloat(); posZ = buffer.readFloat(); rotW = buffer.readFloat(); rotX = buffer.readFloat(); rotY = buffer.readFloat(); rotZ = buffer.readFloat(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // } // Path: src/main/java/com/techjar/vivecraftforge/network/packet/PacketHeadData.java import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP; @Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeBoolean(seated); buffer.writeFloat(posX); buffer.writeFloat(posY); buffer.writeFloat(posZ); buffer.writeFloat(rotW); buffer.writeFloat(rotX); buffer.writeFloat(rotY); buffer.writeFloat(rotZ); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { seated = buffer.readBoolean(); posX = buffer.readFloat(); posY = buffer.readFloat(); posZ = buffer.readFloat(); rotW = buffer.readFloat(); rotX = buffer.readFloat(); rotY = buffer.readFloat(); rotZ = buffer.readFloat(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
VRPlayerData data = PlayerTracker.getPlayerData(player);
Techjar/VivecraftForgeExtensions_110
src/main/java/com/techjar/vivecraftforge/network/packet/PacketWorldScale.java
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // }
import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP;
package com.techjar.vivecraftforge.network.packet; public class PacketWorldScale implements IPacket { public float worldScale; public PacketWorldScale() { } @Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeFloat(worldScale); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { worldScale = buffer.readFloat(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // } // Path: src/main/java/com/techjar/vivecraftforge/network/packet/PacketWorldScale.java import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP; package com.techjar.vivecraftforge.network.packet; public class PacketWorldScale implements IPacket { public float worldScale; public PacketWorldScale() { } @Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeFloat(worldScale); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { worldScale = buffer.readFloat(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
VRPlayerData data = PlayerTracker.getPlayerData(player);
Techjar/VivecraftForgeExtensions_110
src/main/java/com/techjar/vivecraftforge/network/packet/PacketWorldScale.java
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // }
import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP;
package com.techjar.vivecraftforge.network.packet; public class PacketWorldScale implements IPacket { public float worldScale; public PacketWorldScale() { } @Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeFloat(worldScale); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { worldScale = buffer.readFloat(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // } // Path: src/main/java/com/techjar/vivecraftforge/network/packet/PacketWorldScale.java import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP; package com.techjar.vivecraftforge.network.packet; public class PacketWorldScale implements IPacket { public float worldScale; public PacketWorldScale() { } @Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeFloat(worldScale); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { worldScale = buffer.readFloat(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
VRPlayerData data = PlayerTracker.getPlayerData(player);
Techjar/VivecraftForgeExtensions_110
src/main/java/com/techjar/vivecraftforge/network/packet/PacketController0Data.java
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // }
import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP;
@Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeBoolean(handsReversed); buffer.writeFloat(posX); buffer.writeFloat(posY); buffer.writeFloat(posZ); buffer.writeFloat(rotW); buffer.writeFloat(rotX); buffer.writeFloat(rotY); buffer.writeFloat(rotZ); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { handsReversed = buffer.readBoolean(); posX = buffer.readFloat(); posY = buffer.readFloat(); posZ = buffer.readFloat(); rotW = buffer.readFloat(); rotX = buffer.readFloat(); rotY = buffer.readFloat(); rotZ = buffer.readFloat(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // } // Path: src/main/java/com/techjar/vivecraftforge/network/packet/PacketController0Data.java import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP; @Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeBoolean(handsReversed); buffer.writeFloat(posX); buffer.writeFloat(posY); buffer.writeFloat(posZ); buffer.writeFloat(rotW); buffer.writeFloat(rotX); buffer.writeFloat(rotY); buffer.writeFloat(rotZ); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { handsReversed = buffer.readBoolean(); posX = buffer.readFloat(); posY = buffer.readFloat(); posZ = buffer.readFloat(); rotW = buffer.readFloat(); rotX = buffer.readFloat(); rotY = buffer.readFloat(); rotZ = buffer.readFloat(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
VRPlayerData data = PlayerTracker.getPlayerData(player);
Techjar/VivecraftForgeExtensions_110
src/main/java/com/techjar/vivecraftforge/network/packet/PacketController0Data.java
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // }
import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP;
@Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeBoolean(handsReversed); buffer.writeFloat(posX); buffer.writeFloat(posY); buffer.writeFloat(posZ); buffer.writeFloat(rotW); buffer.writeFloat(rotX); buffer.writeFloat(rotY); buffer.writeFloat(rotZ); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { handsReversed = buffer.readBoolean(); posX = buffer.readFloat(); posY = buffer.readFloat(); posZ = buffer.readFloat(); rotW = buffer.readFloat(); rotX = buffer.readFloat(); rotY = buffer.readFloat(); rotZ = buffer.readFloat(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
// Path: src/main/java/com/techjar/vivecraftforge/network/IPacket.java // public interface IPacket { // void encodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void decodePacket(ChannelHandlerContext context, ByteBuf buffer); // // void handleClient(EntityPlayerSP player); // // void handleServer(EntityPlayerMP player); // } // // Path: src/main/java/com/techjar/vivecraftforge/util/PlayerTracker.java // public class PlayerTracker { // public static Map<UUID, VRPlayerData> players = new HashMap<UUID, VRPlayerData>(); // public static Set<UUID> companionPlayers = new HashSet<UUID>(); // // public static void tick() { // for (Iterator<Map.Entry<UUID, VRPlayerData>> it = players.entrySet().iterator(); it.hasNext();) { // Map.Entry<UUID, VRPlayerData> entry = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(entry.getKey()); // if (entity == null) { // it.remove(); // } // } // for (Iterator<UUID> it = companionPlayers.iterator(); it.hasNext();) { // UUID uuid = it.next(); // Entity entity = FMLCommonHandler.instance().getMinecraftServerInstance().getEntityFromUuid(uuid); // if (entity == null) { // it.remove(); // } // } // } // // public static VRPlayerData getPlayerData(EntityPlayer entity) { // return players.get(entity.getGameProfile().getId()); // } // // public static boolean hasPlayerData(EntityPlayer entity) { // return players.containsKey(entity.getGameProfile().getId()); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid, VRPlayerData data) { // PacketHeadData headData = new PacketHeadData(data.seated, data.head.posX, data.head.posY, data.head.posZ, data.head.rotW, data.head.rotX, data.head.rotY, data.head.rotZ); // PacketController0Data controller0Data = new PacketController0Data(data.handsReversed, data.controller0.posX, data.controller0.posY, data.controller0.posZ, data.controller0.rotW, data.controller0.rotX, data.controller0.rotY, data.controller0.rotZ); // PacketController1Data controller1Data = new PacketController1Data(data.handsReversed, data.controller1.posX, data.controller1.posY, data.controller1.posZ, data.controller1.rotW, data.controller1.rotX, data.controller1.rotY, data.controller1.rotZ); // return new PacketUberPacket(uuid, headData, controller0Data, controller1Data); // } // // public static PacketUberPacket getPlayerDataPacket(UUID uuid) { // VRPlayerData data = players.get(uuid); // if (data != null) { // return getPlayerDataPacket(uuid, data); // } // return null; // } // // public static PacketUberPacket getPlayerDataPacket(EntityPlayer entity) { // VRPlayerData data = players.get(entity.getGameProfile().getId()); // if (data != null) { // getPlayerDataPacket(entity.getGameProfile().getId(), data); // } // return null; // } // } // // Path: src/main/java/com/techjar/vivecraftforge/util/VRPlayerData.java // public class VRPlayerData { // public ObjectInfo head = new ObjectInfo(); // public ObjectInfo controller0 = new ObjectInfo(); // public ObjectInfo controller1 = new ObjectInfo(); // public boolean handsReversed; // public float worldScale; // public boolean seated; // public boolean freeMove; // public float bowDraw; // // public static class ObjectInfo { // public float posX; // public float posY; // public float posZ; // public float rotW; // public float rotX; // public float rotY; // public float rotZ; // } // } // Path: src/main/java/com/techjar/vivecraftforge/network/packet/PacketController0Data.java import com.techjar.vivecraftforge.network.IPacket; import com.techjar.vivecraftforge.util.PlayerTracker; import com.techjar.vivecraftforge.util.VRPlayerData; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayerMP; @Override public void encodePacket(ChannelHandlerContext context, ByteBuf buffer) { buffer.writeBoolean(handsReversed); buffer.writeFloat(posX); buffer.writeFloat(posY); buffer.writeFloat(posZ); buffer.writeFloat(rotW); buffer.writeFloat(rotX); buffer.writeFloat(rotY); buffer.writeFloat(rotZ); } @Override public void decodePacket(ChannelHandlerContext context, ByteBuf buffer) { handsReversed = buffer.readBoolean(); posX = buffer.readFloat(); posY = buffer.readFloat(); posZ = buffer.readFloat(); rotW = buffer.readFloat(); rotX = buffer.readFloat(); rotY = buffer.readFloat(); rotZ = buffer.readFloat(); } @Override public void handleClient(EntityPlayerSP player) { } @Override public void handleServer(EntityPlayerMP player) {
VRPlayerData data = PlayerTracker.getPlayerData(player);
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/common/IdSet.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.io.Serializable; import java.util.*;
public static IdSet ids(Integer... ids) { return new IdSet(ids); } /** * Initialise an ID set containing a collection of IDs. Additional IDs may be added. * @param ids Initial set of IDs to add to the ID set. * @return A new ID set containing the given IDs. */ public static IdSet ids(Collection<Integer> ids) { return new IdSet(ids); } /** * Initialise an ID set with a single range of IDs. Additional IDs may be added. * @param from first ID (inclusive) * @param to last ID (inclusive) * @return A new ID set for the given range of IDs. */ public static IdSet range(int from, int to) { IdSet idSet = new IdSet(); return idSet.addRange(from, to); } /** * Parse the string representation of an ID set. * @param str A string ID set. * @return */ public static IdSet parse(String str) {
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/common/IdSet.java import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.io.Serializable; import java.util.*; public static IdSet ids(Integer... ids) { return new IdSet(ids); } /** * Initialise an ID set containing a collection of IDs. Additional IDs may be added. * @param ids Initial set of IDs to add to the ID set. * @return A new ID set containing the given IDs. */ public static IdSet ids(Collection<Integer> ids) { return new IdSet(ids); } /** * Initialise an ID set with a single range of IDs. Additional IDs may be added. * @param from first ID (inclusive) * @param to last ID (inclusive) * @return A new ID set for the given range of IDs. */ public static IdSet range(int from, int to) { IdSet idSet = new IdSet(); return idSet.addRange(from, to); } /** * Parse the string representation of an ID set. * @param str A string ID set. * @return */ public static IdSet parse(String str) {
if (StringUtils.isEmpty(str)) {
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/exception/BrightpearlServiceException.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/common/ServiceError.java // public final class ServiceError implements Serializable { // // private final String code; // // private final String message; // // public ServiceError(String code, String message) { // this.code = code; // this.message = message; // } // // /** // * Returns the error code identifying the error. // * @return the error code. // */ // public String getCode() { // return code; // } // // /** // * A human readable description of the error, sometimes with additional details of its cause. // * @return a human readable message. // */ // public String getMessage() { // return message; // } // // @Override // public String toString() { // return "ServiceError{" + // "code='" + code + '\'' + // ", message='" + message + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceError that = (ServiceError) o; // if (code != null ? !code.equals(that.code) : that.code != null) return false; // if (message != null ? !message.equals(that.message) : that.message != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = code != null ? code.hashCode() : 0; // result = 31 * result + (message != null ? message.hashCode() : 0); // return result; // } // // }
import uk.co.visalia.brightpearl.apiclient.common.ServiceError; import java.util.Collections; import java.util.List;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.exception; /** * This exception is thrown by the simple get, search and execute APIs in {@link uk.co.visalia.brightpearl.apiclient.BrightpearlApiClient} * when the Brightpearl API returns a collection of error messages in the JSON response body. The status code of the * response and the error messages returned are provided. */ public class BrightpearlServiceException extends BrightpearlClientException { private final int status;
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/common/ServiceError.java // public final class ServiceError implements Serializable { // // private final String code; // // private final String message; // // public ServiceError(String code, String message) { // this.code = code; // this.message = message; // } // // /** // * Returns the error code identifying the error. // * @return the error code. // */ // public String getCode() { // return code; // } // // /** // * A human readable description of the error, sometimes with additional details of its cause. // * @return a human readable message. // */ // public String getMessage() { // return message; // } // // @Override // public String toString() { // return "ServiceError{" + // "code='" + code + '\'' + // ", message='" + message + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceError that = (ServiceError) o; // if (code != null ? !code.equals(that.code) : that.code != null) return false; // if (message != null ? !message.equals(that.message) : that.message != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = code != null ? code.hashCode() : 0; // result = 31 * result + (message != null ? message.hashCode() : 0); // return result; // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/exception/BrightpearlServiceException.java import uk.co.visalia.brightpearl.apiclient.common.ServiceError; import java.util.Collections; import java.util.List; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.exception; /** * This exception is thrown by the simple get, search and execute APIs in {@link uk.co.visalia.brightpearl.apiclient.BrightpearlApiClient} * when the Brightpearl API returns a collection of error messages in the JSON response body. The status code of the * response and the error messages returned are provided. */ public class BrightpearlServiceException extends BrightpearlClientException { private final int status;
private final List<ServiceError> serviceErrors;
davemorrissey/brightpearl-api-client-java
src/test/java/uk/co/visalia/brightpearl/apiclient/request/ServiceWriteRequestBuilderTest.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // }
import org.junit.Test; import uk.co.visalia.brightpearl.apiclient.ServiceName; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; public class ServiceWriteRequestBuilderTest { /** * Ensure that each ruid is only used once. */ @Test public void testUniqueRandomRuids() {
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // Path: src/test/java/uk/co/visalia/brightpearl/apiclient/request/ServiceWriteRequestBuilderTest.java import org.junit.Test; import uk.co.visalia.brightpearl.apiclient.ServiceName; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; public class ServiceWriteRequestBuilderTest { /** * Ensure that each ruid is only used once. */ @Test public void testUniqueRandomRuids() {
ServiceWriteRequestBuilder<Void> builder = ServiceWriteRequestBuilder.newPostRequest(ServiceName.CONTACT, "/contact", null, Void.class);
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/client/multimessage/MultiMessageItem.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // }
import uk.co.visalia.brightpearl.apiclient.http.Method;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.client.multimessage; /** * For internal use only. Represents a single message within a multimessage request. */ public class MultiMessageItem { private String label; private String uri;
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/client/multimessage/MultiMessageItem.java import uk.co.visalia.brightpearl.apiclient.http.Method; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.client.multimessage; /** * For internal use only. Represents a single message within a multimessage request. */ public class MultiMessageItem { private String label; private String uri;
private Method httpMethod;
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/multimessage/MultiRequest.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceWriteRequest.java // public class ServiceWriteRequest<T> extends AbstractServiceRequest<T> { // // private final Object entity; // // ServiceWriteRequest(String ruid, ServiceName service, Method method, String path, Type responseType, Map<String, String> params, Object entity) { // super(ruid, service, method, path, responseType, params); // this.entity = entity; // } // // /** // * The entity to be serialised as JSON and sent as the request body. // * @return the request entity object. // */ // public Object getEntity() { // return entity; // } // // }
import uk.co.visalia.brightpearl.apiclient.request.ServiceWriteRequest; import java.util.Collections; import java.util.List;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.multimessage; /** * Wraps a set of write requests together with a {@link OnFailOption} and a {@link ProcessingMode} to define a multimessage * request for execution with the Brightpearl API. Instances are immutable and may be constructed using {@link MultiRequestBuilder}. * For further information please see the link below. * @see <a href="http://www.brightpearl.com/developer/latest/concept/multi-message.html">http://www.brightpearl.com/developer/latest/concept/multi-message.html</a> */ public final class MultiRequest { private final OnFailOption onFailOption; private final ProcessingMode processingMode;
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceWriteRequest.java // public class ServiceWriteRequest<T> extends AbstractServiceRequest<T> { // // private final Object entity; // // ServiceWriteRequest(String ruid, ServiceName service, Method method, String path, Type responseType, Map<String, String> params, Object entity) { // super(ruid, service, method, path, responseType, params); // this.entity = entity; // } // // /** // * The entity to be serialised as JSON and sent as the request body. // * @return the request entity object. // */ // public Object getEntity() { // return entity; // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/multimessage/MultiRequest.java import uk.co.visalia.brightpearl.apiclient.request.ServiceWriteRequest; import java.util.Collections; import java.util.List; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.multimessage; /** * Wraps a set of write requests together with a {@link OnFailOption} and a {@link ProcessingMode} to define a multimessage * request for execution with the Brightpearl API. Instances are immutable and may be constructed using {@link MultiRequestBuilder}. * For further information please see the link below. * @see <a href="http://www.brightpearl.com/developer/latest/concept/multi-message.html">http://www.brightpearl.com/developer/latest/concept/multi-message.html</a> */ public final class MultiRequest { private final OnFailOption onFailOption; private final ProcessingMode processingMode;
private final List<ServiceWriteRequest> requests;
davemorrissey/brightpearl-api-client-java
src/test/java/uk/co/visalia/brightpearl/apiclient/request/ServiceSearchRequestBuilderTest.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // }
import org.junit.Test; import uk.co.visalia.brightpearl.apiclient.ServiceName; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; public class ServiceSearchRequestBuilderTest { /** * Ensure that each ruid is only used once. */ @Test public void testUniqueRandomRuids() {
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // Path: src/test/java/uk/co/visalia/brightpearl/apiclient/request/ServiceSearchRequestBuilderTest.java import org.junit.Test; import uk.co.visalia.brightpearl.apiclient.ServiceName; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; public class ServiceSearchRequestBuilderTest { /** * Ensure that each ruid is only used once. */ @Test public void testUniqueRandomRuids() {
ServiceSearchRequestBuilder<Void> builder = ServiceSearchRequestBuilder.newSearchRequest(ServiceName.CONTACT, "/contact", Void.class);
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/request/AbstractServiceRequestBuilder.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.lang.reflect.Type; import java.util.Collections; import java.util.HashMap; import java.util.Map;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * Intended for internal use only. This is the superclass for request builders providing common functionality. * @param <B> Builder type. Used to support method chaining from superclass methods. */ abstract class AbstractServiceRequestBuilder<B extends AbstractServiceRequestBuilder<B>> { private String ruid;
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/AbstractServiceRequestBuilder.java import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.lang.reflect.Type; import java.util.Collections; import java.util.HashMap; import java.util.Map; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * Intended for internal use only. This is the superclass for request builders providing common functionality. * @param <B> Builder type. Used to support method chaining from superclass methods. */ abstract class AbstractServiceRequestBuilder<B extends AbstractServiceRequestBuilder<B>> { private String ruid;
private ServiceName service;
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/request/AbstractServiceRequestBuilder.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.lang.reflect.Type; import java.util.Collections; import java.util.HashMap; import java.util.Map;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * Intended for internal use only. This is the superclass for request builders providing common functionality. * @param <B> Builder type. Used to support method chaining from superclass methods. */ abstract class AbstractServiceRequestBuilder<B extends AbstractServiceRequestBuilder<B>> { private String ruid; private ServiceName service;
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/AbstractServiceRequestBuilder.java import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.lang.reflect.Type; import java.util.Collections; import java.util.HashMap; import java.util.Map; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * Intended for internal use only. This is the superclass for request builders providing common functionality. * @param <B> Builder type. Used to support method chaining from superclass methods. */ abstract class AbstractServiceRequestBuilder<B extends AbstractServiceRequestBuilder<B>> { private String ruid; private ServiceName service;
private Method method;
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/request/AbstractServiceRequestBuilder.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.lang.reflect.Type; import java.util.Collections; import java.util.HashMap; import java.util.Map;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * Intended for internal use only. This is the superclass for request builders providing common functionality. * @param <B> Builder type. Used to support method chaining from superclass methods. */ abstract class AbstractServiceRequestBuilder<B extends AbstractServiceRequestBuilder<B>> { private String ruid; private ServiceName service; private Method method; private String path; private Type responseType; private Map<String, String> params; AbstractServiceRequestBuilder() { } abstract B getThis(); void resetRuid() { ruid = null; } B withMethod(Method method) { if (method == null) { throw new IllegalArgumentException("Method cannot be null"); } this.method = method; return getThis(); } /** * Set a unique identifier for the request. All requests are given a unique identifier automatically, for use in * logging and as a label for a request contained in a multimessage, and this method may be used to override it with * a custom ID. * <p> * Note this RUID is applied only to the first request built by this builder; if you call {@link #build()} more than * once, the second and subsequent requests will have randomly generated IDs unless you also call this method * between each invocation. * @param ruid the custom unique identifier to use. * @return builder instance for method chaining. */ public B withRuid(String ruid) {
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/AbstractServiceRequestBuilder.java import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.lang.reflect.Type; import java.util.Collections; import java.util.HashMap; import java.util.Map; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * Intended for internal use only. This is the superclass for request builders providing common functionality. * @param <B> Builder type. Used to support method chaining from superclass methods. */ abstract class AbstractServiceRequestBuilder<B extends AbstractServiceRequestBuilder<B>> { private String ruid; private ServiceName service; private Method method; private String path; private Type responseType; private Map<String, String> params; AbstractServiceRequestBuilder() { } abstract B getThis(); void resetRuid() { ruid = null; } B withMethod(Method method) { if (method == null) { throw new IllegalArgumentException("Method cannot be null"); } this.method = method; return getThis(); } /** * Set a unique identifier for the request. All requests are given a unique identifier automatically, for use in * logging and as a label for a request contained in a multimessage, and this method may be used to override it with * a custom ID. * <p> * Note this RUID is applied only to the first request built by this builder; if you call {@link #build()} more than * once, the second and subsequent requests will have randomly generated IDs unless you also call this method * between each invocation. * @param ruid the custom unique identifier to use. * @return builder instance for method chaining. */ public B withRuid(String ruid) {
if (StringUtils.isBlank(ruid)) {
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/http/httpclient4/HttpClient4ClientFactory.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java // public final class Account implements Serializable { // // private final Datacenter datacenter; // // private final String accountCode; // // /** // * Construct an account instance. // * @param datacenter the datacenter that hosts the account. // * @param accountCode the customer account code. // */ // public Account(Datacenter datacenter, String accountCode) { // if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) { // throw new IllegalArgumentException("A datacenter name and host must be provided"); // } // if (StringUtils.isBlank(accountCode)) { // throw new IllegalArgumentException("An account code must be provided"); // } // this.datacenter = datacenter; // this.accountCode = accountCode; // } // // /** // * Returns the datacenter // * @return the datacenter that hosts the account. // */ // public Datacenter getDatacenter() { // return datacenter; // } // // public String getAccountCode() { // return accountCode; // } // // @Override // public String toString() { // return "Account{" + // "datacenter=" + datacenter + // ", accountCode='" + accountCode + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Account account = (Account) o; // if (accountCode != null ? !accountCode.equals(account.accountCode) : account.accountCode != null) return false; // if (datacenter != null ? !datacenter.equals(account.datacenter) : account.datacenter != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = datacenter != null ? datacenter.hashCode() : 0; // result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); // return result; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Client.java // public interface Client { // // /** // * Executes a request and returns the response. The status code, response body and headers should all be returned if // * any response is received from the server, regardless of status code. If the request fails due to a transport error, // * a {@link uk.co.visalia.brightpearl.apiclient.exception.BrightpearlHttpException} should be thrown. // * @param request The request to be executed. // * @return Response from the server. // */ // Response execute(Request request); // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/ClientFactory.java // public interface ClientFactory { // // /** // * <p> // * Get a client to be used for a given {@link uk.co.visalia.brightpearl.apiclient.account.Account}. This method will be called // * for every request to be made to the Brightpearl API, so that client instances that support only a single request // * are supported. Implementations may return the same instance in response to multiple calls to this method, and // * should do so provided the client is thread-safe and supports multiple concurrent requests. // * </p><p> // * Creating a client for each customer account is not recommended but can be used as a method of throttling the // * resources available to each account, so the account is included as a parameter to allow this. // * </p> // * @param account The Brightpearl customer account a client is required for. // * @return A client instance appropriate for the account. // */ // Client getClient(Account account); // // }
import org.apache.http.client.params.HttpClientParams; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.CoreConnectionPNames; import uk.co.visalia.brightpearl.apiclient.account.Account; import uk.co.visalia.brightpearl.apiclient.http.Client; import uk.co.visalia.brightpearl.apiclient.http.ClientFactory;
private int connectionManagerTimeoutMs = DEFAULT_CONNECTION_MANAGER_TIMEOUT_MS; private int connectionTimeoutMs = DEFAULT_CONNECTION_TIMEOUT_MS; private int socketTimeoutMs = DEFAULT_SOCKET_TIMEOUT_MS; private boolean allowRedirects = DEFAULT_ALLOW_REDIRECTS; private final Object clientLock = new Object(); private HttpClient4Client client; HttpClient4ClientFactory( int maxConnections, int maxConnectionsPerRoute, int connectionManagerTimeoutMs, int connectionTimeoutMs, int socketTimeoutMs, boolean allowRedirects) { this.maxConnections = maxConnections; this.maxConnectionsPerRoute = maxConnectionsPerRoute; this.connectionManagerTimeoutMs = connectionManagerTimeoutMs; this.connectionTimeoutMs = connectionTimeoutMs; this.socketTimeoutMs = socketTimeoutMs; this.allowRedirects = allowRedirects; } /** * Returns the same instance of {@link HttpClient4Client}, backed by a {@link DefaultHttpClient} instance using a * thread-safe pooled connection manager, in response to every request. * @param account The Brightpearl customer account a client is required for. * @return a {@link HttpClient4Client} instance. */ @Override
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java // public final class Account implements Serializable { // // private final Datacenter datacenter; // // private final String accountCode; // // /** // * Construct an account instance. // * @param datacenter the datacenter that hosts the account. // * @param accountCode the customer account code. // */ // public Account(Datacenter datacenter, String accountCode) { // if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) { // throw new IllegalArgumentException("A datacenter name and host must be provided"); // } // if (StringUtils.isBlank(accountCode)) { // throw new IllegalArgumentException("An account code must be provided"); // } // this.datacenter = datacenter; // this.accountCode = accountCode; // } // // /** // * Returns the datacenter // * @return the datacenter that hosts the account. // */ // public Datacenter getDatacenter() { // return datacenter; // } // // public String getAccountCode() { // return accountCode; // } // // @Override // public String toString() { // return "Account{" + // "datacenter=" + datacenter + // ", accountCode='" + accountCode + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Account account = (Account) o; // if (accountCode != null ? !accountCode.equals(account.accountCode) : account.accountCode != null) return false; // if (datacenter != null ? !datacenter.equals(account.datacenter) : account.datacenter != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = datacenter != null ? datacenter.hashCode() : 0; // result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); // return result; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Client.java // public interface Client { // // /** // * Executes a request and returns the response. The status code, response body and headers should all be returned if // * any response is received from the server, regardless of status code. If the request fails due to a transport error, // * a {@link uk.co.visalia.brightpearl.apiclient.exception.BrightpearlHttpException} should be thrown. // * @param request The request to be executed. // * @return Response from the server. // */ // Response execute(Request request); // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/ClientFactory.java // public interface ClientFactory { // // /** // * <p> // * Get a client to be used for a given {@link uk.co.visalia.brightpearl.apiclient.account.Account}. This method will be called // * for every request to be made to the Brightpearl API, so that client instances that support only a single request // * are supported. Implementations may return the same instance in response to multiple calls to this method, and // * should do so provided the client is thread-safe and supports multiple concurrent requests. // * </p><p> // * Creating a client for each customer account is not recommended but can be used as a method of throttling the // * resources available to each account, so the account is included as a parameter to allow this. // * </p> // * @param account The Brightpearl customer account a client is required for. // * @return A client instance appropriate for the account. // */ // Client getClient(Account account); // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/httpclient4/HttpClient4ClientFactory.java import org.apache.http.client.params.HttpClientParams; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.CoreConnectionPNames; import uk.co.visalia.brightpearl.apiclient.account.Account; import uk.co.visalia.brightpearl.apiclient.http.Client; import uk.co.visalia.brightpearl.apiclient.http.ClientFactory; private int connectionManagerTimeoutMs = DEFAULT_CONNECTION_MANAGER_TIMEOUT_MS; private int connectionTimeoutMs = DEFAULT_CONNECTION_TIMEOUT_MS; private int socketTimeoutMs = DEFAULT_SOCKET_TIMEOUT_MS; private boolean allowRedirects = DEFAULT_ALLOW_REDIRECTS; private final Object clientLock = new Object(); private HttpClient4Client client; HttpClient4ClientFactory( int maxConnections, int maxConnectionsPerRoute, int connectionManagerTimeoutMs, int connectionTimeoutMs, int socketTimeoutMs, boolean allowRedirects) { this.maxConnections = maxConnections; this.maxConnectionsPerRoute = maxConnectionsPerRoute; this.connectionManagerTimeoutMs = connectionManagerTimeoutMs; this.connectionTimeoutMs = connectionTimeoutMs; this.socketTimeoutMs = socketTimeoutMs; this.allowRedirects = allowRedirects; } /** * Returns the same instance of {@link HttpClient4Client}, backed by a {@link DefaultHttpClient} instance using a * thread-safe pooled connection manager, in response to every request. * @param account The Brightpearl customer account a client is required for. * @return a {@link HttpClient4Client} instance. */ @Override
public Client getClient(Account account) {
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/http/httpclient4/HttpClient4ClientFactory.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java // public final class Account implements Serializable { // // private final Datacenter datacenter; // // private final String accountCode; // // /** // * Construct an account instance. // * @param datacenter the datacenter that hosts the account. // * @param accountCode the customer account code. // */ // public Account(Datacenter datacenter, String accountCode) { // if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) { // throw new IllegalArgumentException("A datacenter name and host must be provided"); // } // if (StringUtils.isBlank(accountCode)) { // throw new IllegalArgumentException("An account code must be provided"); // } // this.datacenter = datacenter; // this.accountCode = accountCode; // } // // /** // * Returns the datacenter // * @return the datacenter that hosts the account. // */ // public Datacenter getDatacenter() { // return datacenter; // } // // public String getAccountCode() { // return accountCode; // } // // @Override // public String toString() { // return "Account{" + // "datacenter=" + datacenter + // ", accountCode='" + accountCode + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Account account = (Account) o; // if (accountCode != null ? !accountCode.equals(account.accountCode) : account.accountCode != null) return false; // if (datacenter != null ? !datacenter.equals(account.datacenter) : account.datacenter != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = datacenter != null ? datacenter.hashCode() : 0; // result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); // return result; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Client.java // public interface Client { // // /** // * Executes a request and returns the response. The status code, response body and headers should all be returned if // * any response is received from the server, regardless of status code. If the request fails due to a transport error, // * a {@link uk.co.visalia.brightpearl.apiclient.exception.BrightpearlHttpException} should be thrown. // * @param request The request to be executed. // * @return Response from the server. // */ // Response execute(Request request); // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/ClientFactory.java // public interface ClientFactory { // // /** // * <p> // * Get a client to be used for a given {@link uk.co.visalia.brightpearl.apiclient.account.Account}. This method will be called // * for every request to be made to the Brightpearl API, so that client instances that support only a single request // * are supported. Implementations may return the same instance in response to multiple calls to this method, and // * should do so provided the client is thread-safe and supports multiple concurrent requests. // * </p><p> // * Creating a client for each customer account is not recommended but can be used as a method of throttling the // * resources available to each account, so the account is included as a parameter to allow this. // * </p> // * @param account The Brightpearl customer account a client is required for. // * @return A client instance appropriate for the account. // */ // Client getClient(Account account); // // }
import org.apache.http.client.params.HttpClientParams; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.CoreConnectionPNames; import uk.co.visalia.brightpearl.apiclient.account.Account; import uk.co.visalia.brightpearl.apiclient.http.Client; import uk.co.visalia.brightpearl.apiclient.http.ClientFactory;
private int connectionManagerTimeoutMs = DEFAULT_CONNECTION_MANAGER_TIMEOUT_MS; private int connectionTimeoutMs = DEFAULT_CONNECTION_TIMEOUT_MS; private int socketTimeoutMs = DEFAULT_SOCKET_TIMEOUT_MS; private boolean allowRedirects = DEFAULT_ALLOW_REDIRECTS; private final Object clientLock = new Object(); private HttpClient4Client client; HttpClient4ClientFactory( int maxConnections, int maxConnectionsPerRoute, int connectionManagerTimeoutMs, int connectionTimeoutMs, int socketTimeoutMs, boolean allowRedirects) { this.maxConnections = maxConnections; this.maxConnectionsPerRoute = maxConnectionsPerRoute; this.connectionManagerTimeoutMs = connectionManagerTimeoutMs; this.connectionTimeoutMs = connectionTimeoutMs; this.socketTimeoutMs = socketTimeoutMs; this.allowRedirects = allowRedirects; } /** * Returns the same instance of {@link HttpClient4Client}, backed by a {@link DefaultHttpClient} instance using a * thread-safe pooled connection manager, in response to every request. * @param account The Brightpearl customer account a client is required for. * @return a {@link HttpClient4Client} instance. */ @Override
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java // public final class Account implements Serializable { // // private final Datacenter datacenter; // // private final String accountCode; // // /** // * Construct an account instance. // * @param datacenter the datacenter that hosts the account. // * @param accountCode the customer account code. // */ // public Account(Datacenter datacenter, String accountCode) { // if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) { // throw new IllegalArgumentException("A datacenter name and host must be provided"); // } // if (StringUtils.isBlank(accountCode)) { // throw new IllegalArgumentException("An account code must be provided"); // } // this.datacenter = datacenter; // this.accountCode = accountCode; // } // // /** // * Returns the datacenter // * @return the datacenter that hosts the account. // */ // public Datacenter getDatacenter() { // return datacenter; // } // // public String getAccountCode() { // return accountCode; // } // // @Override // public String toString() { // return "Account{" + // "datacenter=" + datacenter + // ", accountCode='" + accountCode + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Account account = (Account) o; // if (accountCode != null ? !accountCode.equals(account.accountCode) : account.accountCode != null) return false; // if (datacenter != null ? !datacenter.equals(account.datacenter) : account.datacenter != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = datacenter != null ? datacenter.hashCode() : 0; // result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); // return result; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Client.java // public interface Client { // // /** // * Executes a request and returns the response. The status code, response body and headers should all be returned if // * any response is received from the server, regardless of status code. If the request fails due to a transport error, // * a {@link uk.co.visalia.brightpearl.apiclient.exception.BrightpearlHttpException} should be thrown. // * @param request The request to be executed. // * @return Response from the server. // */ // Response execute(Request request); // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/ClientFactory.java // public interface ClientFactory { // // /** // * <p> // * Get a client to be used for a given {@link uk.co.visalia.brightpearl.apiclient.account.Account}. This method will be called // * for every request to be made to the Brightpearl API, so that client instances that support only a single request // * are supported. Implementations may return the same instance in response to multiple calls to this method, and // * should do so provided the client is thread-safe and supports multiple concurrent requests. // * </p><p> // * Creating a client for each customer account is not recommended but can be used as a method of throttling the // * resources available to each account, so the account is included as a parameter to allow this. // * </p> // * @param account The Brightpearl customer account a client is required for. // * @return A client instance appropriate for the account. // */ // Client getClient(Account account); // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/httpclient4/HttpClient4ClientFactory.java import org.apache.http.client.params.HttpClientParams; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.CoreConnectionPNames; import uk.co.visalia.brightpearl.apiclient.account.Account; import uk.co.visalia.brightpearl.apiclient.http.Client; import uk.co.visalia.brightpearl.apiclient.http.ClientFactory; private int connectionManagerTimeoutMs = DEFAULT_CONNECTION_MANAGER_TIMEOUT_MS; private int connectionTimeoutMs = DEFAULT_CONNECTION_TIMEOUT_MS; private int socketTimeoutMs = DEFAULT_SOCKET_TIMEOUT_MS; private boolean allowRedirects = DEFAULT_ALLOW_REDIRECTS; private final Object clientLock = new Object(); private HttpClient4Client client; HttpClient4ClientFactory( int maxConnections, int maxConnectionsPerRoute, int connectionManagerTimeoutMs, int connectionTimeoutMs, int socketTimeoutMs, boolean allowRedirects) { this.maxConnections = maxConnections; this.maxConnectionsPerRoute = maxConnectionsPerRoute; this.connectionManagerTimeoutMs = connectionManagerTimeoutMs; this.connectionTimeoutMs = connectionTimeoutMs; this.socketTimeoutMs = socketTimeoutMs; this.allowRedirects = allowRedirects; } /** * Returns the same instance of {@link HttpClient4Client}, backed by a {@link DefaultHttpClient} instance using a * thread-safe pooled connection manager, in response to every request. * @param account The Brightpearl customer account a client is required for. * @return a {@link HttpClient4Client} instance. */ @Override
public Client getClient(Account account) {
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/http/RequestBuilder.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.util.Collections; import java.util.Map;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.http; /** * A builder used to create immutable {@link Request} instances. */ public class RequestBuilder { private Method method; private String url; private String body; private Map<String, String> parameters; private Map<String, String> headers; private RequestBuilder() { } /** * Creates a new builder instance. At minimum, a method and URL must be set. * @return a new builder instance. */ public static RequestBuilder newRequest() { return new RequestBuilder(); } /** * Constructs the immutable {@link Request} instance. * @return a request instance for execution. */ public Request build() { if (method == null) { throw new IllegalArgumentException("Request method cannot be null"); }
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/RequestBuilder.java import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.util.Collections; import java.util.Map; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.http; /** * A builder used to create immutable {@link Request} instances. */ public class RequestBuilder { private Method method; private String url; private String body; private Map<String, String> parameters; private Map<String, String> headers; private RequestBuilder() { } /** * Creates a new builder instance. At minimum, a method and URL must be set. * @return a new builder instance. */ public static RequestBuilder newRequest() { return new RequestBuilder(); } /** * Constructs the immutable {@link Request} instance. * @return a request instance for execution. */ public Request build() { if (method == null) { throw new IllegalArgumentException("Request method cannot be null"); }
if (StringUtils.isBlank(url)) {
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/search/SearchSort.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/SortDirection.java // public enum SortDirection { // // /** Sort ascending. */ // ASC, // // /** Sort descending. */ // DESC // // }
import uk.co.visalia.brightpearl.apiclient.request.SortDirection; import java.io.Serializable;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.search; /** * Describes sorting that was applied to a search result. * @see <a href="http://brightpearl.com/developer/latest/tutorial/working-with-resource-search.html">http://brightpearl.com/developer/latest/tutorial/working-with-resource-search.html</a> */ public class SearchSort implements Serializable { private SearchColumn filterable;
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/SortDirection.java // public enum SortDirection { // // /** Sort ascending. */ // ASC, // // /** Sort descending. */ // DESC // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/search/SearchSort.java import uk.co.visalia.brightpearl.apiclient.request.SortDirection; import java.io.Serializable; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.search; /** * Describes sorting that was applied to a search result. * @see <a href="http://brightpearl.com/developer/latest/tutorial/working-with-resource-search.html">http://brightpearl.com/developer/latest/tutorial/working-with-resource-search.html</a> */ public class SearchSort implements Serializable { private SearchColumn filterable;
private SortDirection direction;
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceReadRequestBuilder.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.lang.reflect.Type; import java.util.UUID;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * A factory for immutable {@link ServiceReadRequest} instances. Static methods provide GET and OPTIONS requests configured * with the minimum fields needed to execute a request, and chaining methods are available to set additional attributes * on the request before an immutable instance is build with {@link #build()}. * @param <T> placeholder for the response type, used to avoid casting of responses. This is not * linked to the {@link Type} set on a request so a {@link ClassCastException} is possible if the type is set * incorrectly. */ public class ServiceReadRequestBuilder<T> extends AbstractServiceRequestBuilder<ServiceReadRequestBuilder<T>> { ServiceReadRequestBuilder() { super(); } @Override protected ServiceReadRequestBuilder<T> getThis() { return this; } /** * Creates a new GET request builder configured with the URL to call and expected response type. This method does * not support extraction of generic types but is able to infer the type parameter &lt;T&gt;. * @param service Brightpearl service that contains the resource. * @param path path to the search resource, for example '/product'. * @param responseType type of result expected in the 'response' element of the JSON response body. Use Void or null if no response is expected, or the response is not required. * @param <T> placeholder for the response type, used to avoid casting of responses. * @return an OPTIONS request builder instance. */
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceReadRequestBuilder.java import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.lang.reflect.Type; import java.util.UUID; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * A factory for immutable {@link ServiceReadRequest} instances. Static methods provide GET and OPTIONS requests configured * with the minimum fields needed to execute a request, and chaining methods are available to set additional attributes * on the request before an immutable instance is build with {@link #build()}. * @param <T> placeholder for the response type, used to avoid casting of responses. This is not * linked to the {@link Type} set on a request so a {@link ClassCastException} is possible if the type is set * incorrectly. */ public class ServiceReadRequestBuilder<T> extends AbstractServiceRequestBuilder<ServiceReadRequestBuilder<T>> { ServiceReadRequestBuilder() { super(); } @Override protected ServiceReadRequestBuilder<T> getThis() { return this; } /** * Creates a new GET request builder configured with the URL to call and expected response type. This method does * not support extraction of generic types but is able to infer the type parameter &lt;T&gt;. * @param service Brightpearl service that contains the resource. * @param path path to the search resource, for example '/product'. * @param responseType type of result expected in the 'response' element of the JSON response body. Use Void or null if no response is expected, or the response is not required. * @param <T> placeholder for the response type, used to avoid casting of responses. * @return an OPTIONS request builder instance. */
public static <T> ServiceReadRequestBuilder<T> newGetRequest(ServiceName service, String path, Class<T> responseType) {
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceReadRequestBuilder.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.lang.reflect.Type; import java.util.UUID;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * A factory for immutable {@link ServiceReadRequest} instances. Static methods provide GET and OPTIONS requests configured * with the minimum fields needed to execute a request, and chaining methods are available to set additional attributes * on the request before an immutable instance is build with {@link #build()}. * @param <T> placeholder for the response type, used to avoid casting of responses. This is not * linked to the {@link Type} set on a request so a {@link ClassCastException} is possible if the type is set * incorrectly. */ public class ServiceReadRequestBuilder<T> extends AbstractServiceRequestBuilder<ServiceReadRequestBuilder<T>> { ServiceReadRequestBuilder() { super(); } @Override protected ServiceReadRequestBuilder<T> getThis() { return this; } /** * Creates a new GET request builder configured with the URL to call and expected response type. This method does * not support extraction of generic types but is able to infer the type parameter &lt;T&gt;. * @param service Brightpearl service that contains the resource. * @param path path to the search resource, for example '/product'. * @param responseType type of result expected in the 'response' element of the JSON response body. Use Void or null if no response is expected, or the response is not required. * @param <T> placeholder for the response type, used to avoid casting of responses. * @return an OPTIONS request builder instance. */ public static <T> ServiceReadRequestBuilder<T> newGetRequest(ServiceName service, String path, Class<T> responseType) { ServiceReadRequestBuilder<T> builder = new ServiceReadRequestBuilder<T>();
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceReadRequestBuilder.java import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.lang.reflect.Type; import java.util.UUID; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * A factory for immutable {@link ServiceReadRequest} instances. Static methods provide GET and OPTIONS requests configured * with the minimum fields needed to execute a request, and chaining methods are available to set additional attributes * on the request before an immutable instance is build with {@link #build()}. * @param <T> placeholder for the response type, used to avoid casting of responses. This is not * linked to the {@link Type} set on a request so a {@link ClassCastException} is possible if the type is set * incorrectly. */ public class ServiceReadRequestBuilder<T> extends AbstractServiceRequestBuilder<ServiceReadRequestBuilder<T>> { ServiceReadRequestBuilder() { super(); } @Override protected ServiceReadRequestBuilder<T> getThis() { return this; } /** * Creates a new GET request builder configured with the URL to call and expected response type. This method does * not support extraction of generic types but is able to infer the type parameter &lt;T&gt;. * @param service Brightpearl service that contains the resource. * @param path path to the search resource, for example '/product'. * @param responseType type of result expected in the 'response' element of the JSON response body. Use Void or null if no response is expected, or the response is not required. * @param <T> placeholder for the response type, used to avoid casting of responses. * @return an OPTIONS request builder instance. */ public static <T> ServiceReadRequestBuilder<T> newGetRequest(ServiceName service, String path, Class<T> responseType) { ServiceReadRequestBuilder<T> builder = new ServiceReadRequestBuilder<T>();
return builder.withMethod(Method.GET)
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceReadRequestBuilder.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.lang.reflect.Type; import java.util.UUID;
public static <T> ServiceReadRequestBuilder<T> newOptionsRequest(ServiceName service, String path, Class<T> responseType) { ServiceReadRequestBuilder<T> builder = new ServiceReadRequestBuilder<T>(); return builder.withMethod(Method.GET) .withService(service) .withPath(path) .withResponseType(responseType); } /** * Creates a new OPTIONS request builder configured with the URL to call and expected response type. This method supports * extraction of generic types (e.g. typed lists or maps) from the response element. * @param service Brightpearl service that contains the resource. * @param path path to the search resource, for example '/product'. * @param responseType type of result expected in the 'response' element of the JSON response body. Use Void or null if no response is expected, or the response is not required. * @param <T> placeholder for the response type, used to avoid casting of responses. * @return A OPTIONS request builder instance. */ public static <T> ServiceReadRequestBuilder<T> newOptionsRequest(ServiceName service, String path, Type responseType) { ServiceReadRequestBuilder<T> builder = new ServiceReadRequestBuilder<T>(); return builder.withMethod(Method.OPTIONS) .withService(service) .withPath(path) .withResponseType(responseType); } /** * Builds an immutable request instance from values provided to this builder. * @return immutable request instance. */ public ServiceReadRequest<T> build() {
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceReadRequestBuilder.java import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.lang.reflect.Type; import java.util.UUID; public static <T> ServiceReadRequestBuilder<T> newOptionsRequest(ServiceName service, String path, Class<T> responseType) { ServiceReadRequestBuilder<T> builder = new ServiceReadRequestBuilder<T>(); return builder.withMethod(Method.GET) .withService(service) .withPath(path) .withResponseType(responseType); } /** * Creates a new OPTIONS request builder configured with the URL to call and expected response type. This method supports * extraction of generic types (e.g. typed lists or maps) from the response element. * @param service Brightpearl service that contains the resource. * @param path path to the search resource, for example '/product'. * @param responseType type of result expected in the 'response' element of the JSON response body. Use Void or null if no response is expected, or the response is not required. * @param <T> placeholder for the response type, used to avoid casting of responses. * @return A OPTIONS request builder instance. */ public static <T> ServiceReadRequestBuilder<T> newOptionsRequest(ServiceName service, String path, Type responseType) { ServiceReadRequestBuilder<T> builder = new ServiceReadRequestBuilder<T>(); return builder.withMethod(Method.OPTIONS) .withService(service) .withPath(path) .withResponseType(responseType); } /** * Builds an immutable request instance from values provided to this builder. * @return immutable request instance. */ public ServiceReadRequest<T> build() {
String ruid = StringUtils.isNotEmpty(getRuid()) ? getRuid() : UUID.randomUUID().toString();
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceWriteRequest.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // }
import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import java.lang.reflect.Type; import java.util.Map;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * <p> * Represents a write request to be made to the Brightpearl API. Extends {@link AbstractServiceRequest}, adding the attributes * unique to a write request. This is currently only the entity to be serialised as JSON and sent as the request body. * </p><p> * Request instances are intended to be immutable to avoid modification while a request is being constructed, however * the enclosed entity cannot be protected from external modification. Avoid modifying entities after including them in * a request. * </p> * @param <T> A placeholder for the type expected in the response, avoiding the requirement to cast responses. This is not * linked to the {@link Type} set on a request so a {@link ClassCastException} is possible if the type is set * incorrectly. */ public class ServiceWriteRequest<T> extends AbstractServiceRequest<T> { private final Object entity;
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceWriteRequest.java import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import java.lang.reflect.Type; import java.util.Map; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * <p> * Represents a write request to be made to the Brightpearl API. Extends {@link AbstractServiceRequest}, adding the attributes * unique to a write request. This is currently only the entity to be serialised as JSON and sent as the request body. * </p><p> * Request instances are intended to be immutable to avoid modification while a request is being constructed, however * the enclosed entity cannot be protected from external modification. Avoid modifying entities after including them in * a request. * </p> * @param <T> A placeholder for the type expected in the response, avoiding the requirement to cast responses. This is not * linked to the {@link Type} set on a request so a {@link ClassCastException} is possible if the type is set * incorrectly. */ public class ServiceWriteRequest<T> extends AbstractServiceRequest<T> { private final Object entity;
ServiceWriteRequest(String ruid, ServiceName service, Method method, String path, Type responseType, Map<String, String> params, Object entity) {
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceWriteRequest.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // }
import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import java.lang.reflect.Type; import java.util.Map;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * <p> * Represents a write request to be made to the Brightpearl API. Extends {@link AbstractServiceRequest}, adding the attributes * unique to a write request. This is currently only the entity to be serialised as JSON and sent as the request body. * </p><p> * Request instances are intended to be immutable to avoid modification while a request is being constructed, however * the enclosed entity cannot be protected from external modification. Avoid modifying entities after including them in * a request. * </p> * @param <T> A placeholder for the type expected in the response, avoiding the requirement to cast responses. This is not * linked to the {@link Type} set on a request so a {@link ClassCastException} is possible if the type is set * incorrectly. */ public class ServiceWriteRequest<T> extends AbstractServiceRequest<T> { private final Object entity;
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceWriteRequest.java import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import java.lang.reflect.Type; import java.util.Map; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * <p> * Represents a write request to be made to the Brightpearl API. Extends {@link AbstractServiceRequest}, adding the attributes * unique to a write request. This is currently only the entity to be serialised as JSON and sent as the request body. * </p><p> * Request instances are intended to be immutable to avoid modification while a request is being constructed, however * the enclosed entity cannot be protected from external modification. Avoid modifying entities after including them in * a request. * </p> * @param <T> A placeholder for the type expected in the response, avoiding the requirement to cast responses. This is not * linked to the {@link Type} set on a request so a {@link ClassCastException} is possible if the type is set * incorrectly. */ public class ServiceWriteRequest<T> extends AbstractServiceRequest<T> { private final Object entity;
ServiceWriteRequest(String ruid, ServiceName service, Method method, String path, Type responseType, Map<String, String> params, Object entity) {
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/BrightpearlApiClientFactory.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/ClientFactory.java // public interface ClientFactory { // // /** // * <p> // * Get a client to be used for a given {@link uk.co.visalia.brightpearl.apiclient.account.Account}. This method will be called // * for every request to be made to the Brightpearl API, so that client instances that support only a single request // * are supported. Implementations may return the same instance in response to multiple calls to this method, and // * should do so provided the client is thread-safe and supports multiple concurrent requests. // * </p><p> // * Creating a client for each customer account is not recommended but can be used as a method of throttling the // * resources available to each account, so the account is included as a parameter to allow this. // * </p> // * @param account The Brightpearl customer account a client is required for. // * @return A client instance appropriate for the account. // */ // Client getClient(Account account); // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ratelimit/RateLimiter.java // public interface RateLimiter { // // /** // * Called immediately before a request is made to the Brightpearl API for the given account. Implementations may // * sleep before returning to reduce throughput, or throw an exception to abort the request. // * @param account The account a request will be sent to. // */ // void rateLimit(Account account); // // /** // * Called after every request is made to the Brightpearl API, with values from the brightpearl-requests-remaining // * and brightpearl-next-throttle-period headers. These may be used to adjust the behaviour of the {@link #rateLimit(Account)} // * method, but as other requests may have been made on other threads while this request was executing, the values // * may be stale, and events may be received out of sequence. // * @param account The account a response has been received from. // * @param requestsRemaining The value of the brightpearl-requests-remaining response header. // * @param nextThrottlePeriod The value of the brightpearl-next-throttle-period header. // */ // void requestCompleted(Account account, int requestsRemaining, long nextThrottlePeriod); // // /** // * Called when a request to an account has been rejected due to request throttling. This event may be used to adjust // * the behaviour of the the {@link #rateLimit(Account)} method. Other concurrent requests that were already started // * at the time this event is received are likely to also fail. // * @param account An account for which a request cap error has been received. // */ // void requestCapExceeded(Account account); // // }
import com.google.gson.Gson; import uk.co.visalia.brightpearl.apiclient.http.ClientFactory; import uk.co.visalia.brightpearl.apiclient.ratelimit.RateLimiter; import java.util.Calendar;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient; /** * <p> * Constructs a configured {@link BrightpearlApiClient}. Supports construction in code using the builder pattern (starting * with {@link #brightpearlApiClient()}) and usage as a Spring bean factory. For example: * </p> * <pre> * &lt;bean id="brightpearlApiClientFactory" class="BrightpearlApiClientFactory"&gt; * &lt;property name="clientFactory" ref="myClientFactory"/&gt; * &lt;/bean&gt; * * &lt;bean id="brightpearlApiClient" * factory-bean="brightpearlApiClientFactory" * factory-method="build"/&gt; * </pre> * <p> * Defaults are available for all the configuration options so there is no requirement to set any options before building * the client instance. * </p> */ public final class BrightpearlApiClientFactory { private ClientFactory clientFactory;
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/ClientFactory.java // public interface ClientFactory { // // /** // * <p> // * Get a client to be used for a given {@link uk.co.visalia.brightpearl.apiclient.account.Account}. This method will be called // * for every request to be made to the Brightpearl API, so that client instances that support only a single request // * are supported. Implementations may return the same instance in response to multiple calls to this method, and // * should do so provided the client is thread-safe and supports multiple concurrent requests. // * </p><p> // * Creating a client for each customer account is not recommended but can be used as a method of throttling the // * resources available to each account, so the account is included as a parameter to allow this. // * </p> // * @param account The Brightpearl customer account a client is required for. // * @return A client instance appropriate for the account. // */ // Client getClient(Account account); // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ratelimit/RateLimiter.java // public interface RateLimiter { // // /** // * Called immediately before a request is made to the Brightpearl API for the given account. Implementations may // * sleep before returning to reduce throughput, or throw an exception to abort the request. // * @param account The account a request will be sent to. // */ // void rateLimit(Account account); // // /** // * Called after every request is made to the Brightpearl API, with values from the brightpearl-requests-remaining // * and brightpearl-next-throttle-period headers. These may be used to adjust the behaviour of the {@link #rateLimit(Account)} // * method, but as other requests may have been made on other threads while this request was executing, the values // * may be stale, and events may be received out of sequence. // * @param account The account a response has been received from. // * @param requestsRemaining The value of the brightpearl-requests-remaining response header. // * @param nextThrottlePeriod The value of the brightpearl-next-throttle-period header. // */ // void requestCompleted(Account account, int requestsRemaining, long nextThrottlePeriod); // // /** // * Called when a request to an account has been rejected due to request throttling. This event may be used to adjust // * the behaviour of the the {@link #rateLimit(Account)} method. Other concurrent requests that were already started // * at the time this event is received are likely to also fail. // * @param account An account for which a request cap error has been received. // */ // void requestCapExceeded(Account account); // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/BrightpearlApiClientFactory.java import com.google.gson.Gson; import uk.co.visalia.brightpearl.apiclient.http.ClientFactory; import uk.co.visalia.brightpearl.apiclient.ratelimit.RateLimiter; import java.util.Calendar; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient; /** * <p> * Constructs a configured {@link BrightpearlApiClient}. Supports construction in code using the builder pattern (starting * with {@link #brightpearlApiClient()}) and usage as a Spring bean factory. For example: * </p> * <pre> * &lt;bean id="brightpearlApiClientFactory" class="BrightpearlApiClientFactory"&gt; * &lt;property name="clientFactory" ref="myClientFactory"/&gt; * &lt;/bean&gt; * * &lt;bean id="brightpearlApiClient" * factory-bean="brightpearlApiClientFactory" * factory-method="build"/&gt; * </pre> * <p> * Defaults are available for all the configuration options so there is no requirement to set any options before building * the client instance. * </p> */ public final class BrightpearlApiClientFactory { private ClientFactory clientFactory;
private RateLimiter rateLimiter;
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/ratelimit/NoOpRateLimiter.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java // public final class Account implements Serializable { // // private final Datacenter datacenter; // // private final String accountCode; // // /** // * Construct an account instance. // * @param datacenter the datacenter that hosts the account. // * @param accountCode the customer account code. // */ // public Account(Datacenter datacenter, String accountCode) { // if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) { // throw new IllegalArgumentException("A datacenter name and host must be provided"); // } // if (StringUtils.isBlank(accountCode)) { // throw new IllegalArgumentException("An account code must be provided"); // } // this.datacenter = datacenter; // this.accountCode = accountCode; // } // // /** // * Returns the datacenter // * @return the datacenter that hosts the account. // */ // public Datacenter getDatacenter() { // return datacenter; // } // // public String getAccountCode() { // return accountCode; // } // // @Override // public String toString() { // return "Account{" + // "datacenter=" + datacenter + // ", accountCode='" + accountCode + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Account account = (Account) o; // if (accountCode != null ? !accountCode.equals(account.accountCode) : account.accountCode != null) return false; // if (datacenter != null ? !datacenter.equals(account.datacenter) : account.datacenter != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = datacenter != null ? datacenter.hashCode() : 0; // result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); // return result; // } // }
import uk.co.visalia.brightpearl.apiclient.account.Account;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.ratelimit; /** * An implementation of {@link RateLimiter} that allows requests to be sent to Brightpearl as fast as they are made by * the client. Suitable for use anywhere the request cap is unlikely to be reached, when another strategy is in place * for limiting the rate of requests, or when the client is set up to recover from rate limit errors automatically. */ public class NoOpRateLimiter implements RateLimiter { /** * This implementation does nothing. */ @Override
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java // public final class Account implements Serializable { // // private final Datacenter datacenter; // // private final String accountCode; // // /** // * Construct an account instance. // * @param datacenter the datacenter that hosts the account. // * @param accountCode the customer account code. // */ // public Account(Datacenter datacenter, String accountCode) { // if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) { // throw new IllegalArgumentException("A datacenter name and host must be provided"); // } // if (StringUtils.isBlank(accountCode)) { // throw new IllegalArgumentException("An account code must be provided"); // } // this.datacenter = datacenter; // this.accountCode = accountCode; // } // // /** // * Returns the datacenter // * @return the datacenter that hosts the account. // */ // public Datacenter getDatacenter() { // return datacenter; // } // // public String getAccountCode() { // return accountCode; // } // // @Override // public String toString() { // return "Account{" + // "datacenter=" + datacenter + // ", accountCode='" + accountCode + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Account account = (Account) o; // if (accountCode != null ? !accountCode.equals(account.accountCode) : account.accountCode != null) return false; // if (datacenter != null ? !datacenter.equals(account.datacenter) : account.datacenter != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = datacenter != null ? datacenter.hashCode() : 0; // result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); // return result; // } // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ratelimit/NoOpRateLimiter.java import uk.co.visalia.brightpearl.apiclient.account.Account; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.ratelimit; /** * An implementation of {@link RateLimiter} that allows requests to be sent to Brightpearl as fast as they are made by * the client. Suitable for use anywhere the request cap is unlikely to be reached, when another strategy is in place * for limiting the rate of requests, or when the client is set up to recover from rate limit errors automatically. */ public class NoOpRateLimiter implements RateLimiter { /** * This implementation does nothing. */ @Override
public void rateLimit(Account account) {
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/auth/LegacyAuthorisation.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java // public final class Account implements Serializable { // // private final Datacenter datacenter; // // private final String accountCode; // // /** // * Construct an account instance. // * @param datacenter the datacenter that hosts the account. // * @param accountCode the customer account code. // */ // public Account(Datacenter datacenter, String accountCode) { // if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) { // throw new IllegalArgumentException("A datacenter name and host must be provided"); // } // if (StringUtils.isBlank(accountCode)) { // throw new IllegalArgumentException("An account code must be provided"); // } // this.datacenter = datacenter; // this.accountCode = accountCode; // } // // /** // * Returns the datacenter // * @return the datacenter that hosts the account. // */ // public Datacenter getDatacenter() { // return datacenter; // } // // public String getAccountCode() { // return accountCode; // } // // @Override // public String toString() { // return "Account{" + // "datacenter=" + datacenter + // ", accountCode='" + accountCode + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Account account = (Account) o; // if (accountCode != null ? !accountCode.equals(account.accountCode) : account.accountCode != null) return false; // if (datacenter != null ? !datacenter.equals(account.datacenter) : account.datacenter != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = datacenter != null ? datacenter.hashCode() : 0; // result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); // return result; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.account.Account; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.util.Collections; import java.util.HashMap; import java.util.Map;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.auth; /** * Contains a legacy authentication token related to a staff member and not any developer or app. */ public class LegacyAuthorisation implements AppAuthorisation { private final Account account; private final String authToken; private LegacyAuthorisation(Account account, String authToken) { this.account = account; this.authToken = authToken; } /** * Create legacy authentication details using an account and staff token. * @param account Brightpearl customer account details. * @param authToken Staff authentication token. */ public static LegacyAuthorisation staff(Account account, String authToken) { if (account == null) { throw new IllegalArgumentException("Account is required"); }
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java // public final class Account implements Serializable { // // private final Datacenter datacenter; // // private final String accountCode; // // /** // * Construct an account instance. // * @param datacenter the datacenter that hosts the account. // * @param accountCode the customer account code. // */ // public Account(Datacenter datacenter, String accountCode) { // if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) { // throw new IllegalArgumentException("A datacenter name and host must be provided"); // } // if (StringUtils.isBlank(accountCode)) { // throw new IllegalArgumentException("An account code must be provided"); // } // this.datacenter = datacenter; // this.accountCode = accountCode; // } // // /** // * Returns the datacenter // * @return the datacenter that hosts the account. // */ // public Datacenter getDatacenter() { // return datacenter; // } // // public String getAccountCode() { // return accountCode; // } // // @Override // public String toString() { // return "Account{" + // "datacenter=" + datacenter + // ", accountCode='" + accountCode + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Account account = (Account) o; // if (accountCode != null ? !accountCode.equals(account.accountCode) : account.accountCode != null) return false; // if (datacenter != null ? !datacenter.equals(account.datacenter) : account.datacenter != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = datacenter != null ? datacenter.hashCode() : 0; // result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); // return result; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/auth/LegacyAuthorisation.java import uk.co.visalia.brightpearl.apiclient.account.Account; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.util.Collections; import java.util.HashMap; import java.util.Map; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.auth; /** * Contains a legacy authentication token related to a staff member and not any developer or app. */ public class LegacyAuthorisation implements AppAuthorisation { private final Account account; private final String authToken; private LegacyAuthorisation(Account account, String authToken) { this.account = account; this.authToken = authToken; } /** * Create legacy authentication details using an account and staff token. * @param account Brightpearl customer account details. * @param authToken Staff authentication token. */ public static LegacyAuthorisation staff(Account account, String authToken) { if (account == null) { throw new IllegalArgumentException("Account is required"); }
if (StringUtils.isBlank(authToken)) { throw new IllegalArgumentException("Auth token is required"); }
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/request/AbstractServiceRequest.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // }
import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import java.lang.reflect.Type; import java.util.Collections; import java.util.Map;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * <p> * This is the superclass for read and write request classes, providing the functionality common to both. It is only * intended for use internally so has a package private constructor. * </p><p> * Requests are split into read requests (including searches) and write requests because write requests can be included * in multimessages and read requests cannot, and because read requests can be cached and write requests cannot. * </p> * @param <T> A placeholder for the type expected in the response, avoiding the requirement to cast responses. This is not * linked to the {@link Type} set on a request so a {@link ClassCastException} is possible if the type is set * incorrectly. */ public abstract class AbstractServiceRequest<T> { private final String ruid;
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/AbstractServiceRequest.java import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import java.lang.reflect.Type; import java.util.Collections; import java.util.Map; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * <p> * This is the superclass for read and write request classes, providing the functionality common to both. It is only * intended for use internally so has a package private constructor. * </p><p> * Requests are split into read requests (including searches) and write requests because write requests can be included * in multimessages and read requests cannot, and because read requests can be cached and write requests cannot. * </p> * @param <T> A placeholder for the type expected in the response, avoiding the requirement to cast responses. This is not * linked to the {@link Type} set on a request so a {@link ClassCastException} is possible if the type is set * incorrectly. */ public abstract class AbstractServiceRequest<T> { private final String ruid;
private final ServiceName service;
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/request/AbstractServiceRequest.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // }
import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import java.lang.reflect.Type; import java.util.Collections; import java.util.Map;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * <p> * This is the superclass for read and write request classes, providing the functionality common to both. It is only * intended for use internally so has a package private constructor. * </p><p> * Requests are split into read requests (including searches) and write requests because write requests can be included * in multimessages and read requests cannot, and because read requests can be cached and write requests cannot. * </p> * @param <T> A placeholder for the type expected in the response, avoiding the requirement to cast responses. This is not * linked to the {@link Type} set on a request so a {@link ClassCastException} is possible if the type is set * incorrectly. */ public abstract class AbstractServiceRequest<T> { private final String ruid; private final ServiceName service;
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/AbstractServiceRequest.java import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import java.lang.reflect.Type; import java.util.Collections; import java.util.Map; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * <p> * This is the superclass for read and write request classes, providing the functionality common to both. It is only * intended for use internally so has a package private constructor. * </p><p> * Requests are split into read requests (including searches) and write requests because write requests can be included * in multimessages and read requests cannot, and because read requests can be cached and write requests cannot. * </p> * @param <T> A placeholder for the type expected in the response, avoiding the requirement to cast responses. This is not * linked to the {@link Type} set on a request so a {@link ClassCastException} is possible if the type is set * incorrectly. */ public abstract class AbstractServiceRequest<T> { private final String ruid; private final ServiceName service;
private final Method method;
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/client/parsing/JsonWrapper.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/common/ServiceError.java // public final class ServiceError implements Serializable { // // private final String code; // // private final String message; // // public ServiceError(String code, String message) { // this.code = code; // this.message = message; // } // // /** // * Returns the error code identifying the error. // * @return the error code. // */ // public String getCode() { // return code; // } // // /** // * A human readable description of the error, sometimes with additional details of its cause. // * @return a human readable message. // */ // public String getMessage() { // return message; // } // // @Override // public String toString() { // return "ServiceError{" + // "code='" + code + '\'' + // ", message='" + message + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceError that = (ServiceError) o; // if (code != null ? !code.equals(that.code) : that.code != null) return false; // if (message != null ? !message.equals(that.message) : that.message != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = code != null ? code.hashCode() : 0; // result = 31 * result + (message != null ? message.hashCode() : 0); // return result; // } // // }
import com.google.gson.JsonElement; import uk.co.visalia.brightpearl.apiclient.common.ServiceError; import java.util.List; import java.util.Map;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.client.parsing; /** * For internal use only. Raw type used in the parsing of all BP API responses including searches and multimessage responses. * This represents the entirety of the JSON response and stores the response element as unparsed JSON so that it may be * parsed into the expected type only after the response is checked for errors and for the presence of the expected * response type. Using a generic type is not possible because certain errors are returned in the response element and * not the errors element, which would cause a parsing failure. */ public class JsonWrapper { private JsonElement response;
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/common/ServiceError.java // public final class ServiceError implements Serializable { // // private final String code; // // private final String message; // // public ServiceError(String code, String message) { // this.code = code; // this.message = message; // } // // /** // * Returns the error code identifying the error. // * @return the error code. // */ // public String getCode() { // return code; // } // // /** // * A human readable description of the error, sometimes with additional details of its cause. // * @return a human readable message. // */ // public String getMessage() { // return message; // } // // @Override // public String toString() { // return "ServiceError{" + // "code='" + code + '\'' + // ", message='" + message + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceError that = (ServiceError) o; // if (code != null ? !code.equals(that.code) : that.code != null) return false; // if (message != null ? !message.equals(that.message) : that.message != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = code != null ? code.hashCode() : 0; // result = 31 * result + (message != null ? message.hashCode() : 0); // return result; // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/client/parsing/JsonWrapper.java import com.google.gson.JsonElement; import uk.co.visalia.brightpearl.apiclient.common.ServiceError; import java.util.List; import java.util.Map; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.client.parsing; /** * For internal use only. Raw type used in the parsing of all BP API responses including searches and multimessage responses. * This represents the entirety of the JSON response and stores the response element as unparsed JSON so that it may be * parsed into the expected type only after the response is checked for errors and for the presence of the expected * response type. Using a generic type is not possible because certain errors are returned in the response element and * not the errors element, which would cause a parsing failure. */ public class JsonWrapper { private JsonElement response;
private List<ServiceError> errors;
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceReadRequestSetBuilder.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.lang.reflect.Type; import java.util.*;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * A factory for immutable {@link ServiceReadRequestSet} instances. These requests are used to load large sets of data * easily, by creating individual {@link ServiceReadRequest}s to the same API each with a subset of a large ID set. * <p> * This class is returned from static request builder methods in the services package, and provides a simple method for * setting parameters on all the requests before they are built. * <p> * This builder does not attempt to check that all requests added are to the same API. * * @param <T> placeholder for the response type, used to avoid casting of responses. This is not * linked to the {@link Type} set on each request so a {@link ClassCastException} is possible if the type is set * incorrectly. */ public class ServiceReadRequestSetBuilder<T> { // The set of requests to be executed. These should all be for the same API but there is no check. private Set<ServiceReadRequest<T>> requests = new LinkedHashSet<ServiceReadRequest<T>>(); // Parameters for addition to every request. private Map<String, String> params; // Set to true once build() has been called. Indicates that ruids should be refreshed if it is called again. private boolean regenerateRuids = false; /** * Creates a new paged GET request builder configured with the URL to call and expected response type. This method does * not support extraction of generic types but is able to infer the type parameter &lt;T&gt;. * @param responseType type of result expected in the 'response' element of the JSON response body. This argument is not used for parsing, only to provide * @param <T> placeholder for the response type, used to avoid casting of responses. * @return an OPTIONS request builder instance. */ public static <T> ServiceReadRequestSetBuilder<T> newReadRequestSet(Class<T> responseType) { return new ServiceReadRequestSetBuilder<T>(); } /** * Creates a new paged GET request builder configured with the URL to call and expected response type. This method supports * extraction of generic types (e.g. typed lists or maps) from the response element. * @param <T> placeholder for the response type, used to avoid casting of responses. * @return A GET request builder instance. */ public static <T> ServiceReadRequestSetBuilder<T> newReadRequestSet() { return new ServiceReadRequestSetBuilder<T>(); } /** * Add an additional unencoded querystring parameter to be added to every request, preserving the existing set but * overwriting any param with the same name. The parameter is applied to every request when {@link #build()} is called, * so includes those not yet added. * @param name parameter name. * @param value parameter value. * @return builder instance for method chaining. */ public ServiceReadRequestSetBuilder<T> withAddedParam(String name, String value) {
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceReadRequestSetBuilder.java import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.lang.reflect.Type; import java.util.*; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * A factory for immutable {@link ServiceReadRequestSet} instances. These requests are used to load large sets of data * easily, by creating individual {@link ServiceReadRequest}s to the same API each with a subset of a large ID set. * <p> * This class is returned from static request builder methods in the services package, and provides a simple method for * setting parameters on all the requests before they are built. * <p> * This builder does not attempt to check that all requests added are to the same API. * * @param <T> placeholder for the response type, used to avoid casting of responses. This is not * linked to the {@link Type} set on each request so a {@link ClassCastException} is possible if the type is set * incorrectly. */ public class ServiceReadRequestSetBuilder<T> { // The set of requests to be executed. These should all be for the same API but there is no check. private Set<ServiceReadRequest<T>> requests = new LinkedHashSet<ServiceReadRequest<T>>(); // Parameters for addition to every request. private Map<String, String> params; // Set to true once build() has been called. Indicates that ruids should be refreshed if it is called again. private boolean regenerateRuids = false; /** * Creates a new paged GET request builder configured with the URL to call and expected response type. This method does * not support extraction of generic types but is able to infer the type parameter &lt;T&gt;. * @param responseType type of result expected in the 'response' element of the JSON response body. This argument is not used for parsing, only to provide * @param <T> placeholder for the response type, used to avoid casting of responses. * @return an OPTIONS request builder instance. */ public static <T> ServiceReadRequestSetBuilder<T> newReadRequestSet(Class<T> responseType) { return new ServiceReadRequestSetBuilder<T>(); } /** * Creates a new paged GET request builder configured with the URL to call and expected response type. This method supports * extraction of generic types (e.g. typed lists or maps) from the response element. * @param <T> placeholder for the response type, used to avoid casting of responses. * @return A GET request builder instance. */ public static <T> ServiceReadRequestSetBuilder<T> newReadRequestSet() { return new ServiceReadRequestSetBuilder<T>(); } /** * Add an additional unencoded querystring parameter to be added to every request, preserving the existing set but * overwriting any param with the same name. The parameter is applied to every request when {@link #build()} is called, * so includes those not yet added. * @param name parameter name. * @param value parameter value. * @return builder instance for method chaining. */ public ServiceReadRequestSetBuilder<T> withAddedParam(String name, String value) {
if (StringUtils.isBlank(name)) {
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/multimessage/MultiMessageUtils.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceWriteRequest.java // public class ServiceWriteRequest<T> extends AbstractServiceRequest<T> { // // private final Object entity; // // ServiceWriteRequest(String ruid, ServiceName service, Method method, String path, Type responseType, Map<String, String> params, Object entity) { // super(ruid, service, method, path, responseType, params); // this.entity = entity; // } // // /** // * The entity to be serialised as JSON and sent as the request body. // * @return the request entity object. // */ // public Object getEntity() { // return entity; // } // // }
import uk.co.visalia.brightpearl.apiclient.request.ServiceWriteRequest; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.multimessage; /** * Utilities for multimessage requests. */ public final class MultiMessageUtils { private MultiMessageUtils() { } /** * Splits a {@link MultiRequest} into as many requests as necessary to give no more than ten request, whilst also * avoiding batches of one request (except when the supplied request contains only one request). This is used * internally by {@link uk.co.visalia.brightpearl.apiclient.BrightpearlApiClient} to split requests but may also be used externally to give greater * control over the execution of large batches in case a multimessage or an individual request fails. */ public static List<MultiRequest> split(MultiRequest multiRequest) { if (multiRequest.getRequests().size() > 10) { List<MultiRequest> requests = new ArrayList<MultiRequest>();
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceWriteRequest.java // public class ServiceWriteRequest<T> extends AbstractServiceRequest<T> { // // private final Object entity; // // ServiceWriteRequest(String ruid, ServiceName service, Method method, String path, Type responseType, Map<String, String> params, Object entity) { // super(ruid, service, method, path, responseType, params); // this.entity = entity; // } // // /** // * The entity to be serialised as JSON and sent as the request body. // * @return the request entity object. // */ // public Object getEntity() { // return entity; // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/multimessage/MultiMessageUtils.java import uk.co.visalia.brightpearl.apiclient.request.ServiceWriteRequest; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.multimessage; /** * Utilities for multimessage requests. */ public final class MultiMessageUtils { private MultiMessageUtils() { } /** * Splits a {@link MultiRequest} into as many requests as necessary to give no more than ten request, whilst also * avoiding batches of one request (except when the supplied request contains only one request). This is used * internally by {@link uk.co.visalia.brightpearl.apiclient.BrightpearlApiClient} to split requests but may also be used externally to give greater * control over the execution of large batches in case a multimessage or an individual request fails. */ public static List<MultiRequest> split(MultiRequest multiRequest) { if (multiRequest.getRequests().size() > 10) { List<MultiRequest> requests = new ArrayList<MultiRequest>();
List<ServiceWriteRequest> batch = new ArrayList<ServiceWriteRequest>();
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/auth/PublicAppIdentity.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.util.StringUtils;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.auth; /** * Contains the identity details of a public app. */ public final class PublicAppIdentity { private final String developerReference; private final String developerSecret; private final String appReference; private PublicAppIdentity(String developerReference, String developerSecret, String appReference) { this.developerReference = developerReference; this.developerSecret = developerSecret; this.appReference = appReference; } /** * Create a public app identity where the secret will not be required, either because all authentication will use * staff tokens or because account tokens will be supplied already signed. * @param developerReference Developer's unique reference. * @param appReference App's unique reference. * @return An identity object. */ public static PublicAppIdentity create(String developerReference, String appReference) {
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/auth/PublicAppIdentity.java import uk.co.visalia.brightpearl.apiclient.util.StringUtils; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.auth; /** * Contains the identity details of a public app. */ public final class PublicAppIdentity { private final String developerReference; private final String developerSecret; private final String appReference; private PublicAppIdentity(String developerReference, String developerSecret, String appReference) { this.developerReference = developerReference; this.developerSecret = developerSecret; this.appReference = appReference; } /** * Create a public app identity where the secret will not be required, either because all authentication will use * staff tokens or because account tokens will be supplied already signed. * @param developerReference Developer's unique reference. * @param appReference App's unique reference. * @return An identity object. */ public static PublicAppIdentity create(String developerReference, String appReference) {
if (StringUtils.isBlank(developerReference)) { throw new IllegalArgumentException("Developer reference must be supplied"); }
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceWriteRequestBuilder.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.lang.reflect.Type; import java.util.UUID;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * A factory for immutable {@link ServiceWriteRequest} instances. Static methods provide POST, PUT and DELETE requests configured * with the minimum fields needed to execute a request, and chaining methods are available to set additional attributes * on the request before an immutable instance is build with {@link #build()}. * @param <T> placeholder for the response type, used to avoid casting of responses. This is not * linked to the {@link Type} set on a request so a {@link ClassCastException} is possible if the type is set * incorrectly. */ public class ServiceWriteRequestBuilder<T> extends AbstractServiceRequestBuilder<ServiceWriteRequestBuilder<T>> { private ServiceWriteRequestBuilder() { super(); } private Object entity; @Override protected ServiceWriteRequestBuilder<T> getThis() { return this; } /** * Creates a new POST request builder configured with the URL to call and expected response type. This method does * not support extraction of generic types but is able to infer the type parameter &lt;T&gt;. * @param service Brightpearl service that contains the resource. * @param path path to the search resource, for example '/product'. * @param entity an object to be serialised as JSON and included in the request body. Null is permitted, but rarely appropriate. * @param responseType type of result expected in the 'response' element of the JSON response body. Use Void or null if no response is expected, or the response is not required. * @param <T> placeholder for the response type, used to avoid casting of responses. * @return A POST request builder instance. */
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceWriteRequestBuilder.java import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.lang.reflect.Type; import java.util.UUID; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * A factory for immutable {@link ServiceWriteRequest} instances. Static methods provide POST, PUT and DELETE requests configured * with the minimum fields needed to execute a request, and chaining methods are available to set additional attributes * on the request before an immutable instance is build with {@link #build()}. * @param <T> placeholder for the response type, used to avoid casting of responses. This is not * linked to the {@link Type} set on a request so a {@link ClassCastException} is possible if the type is set * incorrectly. */ public class ServiceWriteRequestBuilder<T> extends AbstractServiceRequestBuilder<ServiceWriteRequestBuilder<T>> { private ServiceWriteRequestBuilder() { super(); } private Object entity; @Override protected ServiceWriteRequestBuilder<T> getThis() { return this; } /** * Creates a new POST request builder configured with the URL to call and expected response type. This method does * not support extraction of generic types but is able to infer the type parameter &lt;T&gt;. * @param service Brightpearl service that contains the resource. * @param path path to the search resource, for example '/product'. * @param entity an object to be serialised as JSON and included in the request body. Null is permitted, but rarely appropriate. * @param responseType type of result expected in the 'response' element of the JSON response body. Use Void or null if no response is expected, or the response is not required. * @param <T> placeholder for the response type, used to avoid casting of responses. * @return A POST request builder instance. */
public static <T> ServiceWriteRequestBuilder<T> newPostRequest(ServiceName service, String path, Object entity, Class<T> responseType) {
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceWriteRequestBuilder.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.lang.reflect.Type; import java.util.UUID;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * A factory for immutable {@link ServiceWriteRequest} instances. Static methods provide POST, PUT and DELETE requests configured * with the minimum fields needed to execute a request, and chaining methods are available to set additional attributes * on the request before an immutable instance is build with {@link #build()}. * @param <T> placeholder for the response type, used to avoid casting of responses. This is not * linked to the {@link Type} set on a request so a {@link ClassCastException} is possible if the type is set * incorrectly. */ public class ServiceWriteRequestBuilder<T> extends AbstractServiceRequestBuilder<ServiceWriteRequestBuilder<T>> { private ServiceWriteRequestBuilder() { super(); } private Object entity; @Override protected ServiceWriteRequestBuilder<T> getThis() { return this; } /** * Creates a new POST request builder configured with the URL to call and expected response type. This method does * not support extraction of generic types but is able to infer the type parameter &lt;T&gt;. * @param service Brightpearl service that contains the resource. * @param path path to the search resource, for example '/product'. * @param entity an object to be serialised as JSON and included in the request body. Null is permitted, but rarely appropriate. * @param responseType type of result expected in the 'response' element of the JSON response body. Use Void or null if no response is expected, or the response is not required. * @param <T> placeholder for the response type, used to avoid casting of responses. * @return A POST request builder instance. */ public static <T> ServiceWriteRequestBuilder<T> newPostRequest(ServiceName service, String path, Object entity, Class<T> responseType) { ServiceWriteRequestBuilder<T> builder = new ServiceWriteRequestBuilder<T>();
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceWriteRequestBuilder.java import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.lang.reflect.Type; import java.util.UUID; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; /** * A factory for immutable {@link ServiceWriteRequest} instances. Static methods provide POST, PUT and DELETE requests configured * with the minimum fields needed to execute a request, and chaining methods are available to set additional attributes * on the request before an immutable instance is build with {@link #build()}. * @param <T> placeholder for the response type, used to avoid casting of responses. This is not * linked to the {@link Type} set on a request so a {@link ClassCastException} is possible if the type is set * incorrectly. */ public class ServiceWriteRequestBuilder<T> extends AbstractServiceRequestBuilder<ServiceWriteRequestBuilder<T>> { private ServiceWriteRequestBuilder() { super(); } private Object entity; @Override protected ServiceWriteRequestBuilder<T> getThis() { return this; } /** * Creates a new POST request builder configured with the URL to call and expected response type. This method does * not support extraction of generic types but is able to infer the type parameter &lt;T&gt;. * @param service Brightpearl service that contains the resource. * @param path path to the search resource, for example '/product'. * @param entity an object to be serialised as JSON and included in the request body. Null is permitted, but rarely appropriate. * @param responseType type of result expected in the 'response' element of the JSON response body. Use Void or null if no response is expected, or the response is not required. * @param <T> placeholder for the response type, used to avoid casting of responses. * @return A POST request builder instance. */ public static <T> ServiceWriteRequestBuilder<T> newPostRequest(ServiceName service, String path, Object entity, Class<T> responseType) { ServiceWriteRequestBuilder<T> builder = new ServiceWriteRequestBuilder<T>();
return builder.withMethod(Method.POST)
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceWriteRequestBuilder.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.lang.reflect.Type; import java.util.UUID;
.withResponseType(responseType); } /** * Creates a new DELETE request builder configured with the URL to call and expected response type. This method supports * extraction of generic types (e.g. typed lists or maps) from the response element. * @param service Brightpearl service that contains the resource. * @param path path to the search resource, for example '/product'. * @param responseType type of result expected in the 'response' element of the JSON response body. Use Void or null if no response is expected, or the response is not required. * @param <T> placeholder for the response type, used to avoid casting of responses. * @return A delete request builder instance. */ public static <T> ServiceWriteRequestBuilder<T> newDeleteRequest(ServiceName service, String path, Type responseType) { ServiceWriteRequestBuilder<T> builder = new ServiceWriteRequestBuilder<T>(); return builder.withMethod(Method.DELETE) .withService(service) .withPath(path) .withResponseType(responseType); } private ServiceWriteRequestBuilder<T> withEntity(Object entity) { this.entity = entity; return getThis(); } /** * Builds an immutable request instance from values provided to this builder. * @return immutable request instance. */ public ServiceWriteRequest<T> build() {
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceWriteRequestBuilder.java import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.lang.reflect.Type; import java.util.UUID; .withResponseType(responseType); } /** * Creates a new DELETE request builder configured with the URL to call and expected response type. This method supports * extraction of generic types (e.g. typed lists or maps) from the response element. * @param service Brightpearl service that contains the resource. * @param path path to the search resource, for example '/product'. * @param responseType type of result expected in the 'response' element of the JSON response body. Use Void or null if no response is expected, or the response is not required. * @param <T> placeholder for the response type, used to avoid casting of responses. * @return A delete request builder instance. */ public static <T> ServiceWriteRequestBuilder<T> newDeleteRequest(ServiceName service, String path, Type responseType) { ServiceWriteRequestBuilder<T> builder = new ServiceWriteRequestBuilder<T>(); return builder.withMethod(Method.DELETE) .withService(service) .withPath(path) .withResponseType(responseType); } private ServiceWriteRequestBuilder<T> withEntity(Object entity) { this.entity = entity; return getThis(); } /** * Builds an immutable request instance from values provided to this builder. * @return immutable request instance. */ public ServiceWriteRequest<T> build() {
String ruid = StringUtils.isNotEmpty(getRuid()) ? getRuid() : UUID.randomUUID().toString();
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/multimessage/ServiceResponse.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/common/ServiceError.java // public final class ServiceError implements Serializable { // // private final String code; // // private final String message; // // public ServiceError(String code, String message) { // this.code = code; // this.message = message; // } // // /** // * Returns the error code identifying the error. // * @return the error code. // */ // public String getCode() { // return code; // } // // /** // * A human readable description of the error, sometimes with additional details of its cause. // * @return a human readable message. // */ // public String getMessage() { // return message; // } // // @Override // public String toString() { // return "ServiceError{" + // "code='" + code + '\'' + // ", message='" + message + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceError that = (ServiceError) o; // if (code != null ? !code.equals(that.code) : that.code != null) return false; // if (message != null ? !message.equals(that.message) : that.message != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = code != null ? code.hashCode() : 0; // result = 31 * result + (message != null ? message.hashCode() : 0); // return result; // } // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/exception/BrightpearlServiceException.java // public class BrightpearlServiceException extends BrightpearlClientException { // // private final int status; // // private final List<ServiceError> serviceErrors; // // public BrightpearlServiceException(int status, List<ServiceError> serviceErrors) { // super(buildMessage(status, serviceErrors)); // this.status = status; // this.serviceErrors = serviceErrors == null ? null : Collections.unmodifiableList(serviceErrors); // } // // /** // * Returns the HTTP status of the response received. // * @return HTTP response status. // */ // public int getStatus() { // return status; // } // // /** // * Returns service errors from the response. // * @return service errors. // */ // public List<ServiceError> getServiceErrors() { // return serviceErrors; // } // // private static String buildMessage(int status, List<ServiceError> serviceErrors) { // if (serviceErrors != null) { // StringBuilder builder = new StringBuilder(); // for (ServiceError serviceError : serviceErrors) { // if (builder.length() > 0) { // builder.append(", "); // } // builder.append(serviceError.getCode()); // } // return "Status code " + status + " and " + serviceErrors.size() + " errors returned from Brightpearl API (" + builder.toString() + ")"; // } // return "Status code " + status + " and 0 errors returned from Brightpearl API"; // } // // }
import uk.co.visalia.brightpearl.apiclient.common.ServiceError; import uk.co.visalia.brightpearl.apiclient.exception.BrightpearlServiceException; import java.util.List;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.multimessage; /** * Contains the response for an individual request executed in a multimessage batch. * @param <T> placeholder for the response type. */ public final class ServiceResponse<T> { /** * The unique ID of the request sent. */ private final String ruid; /** * HTTP status code received. */ private final int status; /** * The parsed response entity of the type expected for the request. */ private final T response; /** * Errors returned by the Brightpearl API. */
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/common/ServiceError.java // public final class ServiceError implements Serializable { // // private final String code; // // private final String message; // // public ServiceError(String code, String message) { // this.code = code; // this.message = message; // } // // /** // * Returns the error code identifying the error. // * @return the error code. // */ // public String getCode() { // return code; // } // // /** // * A human readable description of the error, sometimes with additional details of its cause. // * @return a human readable message. // */ // public String getMessage() { // return message; // } // // @Override // public String toString() { // return "ServiceError{" + // "code='" + code + '\'' + // ", message='" + message + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceError that = (ServiceError) o; // if (code != null ? !code.equals(that.code) : that.code != null) return false; // if (message != null ? !message.equals(that.message) : that.message != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = code != null ? code.hashCode() : 0; // result = 31 * result + (message != null ? message.hashCode() : 0); // return result; // } // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/exception/BrightpearlServiceException.java // public class BrightpearlServiceException extends BrightpearlClientException { // // private final int status; // // private final List<ServiceError> serviceErrors; // // public BrightpearlServiceException(int status, List<ServiceError> serviceErrors) { // super(buildMessage(status, serviceErrors)); // this.status = status; // this.serviceErrors = serviceErrors == null ? null : Collections.unmodifiableList(serviceErrors); // } // // /** // * Returns the HTTP status of the response received. // * @return HTTP response status. // */ // public int getStatus() { // return status; // } // // /** // * Returns service errors from the response. // * @return service errors. // */ // public List<ServiceError> getServiceErrors() { // return serviceErrors; // } // // private static String buildMessage(int status, List<ServiceError> serviceErrors) { // if (serviceErrors != null) { // StringBuilder builder = new StringBuilder(); // for (ServiceError serviceError : serviceErrors) { // if (builder.length() > 0) { // builder.append(", "); // } // builder.append(serviceError.getCode()); // } // return "Status code " + status + " and " + serviceErrors.size() + " errors returned from Brightpearl API (" + builder.toString() + ")"; // } // return "Status code " + status + " and 0 errors returned from Brightpearl API"; // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/multimessage/ServiceResponse.java import uk.co.visalia.brightpearl.apiclient.common.ServiceError; import uk.co.visalia.brightpearl.apiclient.exception.BrightpearlServiceException; import java.util.List; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.multimessage; /** * Contains the response for an individual request executed in a multimessage batch. * @param <T> placeholder for the response type. */ public final class ServiceResponse<T> { /** * The unique ID of the request sent. */ private final String ruid; /** * HTTP status code received. */ private final int status; /** * The parsed response entity of the type expected for the request. */ private final T response; /** * Errors returned by the Brightpearl API. */
private final List<ServiceError> errors;
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/multimessage/ServiceResponse.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/common/ServiceError.java // public final class ServiceError implements Serializable { // // private final String code; // // private final String message; // // public ServiceError(String code, String message) { // this.code = code; // this.message = message; // } // // /** // * Returns the error code identifying the error. // * @return the error code. // */ // public String getCode() { // return code; // } // // /** // * A human readable description of the error, sometimes with additional details of its cause. // * @return a human readable message. // */ // public String getMessage() { // return message; // } // // @Override // public String toString() { // return "ServiceError{" + // "code='" + code + '\'' + // ", message='" + message + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceError that = (ServiceError) o; // if (code != null ? !code.equals(that.code) : that.code != null) return false; // if (message != null ? !message.equals(that.message) : that.message != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = code != null ? code.hashCode() : 0; // result = 31 * result + (message != null ? message.hashCode() : 0); // return result; // } // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/exception/BrightpearlServiceException.java // public class BrightpearlServiceException extends BrightpearlClientException { // // private final int status; // // private final List<ServiceError> serviceErrors; // // public BrightpearlServiceException(int status, List<ServiceError> serviceErrors) { // super(buildMessage(status, serviceErrors)); // this.status = status; // this.serviceErrors = serviceErrors == null ? null : Collections.unmodifiableList(serviceErrors); // } // // /** // * Returns the HTTP status of the response received. // * @return HTTP response status. // */ // public int getStatus() { // return status; // } // // /** // * Returns service errors from the response. // * @return service errors. // */ // public List<ServiceError> getServiceErrors() { // return serviceErrors; // } // // private static String buildMessage(int status, List<ServiceError> serviceErrors) { // if (serviceErrors != null) { // StringBuilder builder = new StringBuilder(); // for (ServiceError serviceError : serviceErrors) { // if (builder.length() > 0) { // builder.append(", "); // } // builder.append(serviceError.getCode()); // } // return "Status code " + status + " and " + serviceErrors.size() + " errors returned from Brightpearl API (" + builder.toString() + ")"; // } // return "Status code " + status + " and 0 errors returned from Brightpearl API"; // } // // }
import uk.co.visalia.brightpearl.apiclient.common.ServiceError; import uk.co.visalia.brightpearl.apiclient.exception.BrightpearlServiceException; import java.util.List;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.multimessage; /** * Contains the response for an individual request executed in a multimessage batch. * @param <T> placeholder for the response type. */ public final class ServiceResponse<T> { /** * The unique ID of the request sent. */ private final String ruid; /** * HTTP status code received. */ private final int status; /** * The parsed response entity of the type expected for the request. */ private final T response; /** * Errors returned by the Brightpearl API. */ private final List<ServiceError> errors; /** * Exception encountered processing the response for this individual item. */ private final RuntimeException exception; ServiceResponse(String ruid, int status, T response, RuntimeException exception) { this.ruid = ruid; this.status = status; this.response = response; this.exception = exception;
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/common/ServiceError.java // public final class ServiceError implements Serializable { // // private final String code; // // private final String message; // // public ServiceError(String code, String message) { // this.code = code; // this.message = message; // } // // /** // * Returns the error code identifying the error. // * @return the error code. // */ // public String getCode() { // return code; // } // // /** // * A human readable description of the error, sometimes with additional details of its cause. // * @return a human readable message. // */ // public String getMessage() { // return message; // } // // @Override // public String toString() { // return "ServiceError{" + // "code='" + code + '\'' + // ", message='" + message + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceError that = (ServiceError) o; // if (code != null ? !code.equals(that.code) : that.code != null) return false; // if (message != null ? !message.equals(that.message) : that.message != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = code != null ? code.hashCode() : 0; // result = 31 * result + (message != null ? message.hashCode() : 0); // return result; // } // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/exception/BrightpearlServiceException.java // public class BrightpearlServiceException extends BrightpearlClientException { // // private final int status; // // private final List<ServiceError> serviceErrors; // // public BrightpearlServiceException(int status, List<ServiceError> serviceErrors) { // super(buildMessage(status, serviceErrors)); // this.status = status; // this.serviceErrors = serviceErrors == null ? null : Collections.unmodifiableList(serviceErrors); // } // // /** // * Returns the HTTP status of the response received. // * @return HTTP response status. // */ // public int getStatus() { // return status; // } // // /** // * Returns service errors from the response. // * @return service errors. // */ // public List<ServiceError> getServiceErrors() { // return serviceErrors; // } // // private static String buildMessage(int status, List<ServiceError> serviceErrors) { // if (serviceErrors != null) { // StringBuilder builder = new StringBuilder(); // for (ServiceError serviceError : serviceErrors) { // if (builder.length() > 0) { // builder.append(", "); // } // builder.append(serviceError.getCode()); // } // return "Status code " + status + " and " + serviceErrors.size() + " errors returned from Brightpearl API (" + builder.toString() + ")"; // } // return "Status code " + status + " and 0 errors returned from Brightpearl API"; // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/multimessage/ServiceResponse.java import uk.co.visalia.brightpearl.apiclient.common.ServiceError; import uk.co.visalia.brightpearl.apiclient.exception.BrightpearlServiceException; import java.util.List; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.multimessage; /** * Contains the response for an individual request executed in a multimessage batch. * @param <T> placeholder for the response type. */ public final class ServiceResponse<T> { /** * The unique ID of the request sent. */ private final String ruid; /** * HTTP status code received. */ private final int status; /** * The parsed response entity of the type expected for the request. */ private final T response; /** * Errors returned by the Brightpearl API. */ private final List<ServiceError> errors; /** * Exception encountered processing the response for this individual item. */ private final RuntimeException exception; ServiceResponse(String ruid, int status, T response, RuntimeException exception) { this.ruid = ruid; this.status = status; this.response = response; this.exception = exception;
if (exception instanceof BrightpearlServiceException) {
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/auth/AppAuthorisation.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java // public final class Account implements Serializable { // // private final Datacenter datacenter; // // private final String accountCode; // // /** // * Construct an account instance. // * @param datacenter the datacenter that hosts the account. // * @param accountCode the customer account code. // */ // public Account(Datacenter datacenter, String accountCode) { // if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) { // throw new IllegalArgumentException("A datacenter name and host must be provided"); // } // if (StringUtils.isBlank(accountCode)) { // throw new IllegalArgumentException("An account code must be provided"); // } // this.datacenter = datacenter; // this.accountCode = accountCode; // } // // /** // * Returns the datacenter // * @return the datacenter that hosts the account. // */ // public Datacenter getDatacenter() { // return datacenter; // } // // public String getAccountCode() { // return accountCode; // } // // @Override // public String toString() { // return "Account{" + // "datacenter=" + datacenter + // ", accountCode='" + accountCode + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Account account = (Account) o; // if (accountCode != null ? !accountCode.equals(account.accountCode) : account.accountCode != null) return false; // if (datacenter != null ? !datacenter.equals(account.datacenter) : account.datacenter != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = datacenter != null ? datacenter.hashCode() : 0; // result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); // return result; // } // }
import uk.co.visalia.brightpearl.apiclient.account.Account; import java.util.Map;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.auth; /** * <p> * Interface for classes that combine details of an an app with details of an account, providing account details * and authentication headers for {@link uk.co.visalia.brightpearl.apiclient.BrightpearlApiClient}. * </p><p> * This interface is generic enough to support all four types of app, which each require different headers, together with * legacy auth tokens. * </p> */ public interface AppAuthorisation { static final String DEV_HEADER = "brightpearl-dev-ref"; static final String APP_HEADER = "brightpearl-app-ref"; static final String ACCOUNT_TOKEN_HEADER = "brightpearl-account-token"; static final String STAFF_TOKEN_HEADER = "brightpearl-staff-token"; static final String LEGACY_AUTH_HEADER = "brightpearl-auth"; /** * Returns the Brightpearl customer's account. */
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java // public final class Account implements Serializable { // // private final Datacenter datacenter; // // private final String accountCode; // // /** // * Construct an account instance. // * @param datacenter the datacenter that hosts the account. // * @param accountCode the customer account code. // */ // public Account(Datacenter datacenter, String accountCode) { // if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) { // throw new IllegalArgumentException("A datacenter name and host must be provided"); // } // if (StringUtils.isBlank(accountCode)) { // throw new IllegalArgumentException("An account code must be provided"); // } // this.datacenter = datacenter; // this.accountCode = accountCode; // } // // /** // * Returns the datacenter // * @return the datacenter that hosts the account. // */ // public Datacenter getDatacenter() { // return datacenter; // } // // public String getAccountCode() { // return accountCode; // } // // @Override // public String toString() { // return "Account{" + // "datacenter=" + datacenter + // ", accountCode='" + accountCode + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Account account = (Account) o; // if (accountCode != null ? !accountCode.equals(account.accountCode) : account.accountCode != null) return false; // if (datacenter != null ? !datacenter.equals(account.datacenter) : account.datacenter != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = datacenter != null ? datacenter.hashCode() : 0; // result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); // return result; // } // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/auth/AppAuthorisation.java import uk.co.visalia.brightpearl.apiclient.account.Account; import java.util.Map; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.auth; /** * <p> * Interface for classes that combine details of an an app with details of an account, providing account details * and authentication headers for {@link uk.co.visalia.brightpearl.apiclient.BrightpearlApiClient}. * </p><p> * This interface is generic enough to support all four types of app, which each require different headers, together with * legacy auth tokens. * </p> */ public interface AppAuthorisation { static final String DEV_HEADER = "brightpearl-dev-ref"; static final String APP_HEADER = "brightpearl-app-ref"; static final String ACCOUNT_TOKEN_HEADER = "brightpearl-account-token"; static final String STAFF_TOKEN_HEADER = "brightpearl-staff-token"; static final String LEGACY_AUTH_HEADER = "brightpearl-auth"; /** * Returns the Brightpearl customer's account. */
Account getAccount();
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/multimessage/MultiResponse.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceWriteRequest.java // public class ServiceWriteRequest<T> extends AbstractServiceRequest<T> { // // private final Object entity; // // ServiceWriteRequest(String ruid, ServiceName service, Method method, String path, Type responseType, Map<String, String> params, Object entity) { // super(ruid, service, method, path, responseType, params); // this.entity = entity; // } // // /** // * The entity to be serialised as JSON and sent as the request body. // * @return the request entity object. // */ // public Object getEntity() { // return entity; // } // // }
import uk.co.visalia.brightpearl.apiclient.request.ServiceWriteRequest; import java.util.*;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.multimessage; /** * Contains the results of a multimessage request. This consists of the status code from the multimessage API, results of * each request executed, and a list of unique IDs for the requests that were not executed. * @see <a href="http://www.brightpearl.com/developer/latest/concept/multi-message.html">http://www.brightpearl.com/developer/latest/concept/multi-message.html</a> */ public final class MultiResponse { /** * HTTP status code for the multimessage wrapper. */ private int status; /** * Map of request ID to result received for the individual request. */ private Map<String, ServiceResponse> serviceResponseMap; /** * List of IDs of requests that were not executed. */ private List<String> unprocessedRequestRuids; MultiResponse(int status, Map<String, ServiceResponse> serviceResponseMap, List<String> unprocessedRequestRuids) { this.status = status; this.serviceResponseMap = serviceResponseMap == null ? Collections.unmodifiableMap(new HashMap<String, ServiceResponse>()) : Collections.unmodifiableMap(serviceResponseMap); this.unprocessedRequestRuids = unprocessedRequestRuids == null ? Collections.unmodifiableList(new ArrayList<String>()) : Collections.unmodifiableList(unprocessedRequestRuids); } /** * Returns the status code for the multimessage container request. If the request succeeded, the response code will * be 200 if all individual messages received 200 responses, and 207 if any did not. Regardless of this status code, * the {@link #getUnprocessedRequestRuids()} collection and the results of each individual request from {@link #getServiceResponse(String)} * should be inspected to confirm the requests were all successfully executed. * @return status code of the multimessage request. */ public int getStatus() { return status; } /** * Fetches the response for an individual request included in the multimessage, using the request's unique ID. This * is equivalent to passing the ID to {@link #getServiceResponse(String)} but hides casting of the response to the * correct generic type. * @param request A request sent in the multi-message. * @param <T> Type of response entity expected for the request. * @return The response received for the individual request, or null if the ID is either not valid or the request was not processed due to an earlier failure. */ @SuppressWarnings("unchecked")
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceWriteRequest.java // public class ServiceWriteRequest<T> extends AbstractServiceRequest<T> { // // private final Object entity; // // ServiceWriteRequest(String ruid, ServiceName service, Method method, String path, Type responseType, Map<String, String> params, Object entity) { // super(ruid, service, method, path, responseType, params); // this.entity = entity; // } // // /** // * The entity to be serialised as JSON and sent as the request body. // * @return the request entity object. // */ // public Object getEntity() { // return entity; // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/multimessage/MultiResponse.java import uk.co.visalia.brightpearl.apiclient.request.ServiceWriteRequest; import java.util.*; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.multimessage; /** * Contains the results of a multimessage request. This consists of the status code from the multimessage API, results of * each request executed, and a list of unique IDs for the requests that were not executed. * @see <a href="http://www.brightpearl.com/developer/latest/concept/multi-message.html">http://www.brightpearl.com/developer/latest/concept/multi-message.html</a> */ public final class MultiResponse { /** * HTTP status code for the multimessage wrapper. */ private int status; /** * Map of request ID to result received for the individual request. */ private Map<String, ServiceResponse> serviceResponseMap; /** * List of IDs of requests that were not executed. */ private List<String> unprocessedRequestRuids; MultiResponse(int status, Map<String, ServiceResponse> serviceResponseMap, List<String> unprocessedRequestRuids) { this.status = status; this.serviceResponseMap = serviceResponseMap == null ? Collections.unmodifiableMap(new HashMap<String, ServiceResponse>()) : Collections.unmodifiableMap(serviceResponseMap); this.unprocessedRequestRuids = unprocessedRequestRuids == null ? Collections.unmodifiableList(new ArrayList<String>()) : Collections.unmodifiableList(unprocessedRequestRuids); } /** * Returns the status code for the multimessage container request. If the request succeeded, the response code will * be 200 if all individual messages received 200 responses, and 207 if any did not. Regardless of this status code, * the {@link #getUnprocessedRequestRuids()} collection and the results of each individual request from {@link #getServiceResponse(String)} * should be inspected to confirm the requests were all successfully executed. * @return status code of the multimessage request. */ public int getStatus() { return status; } /** * Fetches the response for an individual request included in the multimessage, using the request's unique ID. This * is equivalent to passing the ID to {@link #getServiceResponse(String)} but hides casting of the response to the * correct generic type. * @param request A request sent in the multi-message. * @param <T> Type of response entity expected for the request. * @return The response received for the individual request, or null if the ID is either not valid or the request was not processed due to an earlier failure. */ @SuppressWarnings("unchecked")
public <T> ServiceResponse<T> getServiceResponse(ServiceWriteRequest<T> request) {
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/client/multimessage/MultiMessage.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/multimessage/OnFailOption.java // public enum OnFailOption { // // /** // * Cancel the processing of subsequent requests in a multi-message batch when one fails. This option cannot be used // * with the {@link ProcessingMode#PARALLEL} processing option. // */ // STOP, // // /** // * Continue processing all requests in a multi-message regardless of failures. // */ // CONTINUE // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/multimessage/ProcessingMode.java // public enum ProcessingMode { // // /** // * Process the individual requests of a multi-message in parallel. This option cannot be used with {@link OnFailOption#STOP}. // */ // PARALLEL, // // /** // * Process the individual requests of a multi-message in sequence. // */ // SEQUENTIAL // // }
import uk.co.visalia.brightpearl.apiclient.multimessage.OnFailOption; import uk.co.visalia.brightpearl.apiclient.multimessage.ProcessingMode; import java.util.Collections; import java.util.List;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.client.multimessage; /** * For internal use only. Represents the JSON body of a multimessage request. */ public class MultiMessage { private ProcessingMode processingMode;
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/multimessage/OnFailOption.java // public enum OnFailOption { // // /** // * Cancel the processing of subsequent requests in a multi-message batch when one fails. This option cannot be used // * with the {@link ProcessingMode#PARALLEL} processing option. // */ // STOP, // // /** // * Continue processing all requests in a multi-message regardless of failures. // */ // CONTINUE // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/multimessage/ProcessingMode.java // public enum ProcessingMode { // // /** // * Process the individual requests of a multi-message in parallel. This option cannot be used with {@link OnFailOption#STOP}. // */ // PARALLEL, // // /** // * Process the individual requests of a multi-message in sequence. // */ // SEQUENTIAL // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/client/multimessage/MultiMessage.java import uk.co.visalia.brightpearl.apiclient.multimessage.OnFailOption; import uk.co.visalia.brightpearl.apiclient.multimessage.ProcessingMode; import java.util.Collections; import java.util.List; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.client.multimessage; /** * For internal use only. Represents the JSON body of a multimessage request. */ public class MultiMessage { private ProcessingMode processingMode;
private OnFailOption onFail;
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceSearchRequestBuilder.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.lang.reflect.Type; import java.util.*;
ServiceSearchRequestBuilder<T> builder = new ServiceSearchRequestBuilder<T>(); return builder.withMethod(Method.GET) .withService(service) .withPath(path) .withResponseType(responseType); } /** * Creates a new search request builder configured with the URL to call and expected response type. Filters, column * selection, pagination and sorting parameters can be added if required. * @param service Brightpearl service that contains the resource. * @param path Path to the search resource, for example '/product-search'. * @param responseType Type of search result expected. In many cases this will be a different class to that used for * resource GET requests; it must have a flat structure with fields corresponding to column names. * @param <T> Placeholder for the response type, used to avoid casting of responses. Responses are parsed into the type defined by responseType, not this type parameter. * @return A search request builder instance. */ public static <T> ServiceSearchRequestBuilder<T> newSearchRequest(ServiceName service, String path, Type responseType) { ServiceSearchRequestBuilder<T> builder = new ServiceSearchRequestBuilder<T>(); return builder.withMethod(Method.GET) .withService(service) .withPath(path) .withResponseType(responseType); } /** * Constructs the immutable request instance for execution. * @return an immutable search request. */ public ServiceSearchRequest<T> build() {
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/Method.java // public enum Method { // // GET, // POST, // PUT, // DELETE, // OPTIONS // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/request/ServiceSearchRequestBuilder.java import uk.co.visalia.brightpearl.apiclient.ServiceName; import uk.co.visalia.brightpearl.apiclient.http.Method; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.lang.reflect.Type; import java.util.*; ServiceSearchRequestBuilder<T> builder = new ServiceSearchRequestBuilder<T>(); return builder.withMethod(Method.GET) .withService(service) .withPath(path) .withResponseType(responseType); } /** * Creates a new search request builder configured with the URL to call and expected response type. Filters, column * selection, pagination and sorting parameters can be added if required. * @param service Brightpearl service that contains the resource. * @param path Path to the search resource, for example '/product-search'. * @param responseType Type of search result expected. In many cases this will be a different class to that used for * resource GET requests; it must have a flat structure with fields corresponding to column names. * @param <T> Placeholder for the response type, used to avoid casting of responses. Responses are parsed into the type defined by responseType, not this type parameter. * @return A search request builder instance. */ public static <T> ServiceSearchRequestBuilder<T> newSearchRequest(ServiceName service, String path, Type responseType) { ServiceSearchRequestBuilder<T> builder = new ServiceSearchRequestBuilder<T>(); return builder.withMethod(Method.GET) .withService(service) .withPath(path) .withResponseType(responseType); } /** * Constructs the immutable request instance for execution. * @return an immutable search request. */ public ServiceSearchRequest<T> build() {
String ruid = StringUtils.isNotEmpty(getRuid()) ? getRuid() : UUID.randomUUID().toString();
davemorrissey/brightpearl-api-client-java
src/test/java/uk/co/visalia/brightpearl/apiclient/request/ServiceReadRequestBuilderTest.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // }
import org.junit.Test; import uk.co.visalia.brightpearl.apiclient.ServiceName; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; public class ServiceReadRequestBuilderTest { /** * Ensure that each ruid is only used once. */ @Test public void testUniqueRandomRuids() {
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ServiceName.java // public final class ServiceName { // // private static final Pattern PATH_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-]+"); // // public static final ServiceName ACCOUNTING = new ServiceName("accounting-service"); // public static final ServiceName CONTACT = new ServiceName("contact-service"); // public static final ServiceName INTEGRATION = new ServiceName("integration-service"); // public static final ServiceName ORDER = new ServiceName("order-service"); // public static final ServiceName PRODUCT = new ServiceName("product-service"); // public static final ServiceName WAREHOUSE = new ServiceName("warehouse-service"); // // private final String path; // // /** // * Constructs a custom service name instance, using the path, for example &quot;product-service&quot;. // * @param path path component for the service. // */ // public ServiceName(String path) { // validatePath(path); // this.path = path; // } // // /** // * Returns the URI component for the service, for example &quot;product-service&quot;. // * @return path component for the service. // */ // public String getPath() { // return path; // } // // private void validatePath(String path) { // if (path == null || path.trim().length() == 0) { // throw new IllegalArgumentException("Service path must be provided"); // } else if (!PATH_PATTERN.matcher(path).matches()) { // throw new IllegalArgumentException("Service must contain alphanumeric characters, hyphen and underscore only"); // } // } // // @Override // public String toString() { // return "ServiceName{" + // "path='" + path + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ServiceName that = (ServiceName) o; // if (path != null ? !path.equals(that.path) : that.path != null) return false; // return true; // } // // @Override // public int hashCode() { // return path != null ? path.hashCode() : 0; // } // } // Path: src/test/java/uk/co/visalia/brightpearl/apiclient/request/ServiceReadRequestBuilderTest.java import org.junit.Test; import uk.co.visalia.brightpearl.apiclient.ServiceName; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.request; public class ServiceReadRequestBuilderTest { /** * Ensure that each ruid is only used once. */ @Test public void testUniqueRandomRuids() {
ServiceReadRequestBuilder<Void> builder = ServiceReadRequestBuilder.newGetRequest(ServiceName.CONTACT, "/contact", Void.class);
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/auth/PrivateAppIdentity.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java // public final class Account implements Serializable { // // private final Datacenter datacenter; // // private final String accountCode; // // /** // * Construct an account instance. // * @param datacenter the datacenter that hosts the account. // * @param accountCode the customer account code. // */ // public Account(Datacenter datacenter, String accountCode) { // if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) { // throw new IllegalArgumentException("A datacenter name and host must be provided"); // } // if (StringUtils.isBlank(accountCode)) { // throw new IllegalArgumentException("An account code must be provided"); // } // this.datacenter = datacenter; // this.accountCode = accountCode; // } // // /** // * Returns the datacenter // * @return the datacenter that hosts the account. // */ // public Datacenter getDatacenter() { // return datacenter; // } // // public String getAccountCode() { // return accountCode; // } // // @Override // public String toString() { // return "Account{" + // "datacenter=" + datacenter + // ", accountCode='" + accountCode + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Account account = (Account) o; // if (accountCode != null ? !accountCode.equals(account.accountCode) : account.accountCode != null) return false; // if (datacenter != null ? !datacenter.equals(account.datacenter) : account.datacenter != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = datacenter != null ? datacenter.hashCode() : 0; // result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); // return result; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.account.Account; import uk.co.visalia.brightpearl.apiclient.util.StringUtils;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.auth; /** * Contains the identity of a private app, which is specific to a single Brightpearl account. It contains the account * details as well, because all calls made for this app must go to the same account. */ public final class PrivateAppIdentity { private final String appReference;
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java // public final class Account implements Serializable { // // private final Datacenter datacenter; // // private final String accountCode; // // /** // * Construct an account instance. // * @param datacenter the datacenter that hosts the account. // * @param accountCode the customer account code. // */ // public Account(Datacenter datacenter, String accountCode) { // if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) { // throw new IllegalArgumentException("A datacenter name and host must be provided"); // } // if (StringUtils.isBlank(accountCode)) { // throw new IllegalArgumentException("An account code must be provided"); // } // this.datacenter = datacenter; // this.accountCode = accountCode; // } // // /** // * Returns the datacenter // * @return the datacenter that hosts the account. // */ // public Datacenter getDatacenter() { // return datacenter; // } // // public String getAccountCode() { // return accountCode; // } // // @Override // public String toString() { // return "Account{" + // "datacenter=" + datacenter + // ", accountCode='" + accountCode + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Account account = (Account) o; // if (accountCode != null ? !accountCode.equals(account.accountCode) : account.accountCode != null) return false; // if (datacenter != null ? !datacenter.equals(account.datacenter) : account.datacenter != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = datacenter != null ? datacenter.hashCode() : 0; // result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); // return result; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/auth/PrivateAppIdentity.java import uk.co.visalia.brightpearl.apiclient.account.Account; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.auth; /** * Contains the identity of a private app, which is specific to a single Brightpearl account. It contains the account * details as well, because all calls made for this app must go to the same account. */ public final class PrivateAppIdentity { private final String appReference;
private final Account account;
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/auth/PrivateAppIdentity.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java // public final class Account implements Serializable { // // private final Datacenter datacenter; // // private final String accountCode; // // /** // * Construct an account instance. // * @param datacenter the datacenter that hosts the account. // * @param accountCode the customer account code. // */ // public Account(Datacenter datacenter, String accountCode) { // if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) { // throw new IllegalArgumentException("A datacenter name and host must be provided"); // } // if (StringUtils.isBlank(accountCode)) { // throw new IllegalArgumentException("An account code must be provided"); // } // this.datacenter = datacenter; // this.accountCode = accountCode; // } // // /** // * Returns the datacenter // * @return the datacenter that hosts the account. // */ // public Datacenter getDatacenter() { // return datacenter; // } // // public String getAccountCode() { // return accountCode; // } // // @Override // public String toString() { // return "Account{" + // "datacenter=" + datacenter + // ", accountCode='" + accountCode + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Account account = (Account) o; // if (accountCode != null ? !accountCode.equals(account.accountCode) : account.accountCode != null) return false; // if (datacenter != null ? !datacenter.equals(account.datacenter) : account.datacenter != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = datacenter != null ? datacenter.hashCode() : 0; // result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); // return result; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.account.Account; import uk.co.visalia.brightpearl.apiclient.util.StringUtils;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.auth; /** * Contains the identity of a private app, which is specific to a single Brightpearl account. It contains the account * details as well, because all calls made for this app must go to the same account. */ public final class PrivateAppIdentity { private final String appReference; private final Account account; private PrivateAppIdentity(Account account, String appReference) { this.account = account; this.appReference = appReference; } /** * Create a private app identity. * @param account A Brightpearl customer account. * @param appReference The private app's unique reference. * @return An identity object. */ public static PrivateAppIdentity create(Account account, String appReference) { if (account == null) { throw new IllegalArgumentException("Account must not be null"); }
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java // public final class Account implements Serializable { // // private final Datacenter datacenter; // // private final String accountCode; // // /** // * Construct an account instance. // * @param datacenter the datacenter that hosts the account. // * @param accountCode the customer account code. // */ // public Account(Datacenter datacenter, String accountCode) { // if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) { // throw new IllegalArgumentException("A datacenter name and host must be provided"); // } // if (StringUtils.isBlank(accountCode)) { // throw new IllegalArgumentException("An account code must be provided"); // } // this.datacenter = datacenter; // this.accountCode = accountCode; // } // // /** // * Returns the datacenter // * @return the datacenter that hosts the account. // */ // public Datacenter getDatacenter() { // return datacenter; // } // // public String getAccountCode() { // return accountCode; // } // // @Override // public String toString() { // return "Account{" + // "datacenter=" + datacenter + // ", accountCode='" + accountCode + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Account account = (Account) o; // if (accountCode != null ? !accountCode.equals(account.accountCode) : account.accountCode != null) return false; // if (datacenter != null ? !datacenter.equals(account.datacenter) : account.datacenter != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = datacenter != null ? datacenter.hashCode() : 0; // result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); // return result; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/auth/PrivateAppIdentity.java import uk.co.visalia.brightpearl.apiclient.account.Account; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.auth; /** * Contains the identity of a private app, which is specific to a single Brightpearl account. It contains the account * details as well, because all calls made for this app must go to the same account. */ public final class PrivateAppIdentity { private final String appReference; private final Account account; private PrivateAppIdentity(Account account, String appReference) { this.account = account; this.appReference = appReference; } /** * Create a private app identity. * @param account A Brightpearl customer account. * @param appReference The private app's unique reference. * @return An identity object. */ public static PrivateAppIdentity create(Account account, String appReference) { if (account == null) { throw new IllegalArgumentException("Account must not be null"); }
if (StringUtils.isBlank(appReference)) { throw new IllegalArgumentException("App reference must be supplied"); }
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/client/adaptors/CalendarAdaptor.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.io.IOException; import java.util.Calendar;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.client.adaptors; /** * A custom GSON serialiser and deserialiser implementation that supports {@link Calendar}s represented as ISO date times. */ public class CalendarAdaptor extends TypeAdapter<Calendar> { private static DatatypeFactory datatypeFactory; private static Exception storedInitException; static { try { datatypeFactory = DatatypeFactory.newInstance(); } catch (Exception e) { storedInitException = e; } } @Override public Calendar read(JsonReader jsonReader) throws IOException { if (jsonReader.peek() == JsonToken.NULL) { jsonReader.nextNull(); return null; } String string = jsonReader.nextString();
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/client/adaptors/CalendarAdaptor.java import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.io.IOException; import java.util.Calendar; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.client.adaptors; /** * A custom GSON serialiser and deserialiser implementation that supports {@link Calendar}s represented as ISO date times. */ public class CalendarAdaptor extends TypeAdapter<Calendar> { private static DatatypeFactory datatypeFactory; private static Exception storedInitException; static { try { datatypeFactory = DatatypeFactory.newInstance(); } catch (Exception e) { storedInitException = e; } } @Override public Calendar read(JsonReader jsonReader) throws IOException { if (jsonReader.peek() == JsonToken.NULL) { jsonReader.nextNull(); return null; } String string = jsonReader.nextString();
if (StringUtils.isNotBlank(string)) {
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/http/httpclient4/HttpClient4Client.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/exception/BrightpearlHttpException.java // public class BrightpearlHttpException extends BrightpearlClientException { // // private final ClientErrorCode clientErrorCode; // // public BrightpearlHttpException(ClientErrorCode clientErrorCode) { // super("Brightpearl request failed: " + clientErrorCode); // this.clientErrorCode = clientErrorCode; // } // // public BrightpearlHttpException(ClientErrorCode clientErrorCode, String message) { // super("Brightpearl request failed: " + clientErrorCode + " (" + message + ")"); // this.clientErrorCode = clientErrorCode; // } // // public BrightpearlHttpException(ClientErrorCode clientErrorCode, Exception e) { // super("Brightpearl request failed: " + clientErrorCode + " (" + e.getClass().getSimpleName() + ")", e); // this.clientErrorCode = clientErrorCode; // } // // public ClientErrorCode getClientErrorCode() { // return clientErrorCode; // } // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/exception/ClientErrorCode.java // public enum ClientErrorCode { // // EMPTY_RESPONSE, // INVALID_RESPONSE_FORMAT, // INVALID_RESPONSE_TYPE, // NO_RESPONSE, // UNKNOWN_HOST, // CONNECTION_TIMEOUT, // SOCKET_ERROR, // SOCKET_TIMEOUT, // READ_TIMEOUT, // OTHER_TRANSPORT_ERROR // // }
import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.NoHttpResponseException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.*; import org.apache.http.client.utils.URIBuilder; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.entity.StringEntity; import org.apache.http.util.EntityUtils; import uk.co.visalia.brightpearl.apiclient.exception.BrightpearlHttpException; import uk.co.visalia.brightpearl.apiclient.exception.ClientErrorCode; import uk.co.visalia.brightpearl.apiclient.http.*; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map;
return clientRequest; } private HttpRequestBase createBaseRequest(Method method, String url, String body) { if (method == Method.GET) { return new HttpGet(url); } else if (method == Method.POST) { HttpPost post = new HttpPost(url); addBody(post, body); return post; } else if (method == Method.PUT) { HttpPut put = new HttpPut(url); addBody(put, body); return put; } else if (method == Method.DELETE) { return new HttpDelete(url); } else if (method == Method.OPTIONS) { return new HttpOptions(url); } throw new IllegalArgumentException("HTTP method " + method + " is not supported by this client"); } private void addBody(HttpEntityEnclosingRequestBase requestBase, String body) { if (body != null) { requestBase.setEntity(new StringEntity(body, Charset.forName("UTF-8"))); } }
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/exception/BrightpearlHttpException.java // public class BrightpearlHttpException extends BrightpearlClientException { // // private final ClientErrorCode clientErrorCode; // // public BrightpearlHttpException(ClientErrorCode clientErrorCode) { // super("Brightpearl request failed: " + clientErrorCode); // this.clientErrorCode = clientErrorCode; // } // // public BrightpearlHttpException(ClientErrorCode clientErrorCode, String message) { // super("Brightpearl request failed: " + clientErrorCode + " (" + message + ")"); // this.clientErrorCode = clientErrorCode; // } // // public BrightpearlHttpException(ClientErrorCode clientErrorCode, Exception e) { // super("Brightpearl request failed: " + clientErrorCode + " (" + e.getClass().getSimpleName() + ")", e); // this.clientErrorCode = clientErrorCode; // } // // public ClientErrorCode getClientErrorCode() { // return clientErrorCode; // } // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/exception/ClientErrorCode.java // public enum ClientErrorCode { // // EMPTY_RESPONSE, // INVALID_RESPONSE_FORMAT, // INVALID_RESPONSE_TYPE, // NO_RESPONSE, // UNKNOWN_HOST, // CONNECTION_TIMEOUT, // SOCKET_ERROR, // SOCKET_TIMEOUT, // READ_TIMEOUT, // OTHER_TRANSPORT_ERROR // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/httpclient4/HttpClient4Client.java import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.NoHttpResponseException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.*; import org.apache.http.client.utils.URIBuilder; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.entity.StringEntity; import org.apache.http.util.EntityUtils; import uk.co.visalia.brightpearl.apiclient.exception.BrightpearlHttpException; import uk.co.visalia.brightpearl.apiclient.exception.ClientErrorCode; import uk.co.visalia.brightpearl.apiclient.http.*; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; return clientRequest; } private HttpRequestBase createBaseRequest(Method method, String url, String body) { if (method == Method.GET) { return new HttpGet(url); } else if (method == Method.POST) { HttpPost post = new HttpPost(url); addBody(post, body); return post; } else if (method == Method.PUT) { HttpPut put = new HttpPut(url); addBody(put, body); return put; } else if (method == Method.DELETE) { return new HttpDelete(url); } else if (method == Method.OPTIONS) { return new HttpOptions(url); } throw new IllegalArgumentException("HTTP method " + method + " is not supported by this client"); } private void addBody(HttpEntityEnclosingRequestBase requestBase, String body) { if (body != null) { requestBase.setEntity(new StringEntity(body, Charset.forName("UTF-8"))); } }
private BrightpearlHttpException resolveException(Exception e) {
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/http/httpclient4/HttpClient4Client.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/exception/BrightpearlHttpException.java // public class BrightpearlHttpException extends BrightpearlClientException { // // private final ClientErrorCode clientErrorCode; // // public BrightpearlHttpException(ClientErrorCode clientErrorCode) { // super("Brightpearl request failed: " + clientErrorCode); // this.clientErrorCode = clientErrorCode; // } // // public BrightpearlHttpException(ClientErrorCode clientErrorCode, String message) { // super("Brightpearl request failed: " + clientErrorCode + " (" + message + ")"); // this.clientErrorCode = clientErrorCode; // } // // public BrightpearlHttpException(ClientErrorCode clientErrorCode, Exception e) { // super("Brightpearl request failed: " + clientErrorCode + " (" + e.getClass().getSimpleName() + ")", e); // this.clientErrorCode = clientErrorCode; // } // // public ClientErrorCode getClientErrorCode() { // return clientErrorCode; // } // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/exception/ClientErrorCode.java // public enum ClientErrorCode { // // EMPTY_RESPONSE, // INVALID_RESPONSE_FORMAT, // INVALID_RESPONSE_TYPE, // NO_RESPONSE, // UNKNOWN_HOST, // CONNECTION_TIMEOUT, // SOCKET_ERROR, // SOCKET_TIMEOUT, // READ_TIMEOUT, // OTHER_TRANSPORT_ERROR // // }
import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.NoHttpResponseException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.*; import org.apache.http.client.utils.URIBuilder; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.entity.StringEntity; import org.apache.http.util.EntityUtils; import uk.co.visalia.brightpearl.apiclient.exception.BrightpearlHttpException; import uk.co.visalia.brightpearl.apiclient.exception.ClientErrorCode; import uk.co.visalia.brightpearl.apiclient.http.*; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map;
} private HttpRequestBase createBaseRequest(Method method, String url, String body) { if (method == Method.GET) { return new HttpGet(url); } else if (method == Method.POST) { HttpPost post = new HttpPost(url); addBody(post, body); return post; } else if (method == Method.PUT) { HttpPut put = new HttpPut(url); addBody(put, body); return put; } else if (method == Method.DELETE) { return new HttpDelete(url); } else if (method == Method.OPTIONS) { return new HttpOptions(url); } throw new IllegalArgumentException("HTTP method " + method + " is not supported by this client"); } private void addBody(HttpEntityEnclosingRequestBase requestBase, String body) { if (body != null) { requestBase.setEntity(new StringEntity(body, Charset.forName("UTF-8"))); } } private BrightpearlHttpException resolveException(Exception e) { if (e instanceof ConnectTimeoutException) {
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/exception/BrightpearlHttpException.java // public class BrightpearlHttpException extends BrightpearlClientException { // // private final ClientErrorCode clientErrorCode; // // public BrightpearlHttpException(ClientErrorCode clientErrorCode) { // super("Brightpearl request failed: " + clientErrorCode); // this.clientErrorCode = clientErrorCode; // } // // public BrightpearlHttpException(ClientErrorCode clientErrorCode, String message) { // super("Brightpearl request failed: " + clientErrorCode + " (" + message + ")"); // this.clientErrorCode = clientErrorCode; // } // // public BrightpearlHttpException(ClientErrorCode clientErrorCode, Exception e) { // super("Brightpearl request failed: " + clientErrorCode + " (" + e.getClass().getSimpleName() + ")", e); // this.clientErrorCode = clientErrorCode; // } // // public ClientErrorCode getClientErrorCode() { // return clientErrorCode; // } // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/exception/ClientErrorCode.java // public enum ClientErrorCode { // // EMPTY_RESPONSE, // INVALID_RESPONSE_FORMAT, // INVALID_RESPONSE_TYPE, // NO_RESPONSE, // UNKNOWN_HOST, // CONNECTION_TIMEOUT, // SOCKET_ERROR, // SOCKET_TIMEOUT, // READ_TIMEOUT, // OTHER_TRANSPORT_ERROR // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/http/httpclient4/HttpClient4Client.java import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.NoHttpResponseException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.*; import org.apache.http.client.utils.URIBuilder; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.entity.StringEntity; import org.apache.http.util.EntityUtils; import uk.co.visalia.brightpearl.apiclient.exception.BrightpearlHttpException; import uk.co.visalia.brightpearl.apiclient.exception.ClientErrorCode; import uk.co.visalia.brightpearl.apiclient.http.*; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; } private HttpRequestBase createBaseRequest(Method method, String url, String body) { if (method == Method.GET) { return new HttpGet(url); } else if (method == Method.POST) { HttpPost post = new HttpPost(url); addBody(post, body); return post; } else if (method == Method.PUT) { HttpPut put = new HttpPut(url); addBody(put, body); return put; } else if (method == Method.DELETE) { return new HttpDelete(url); } else if (method == Method.OPTIONS) { return new HttpOptions(url); } throw new IllegalArgumentException("HTTP method " + method + " is not supported by this client"); } private void addBody(HttpEntityEnclosingRequestBase requestBase, String body) { if (body != null) { requestBase.setEntity(new StringEntity(body, Charset.forName("UTF-8"))); } } private BrightpearlHttpException resolveException(Exception e) { if (e instanceof ConnectTimeoutException) {
throw new BrightpearlHttpException(ClientErrorCode.CONNECTION_TIMEOUT, e);
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/auth/PrivateAppAuthorisation.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java // public final class Account implements Serializable { // // private final Datacenter datacenter; // // private final String accountCode; // // /** // * Construct an account instance. // * @param datacenter the datacenter that hosts the account. // * @param accountCode the customer account code. // */ // public Account(Datacenter datacenter, String accountCode) { // if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) { // throw new IllegalArgumentException("A datacenter name and host must be provided"); // } // if (StringUtils.isBlank(accountCode)) { // throw new IllegalArgumentException("An account code must be provided"); // } // this.datacenter = datacenter; // this.accountCode = accountCode; // } // // /** // * Returns the datacenter // * @return the datacenter that hosts the account. // */ // public Datacenter getDatacenter() { // return datacenter; // } // // public String getAccountCode() { // return accountCode; // } // // @Override // public String toString() { // return "Account{" + // "datacenter=" + datacenter + // ", accountCode='" + accountCode + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Account account = (Account) o; // if (accountCode != null ? !accountCode.equals(account.accountCode) : account.accountCode != null) return false; // if (datacenter != null ? !datacenter.equals(account.datacenter) : account.datacenter != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = datacenter != null ? datacenter.hashCode() : 0; // result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); // return result; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.account.Account; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.util.Collections; import java.util.HashMap; import java.util.Map;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.auth; /** * Contains the details of a private app, the Brightpearl customer account to which it belongs, and either an account token * or a staff token for authorisation of calls to this account. */ public final class PrivateAppAuthorisation implements AppAuthorisation { private final PrivateAppIdentity appIdentity; private final String accountToken; private final String staffToken; private PrivateAppAuthorisation(PrivateAppIdentity appIdentity, String accountToken, String staffToken) { this.appIdentity = appIdentity; this.accountToken = accountToken; this.staffToken = staffToken; } /** * Create account authorisation details for a private (own account) system-to-system call using the account token * generated for a private app. * @param appIdentity Details of the private app including the Brightpearl customer account it belongs to. * @param accountToken Account token generated for the private app. * @return authorisation details. */ public static PrivateAppAuthorisation system(PrivateAppIdentity appIdentity, String accountToken) { if (appIdentity == null) { throw new IllegalArgumentException("App identity is required"); }
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java // public final class Account implements Serializable { // // private final Datacenter datacenter; // // private final String accountCode; // // /** // * Construct an account instance. // * @param datacenter the datacenter that hosts the account. // * @param accountCode the customer account code. // */ // public Account(Datacenter datacenter, String accountCode) { // if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) { // throw new IllegalArgumentException("A datacenter name and host must be provided"); // } // if (StringUtils.isBlank(accountCode)) { // throw new IllegalArgumentException("An account code must be provided"); // } // this.datacenter = datacenter; // this.accountCode = accountCode; // } // // /** // * Returns the datacenter // * @return the datacenter that hosts the account. // */ // public Datacenter getDatacenter() { // return datacenter; // } // // public String getAccountCode() { // return accountCode; // } // // @Override // public String toString() { // return "Account{" + // "datacenter=" + datacenter + // ", accountCode='" + accountCode + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Account account = (Account) o; // if (accountCode != null ? !accountCode.equals(account.accountCode) : account.accountCode != null) return false; // if (datacenter != null ? !datacenter.equals(account.datacenter) : account.datacenter != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = datacenter != null ? datacenter.hashCode() : 0; // result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); // return result; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/auth/PrivateAppAuthorisation.java import uk.co.visalia.brightpearl.apiclient.account.Account; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.util.Collections; import java.util.HashMap; import java.util.Map; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.auth; /** * Contains the details of a private app, the Brightpearl customer account to which it belongs, and either an account token * or a staff token for authorisation of calls to this account. */ public final class PrivateAppAuthorisation implements AppAuthorisation { private final PrivateAppIdentity appIdentity; private final String accountToken; private final String staffToken; private PrivateAppAuthorisation(PrivateAppIdentity appIdentity, String accountToken, String staffToken) { this.appIdentity = appIdentity; this.accountToken = accountToken; this.staffToken = staffToken; } /** * Create account authorisation details for a private (own account) system-to-system call using the account token * generated for a private app. * @param appIdentity Details of the private app including the Brightpearl customer account it belongs to. * @param accountToken Account token generated for the private app. * @return authorisation details. */ public static PrivateAppAuthorisation system(PrivateAppIdentity appIdentity, String accountToken) { if (appIdentity == null) { throw new IllegalArgumentException("App identity is required"); }
if (StringUtils.isBlank(accountToken)) { throw new IllegalArgumentException("Account token is required"); }
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/auth/PrivateAppAuthorisation.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java // public final class Account implements Serializable { // // private final Datacenter datacenter; // // private final String accountCode; // // /** // * Construct an account instance. // * @param datacenter the datacenter that hosts the account. // * @param accountCode the customer account code. // */ // public Account(Datacenter datacenter, String accountCode) { // if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) { // throw new IllegalArgumentException("A datacenter name and host must be provided"); // } // if (StringUtils.isBlank(accountCode)) { // throw new IllegalArgumentException("An account code must be provided"); // } // this.datacenter = datacenter; // this.accountCode = accountCode; // } // // /** // * Returns the datacenter // * @return the datacenter that hosts the account. // */ // public Datacenter getDatacenter() { // return datacenter; // } // // public String getAccountCode() { // return accountCode; // } // // @Override // public String toString() { // return "Account{" + // "datacenter=" + datacenter + // ", accountCode='" + accountCode + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Account account = (Account) o; // if (accountCode != null ? !accountCode.equals(account.accountCode) : account.accountCode != null) return false; // if (datacenter != null ? !datacenter.equals(account.datacenter) : account.datacenter != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = datacenter != null ? datacenter.hashCode() : 0; // result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); // return result; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.account.Account; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.util.Collections; import java.util.HashMap; import java.util.Map;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.auth; /** * Contains the details of a private app, the Brightpearl customer account to which it belongs, and either an account token * or a staff token for authorisation of calls to this account. */ public final class PrivateAppAuthorisation implements AppAuthorisation { private final PrivateAppIdentity appIdentity; private final String accountToken; private final String staffToken; private PrivateAppAuthorisation(PrivateAppIdentity appIdentity, String accountToken, String staffToken) { this.appIdentity = appIdentity; this.accountToken = accountToken; this.staffToken = staffToken; } /** * Create account authorisation details for a private (own account) system-to-system call using the account token * generated for a private app. * @param appIdentity Details of the private app including the Brightpearl customer account it belongs to. * @param accountToken Account token generated for the private app. * @return authorisation details. */ public static PrivateAppAuthorisation system(PrivateAppIdentity appIdentity, String accountToken) { if (appIdentity == null) { throw new IllegalArgumentException("App identity is required"); } if (StringUtils.isBlank(accountToken)) { throw new IllegalArgumentException("Account token is required"); } return new PrivateAppAuthorisation(appIdentity, accountToken, null); } /** * Create account authorisation details for a staff authorised API call for a private app. * @param appIdentity Details of the private app including the Brightpearl customer account it belongs to. * @param staffToken Account token, signed or unsigned. If it is unsigned, the developer secret is required. * @return authorisation details. */ public static PrivateAppAuthorisation staff(PrivateAppIdentity appIdentity, String staffToken) { if (appIdentity == null) { throw new IllegalArgumentException("App identity is required"); } if (StringUtils.isBlank(staffToken)) { throw new IllegalArgumentException("Staff token is required"); } return new PrivateAppAuthorisation(appIdentity, null, staffToken); } public PrivateAppIdentity getAppIdentity() { return appIdentity; } public String getAccountToken() { return accountToken; } public String getStaffToken() { return staffToken; } @Override
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java // public final class Account implements Serializable { // // private final Datacenter datacenter; // // private final String accountCode; // // /** // * Construct an account instance. // * @param datacenter the datacenter that hosts the account. // * @param accountCode the customer account code. // */ // public Account(Datacenter datacenter, String accountCode) { // if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) { // throw new IllegalArgumentException("A datacenter name and host must be provided"); // } // if (StringUtils.isBlank(accountCode)) { // throw new IllegalArgumentException("An account code must be provided"); // } // this.datacenter = datacenter; // this.accountCode = accountCode; // } // // /** // * Returns the datacenter // * @return the datacenter that hosts the account. // */ // public Datacenter getDatacenter() { // return datacenter; // } // // public String getAccountCode() { // return accountCode; // } // // @Override // public String toString() { // return "Account{" + // "datacenter=" + datacenter + // ", accountCode='" + accountCode + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Account account = (Account) o; // if (accountCode != null ? !accountCode.equals(account.accountCode) : account.accountCode != null) return false; // if (datacenter != null ? !datacenter.equals(account.datacenter) : account.datacenter != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = datacenter != null ? datacenter.hashCode() : 0; // result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); // return result; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/auth/PrivateAppAuthorisation.java import uk.co.visalia.brightpearl.apiclient.account.Account; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.util.Collections; import java.util.HashMap; import java.util.Map; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.auth; /** * Contains the details of a private app, the Brightpearl customer account to which it belongs, and either an account token * or a staff token for authorisation of calls to this account. */ public final class PrivateAppAuthorisation implements AppAuthorisation { private final PrivateAppIdentity appIdentity; private final String accountToken; private final String staffToken; private PrivateAppAuthorisation(PrivateAppIdentity appIdentity, String accountToken, String staffToken) { this.appIdentity = appIdentity; this.accountToken = accountToken; this.staffToken = staffToken; } /** * Create account authorisation details for a private (own account) system-to-system call using the account token * generated for a private app. * @param appIdentity Details of the private app including the Brightpearl customer account it belongs to. * @param accountToken Account token generated for the private app. * @return authorisation details. */ public static PrivateAppAuthorisation system(PrivateAppIdentity appIdentity, String accountToken) { if (appIdentity == null) { throw new IllegalArgumentException("App identity is required"); } if (StringUtils.isBlank(accountToken)) { throw new IllegalArgumentException("Account token is required"); } return new PrivateAppAuthorisation(appIdentity, accountToken, null); } /** * Create account authorisation details for a staff authorised API call for a private app. * @param appIdentity Details of the private app including the Brightpearl customer account it belongs to. * @param staffToken Account token, signed or unsigned. If it is unsigned, the developer secret is required. * @return authorisation details. */ public static PrivateAppAuthorisation staff(PrivateAppIdentity appIdentity, String staffToken) { if (appIdentity == null) { throw new IllegalArgumentException("App identity is required"); } if (StringUtils.isBlank(staffToken)) { throw new IllegalArgumentException("Staff token is required"); } return new PrivateAppAuthorisation(appIdentity, null, staffToken); } public PrivateAppIdentity getAppIdentity() { return appIdentity; } public String getAccountToken() { return accountToken; } public String getStaffToken() { return staffToken; } @Override
public Account getAccount() {
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/account/Datacenter.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.io.Serializable;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.account; /** * Represents the datacenter on which an account is hosted. Static instances are included representing the known datacenters, * and a customer datacenter can be created if required. To find the datacenter for an account, see the link below. * * @see <a href="http://www.brightpearl.com/developer/latest/concept/uri-syntax.html">http://www.brightpearl.com/developer/latest/concept/uri-syntax.html</a> */ public final class Datacenter implements Serializable { /** * Datacenter EU1 (GMT, CET). */ public static final Datacenter EU1 = new Datacenter("EU1", "https://ws-eu1.brightpearl.com"); /** * Datacenter EU2 (for accounts where admin domain is https://secure2.thisispearl.com). */ public static final Datacenter EU2 = new Datacenter("EU2", "https://ws-eu2.brightpearl.com"); /** * Datacenter USE (EST, CST). */ public static final Datacenter USE = new Datacenter("USE", "https://ws-use.brightpearl.com"); /** * Datacenter USW (PST, MST). */ public static final Datacenter USW = new Datacenter("USW", "https://ws-usw.brightpearl.com"); private static final Datacenter[] DATACENTERS = { EU1, EU2, USE, USW }; private final String name; private final String host; /** * Create a custom datacenter. * @param name User friendly name of the datacenter. This is used for logging only; any non-null value is valid. * @param host Scheme and host name of the datacenter, e.g. https://ws-usw.brightpearl.com. Trailing slashes should be omitted. */ public Datacenter(String name, String host) {
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Datacenter.java import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.io.Serializable; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.account; /** * Represents the datacenter on which an account is hosted. Static instances are included representing the known datacenters, * and a customer datacenter can be created if required. To find the datacenter for an account, see the link below. * * @see <a href="http://www.brightpearl.com/developer/latest/concept/uri-syntax.html">http://www.brightpearl.com/developer/latest/concept/uri-syntax.html</a> */ public final class Datacenter implements Serializable { /** * Datacenter EU1 (GMT, CET). */ public static final Datacenter EU1 = new Datacenter("EU1", "https://ws-eu1.brightpearl.com"); /** * Datacenter EU2 (for accounts where admin domain is https://secure2.thisispearl.com). */ public static final Datacenter EU2 = new Datacenter("EU2", "https://ws-eu2.brightpearl.com"); /** * Datacenter USE (EST, CST). */ public static final Datacenter USE = new Datacenter("USE", "https://ws-use.brightpearl.com"); /** * Datacenter USW (PST, MST). */ public static final Datacenter USW = new Datacenter("USW", "https://ws-usw.brightpearl.com"); private static final Datacenter[] DATACENTERS = { EU1, EU2, USE, USW }; private final String name; private final String host; /** * Create a custom datacenter. * @param name User friendly name of the datacenter. This is used for logging only; any non-null value is valid. * @param host Scheme and host name of the datacenter, e.g. https://ws-usw.brightpearl.com. Trailing slashes should be omitted. */ public Datacenter(String name, String host) {
if (StringUtils.isBlank(name)) {
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.io.Serializable;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.account; /** * Defines a Brightpearl customer account. There is no way to look up the datacenter that contains a unique account code, * so it must be configured. */ public final class Account implements Serializable { private final Datacenter datacenter; private final String accountCode; /** * Construct an account instance. * @param datacenter the datacenter that hosts the account. * @param accountCode the customer account code. */ public Account(Datacenter datacenter, String accountCode) {
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.io.Serializable; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.account; /** * Defines a Brightpearl customer account. There is no way to look up the datacenter that contains a unique account code, * so it must be configured. */ public final class Account implements Serializable { private final Datacenter datacenter; private final String accountCode; /** * Construct an account instance. * @param datacenter the datacenter that hosts the account. * @param accountCode the customer account code. */ public Account(Datacenter datacenter, String accountCode) {
if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) {
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/auth/PublicAppAuthorisation.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java // public final class Account implements Serializable { // // private final Datacenter datacenter; // // private final String accountCode; // // /** // * Construct an account instance. // * @param datacenter the datacenter that hosts the account. // * @param accountCode the customer account code. // */ // public Account(Datacenter datacenter, String accountCode) { // if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) { // throw new IllegalArgumentException("A datacenter name and host must be provided"); // } // if (StringUtils.isBlank(accountCode)) { // throw new IllegalArgumentException("An account code must be provided"); // } // this.datacenter = datacenter; // this.accountCode = accountCode; // } // // /** // * Returns the datacenter // * @return the datacenter that hosts the account. // */ // public Datacenter getDatacenter() { // return datacenter; // } // // public String getAccountCode() { // return accountCode; // } // // @Override // public String toString() { // return "Account{" + // "datacenter=" + datacenter + // ", accountCode='" + accountCode + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Account account = (Account) o; // if (accountCode != null ? !accountCode.equals(account.accountCode) : account.accountCode != null) return false; // if (datacenter != null ? !datacenter.equals(account.datacenter) : account.datacenter != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = datacenter != null ? datacenter.hashCode() : 0; // result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); // return result; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/Base64.java // public class Base64 { // // private static final String base64code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // // private static byte[] zeroPad(int length, byte[] bytes) { // byte[] padded = new byte[length]; // System.arraycopy(bytes, 0, padded, 0, bytes.length); // return padded; // } // // public static String encode(String string) { // String encoded = ""; // byte[] stringArray; // try { // stringArray = string.getBytes("UTF-8"); // } catch (Exception ignored) { // stringArray = string.getBytes(); // } // int paddingCount = (3 - (stringArray.length % 3)) % 3; // stringArray = zeroPad(stringArray.length + paddingCount, stringArray); // for (int i = 0; i < stringArray.length; i += 3) { // int j = ((stringArray[i] & 0xff) << 16) + // ((stringArray[i + 1] & 0xff) << 8) + // (stringArray[i + 2] & 0xff); // encoded = encoded + base64code.charAt((j >> 18) & 0x3f) + // base64code.charAt((j >> 12) & 0x3f) + // base64code.charAt((j >> 6) & 0x3f) + // base64code.charAt(j & 0x3f); // } // return encoded.substring(0, encoded.length() - paddingCount) + "==".substring(0, paddingCount); // } // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.account.Account; import uk.co.visalia.brightpearl.apiclient.util.Base64; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.util.Collections; import java.util.HashMap; import java.util.Map;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.auth; /** * Contains the details of an app, a Brightpearl customer account and the tokens required to verify the app's permission * to make API calls to the account. */ public final class PublicAppAuthorisation implements AppAuthorisation { private final PublicAppIdentity appIdentity;
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java // public final class Account implements Serializable { // // private final Datacenter datacenter; // // private final String accountCode; // // /** // * Construct an account instance. // * @param datacenter the datacenter that hosts the account. // * @param accountCode the customer account code. // */ // public Account(Datacenter datacenter, String accountCode) { // if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) { // throw new IllegalArgumentException("A datacenter name and host must be provided"); // } // if (StringUtils.isBlank(accountCode)) { // throw new IllegalArgumentException("An account code must be provided"); // } // this.datacenter = datacenter; // this.accountCode = accountCode; // } // // /** // * Returns the datacenter // * @return the datacenter that hosts the account. // */ // public Datacenter getDatacenter() { // return datacenter; // } // // public String getAccountCode() { // return accountCode; // } // // @Override // public String toString() { // return "Account{" + // "datacenter=" + datacenter + // ", accountCode='" + accountCode + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Account account = (Account) o; // if (accountCode != null ? !accountCode.equals(account.accountCode) : account.accountCode != null) return false; // if (datacenter != null ? !datacenter.equals(account.datacenter) : account.datacenter != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = datacenter != null ? datacenter.hashCode() : 0; // result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); // return result; // } // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/Base64.java // public class Base64 { // // private static final String base64code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // // private static byte[] zeroPad(int length, byte[] bytes) { // byte[] padded = new byte[length]; // System.arraycopy(bytes, 0, padded, 0, bytes.length); // return padded; // } // // public static String encode(String string) { // String encoded = ""; // byte[] stringArray; // try { // stringArray = string.getBytes("UTF-8"); // } catch (Exception ignored) { // stringArray = string.getBytes(); // } // int paddingCount = (3 - (stringArray.length % 3)) % 3; // stringArray = zeroPad(stringArray.length + paddingCount, stringArray); // for (int i = 0; i < stringArray.length; i += 3) { // int j = ((stringArray[i] & 0xff) << 16) + // ((stringArray[i + 1] & 0xff) << 8) + // (stringArray[i + 2] & 0xff); // encoded = encoded + base64code.charAt((j >> 18) & 0x3f) + // base64code.charAt((j >> 12) & 0x3f) + // base64code.charAt((j >> 6) & 0x3f) + // base64code.charAt(j & 0x3f); // } // return encoded.substring(0, encoded.length() - paddingCount) + "==".substring(0, paddingCount); // } // // } // // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/auth/PublicAppAuthorisation.java import uk.co.visalia.brightpearl.apiclient.account.Account; import uk.co.visalia.brightpearl.apiclient.util.Base64; import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.util.Collections; import java.util.HashMap; import java.util.Map; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.auth; /** * Contains the details of an app, a Brightpearl customer account and the tokens required to verify the app's permission * to make API calls to the account. */ public final class PublicAppAuthorisation implements AppAuthorisation { private final PublicAppIdentity appIdentity;
private final Account account;
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/account/UserCredentials.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // }
import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.io.Serializable;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.account; /** * Contains the email address and password of an account user with API access to be used for authentication. */ public final class UserCredentials implements Serializable { private final String emailAddress; private final String password; /** * Create an immutable credentials instance with a supplied email address and password. * @param emailAddress Email address of a user account within a Brightpearl customer account. Must be a non-empty string. * @param password The user's password. Must be a non-empty string. */ public UserCredentials(String emailAddress, String password) {
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/util/StringUtils.java // public final class StringUtils { // // private StringUtils() { } // // public static boolean isEmpty(String string) { // return string == null || string.length() == 0; // } // // public static boolean isNotEmpty(String string) { // return !isEmpty(string); // } // // public static boolean isBlank(String string) { // return string == null || string.trim().length() == 0; // } // // public static boolean isNotBlank(String string) { // return !isBlank(string); // } // // public static boolean equals(String lhs, String rhs) { // if ((lhs == null) != (rhs == null)) { // return false; // } else if (lhs == null && rhs == null) { // return true; // } else { // return lhs.equals(rhs); // } // } // // public static String join(Collection<String> strings, String separator) { // StringBuilder builder = new StringBuilder(); // for (String string : strings) { // if (builder.length() > 0) { // builder.append(separator); // } // builder.append(string); // } // return builder.toString(); // } // // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/UserCredentials.java import uk.co.visalia.brightpearl.apiclient.util.StringUtils; import java.io.Serializable; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.account; /** * Contains the email address and password of an account user with API access to be used for authentication. */ public final class UserCredentials implements Serializable { private final String emailAddress; private final String password; /** * Create an immutable credentials instance with a supplied email address and password. * @param emailAddress Email address of a user account within a Brightpearl customer account. Must be a non-empty string. * @param password The user's password. Must be a non-empty string. */ public UserCredentials(String emailAddress, String password) {
if (StringUtils.isBlank(emailAddress)) {
davemorrissey/brightpearl-api-client-java
src/main/java/uk/co/visalia/brightpearl/apiclient/ratelimit/ConstantWaitRateLimiter.java
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java // public final class Account implements Serializable { // // private final Datacenter datacenter; // // private final String accountCode; // // /** // * Construct an account instance. // * @param datacenter the datacenter that hosts the account. // * @param accountCode the customer account code. // */ // public Account(Datacenter datacenter, String accountCode) { // if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) { // throw new IllegalArgumentException("A datacenter name and host must be provided"); // } // if (StringUtils.isBlank(accountCode)) { // throw new IllegalArgumentException("An account code must be provided"); // } // this.datacenter = datacenter; // this.accountCode = accountCode; // } // // /** // * Returns the datacenter // * @return the datacenter that hosts the account. // */ // public Datacenter getDatacenter() { // return datacenter; // } // // public String getAccountCode() { // return accountCode; // } // // @Override // public String toString() { // return "Account{" + // "datacenter=" + datacenter + // ", accountCode='" + accountCode + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Account account = (Account) o; // if (accountCode != null ? !accountCode.equals(account.accountCode) : account.accountCode != null) return false; // if (datacenter != null ? !datacenter.equals(account.datacenter) : account.datacenter != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = datacenter != null ? datacenter.hashCode() : 0; // result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); // return result; // } // }
import uk.co.visalia.brightpearl.apiclient.account.Account; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit;
/* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.ratelimit; /** * <p> * A very basic implementation of {@link RateLimiter} that will reduce the * throughput of requests by pausing for the minimum period required to ensure the cap is not exceeded. By default this * is 300 ms. Each calling thread is blocked until the request may be sent, so this is not suitable for use as a queue. * </p><p> * If there is more than one server making requests to the same Brightpearl account, this approach will only be effective * if this class is configured with a 1/n share of the request cap, which increases latency for all requests, however a * distributed tracking approach may be more appropriate. * </p><p> * This class is intended to prevent hitting the request cap for an account, and its behaviour is not affected by an * account unexpectedly being throttled. * </p> */ public class ConstantWaitRateLimiter implements RateLimiter { private final int cap; private final int period; private final TimeUnit periodUnit; private final long minimumPeriod; private final ConcurrentHashMap<String, Long> lastRequestMap; /** * Construct a constant wait rate limiter with the default settings, limiting requests to 200 per minute. This is * suitable for a single node system. */ public ConstantWaitRateLimiter() { this(200, 1, TimeUnit.MINUTES); } /** * Construct a constant wait limiter with a custom rate limit. Avoid low rates as this will cause high latency * during busy periods. * @param cap The number of requests allowed in the given period. * @param period The period of time. * @param periodUnit Unit of the period of time. */ public ConstantWaitRateLimiter(int cap, int period, TimeUnit periodUnit) { this.cap = cap; this.period = period; this.periodUnit = periodUnit; this.lastRequestMap = new ConcurrentHashMap<String, Long>(); this.minimumPeriod = minimumPeriod(); } /** * Called before a request is made, this sleeps for the minimum amount of time that must be left to ensure no more * than the maximum number of requests are made in the configured period. With default configuration, the maximum * wait will be 300ms to give a rate of 200 per minute. If more than 300ms has passed since the previous request, * the wait will be zero. * @param account The account a request is about to be sent to. */ @Override
// Path: src/main/java/uk/co/visalia/brightpearl/apiclient/account/Account.java // public final class Account implements Serializable { // // private final Datacenter datacenter; // // private final String accountCode; // // /** // * Construct an account instance. // * @param datacenter the datacenter that hosts the account. // * @param accountCode the customer account code. // */ // public Account(Datacenter datacenter, String accountCode) { // if (datacenter == null || StringUtils.isBlank(datacenter.getHost()) || StringUtils.isBlank(datacenter.getName())) { // throw new IllegalArgumentException("A datacenter name and host must be provided"); // } // if (StringUtils.isBlank(accountCode)) { // throw new IllegalArgumentException("An account code must be provided"); // } // this.datacenter = datacenter; // this.accountCode = accountCode; // } // // /** // * Returns the datacenter // * @return the datacenter that hosts the account. // */ // public Datacenter getDatacenter() { // return datacenter; // } // // public String getAccountCode() { // return accountCode; // } // // @Override // public String toString() { // return "Account{" + // "datacenter=" + datacenter + // ", accountCode='" + accountCode + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Account account = (Account) o; // if (accountCode != null ? !accountCode.equals(account.accountCode) : account.accountCode != null) return false; // if (datacenter != null ? !datacenter.equals(account.datacenter) : account.datacenter != null) return false; // return true; // } // // @Override // public int hashCode() { // int result = datacenter != null ? datacenter.hashCode() : 0; // result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); // return result; // } // } // Path: src/main/java/uk/co/visalia/brightpearl/apiclient/ratelimit/ConstantWaitRateLimiter.java import uk.co.visalia.brightpearl.apiclient.account.Account; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; /* * Copyright 2014 David Morrissey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.visalia.brightpearl.apiclient.ratelimit; /** * <p> * A very basic implementation of {@link RateLimiter} that will reduce the * throughput of requests by pausing for the minimum period required to ensure the cap is not exceeded. By default this * is 300 ms. Each calling thread is blocked until the request may be sent, so this is not suitable for use as a queue. * </p><p> * If there is more than one server making requests to the same Brightpearl account, this approach will only be effective * if this class is configured with a 1/n share of the request cap, which increases latency for all requests, however a * distributed tracking approach may be more appropriate. * </p><p> * This class is intended to prevent hitting the request cap for an account, and its behaviour is not affected by an * account unexpectedly being throttled. * </p> */ public class ConstantWaitRateLimiter implements RateLimiter { private final int cap; private final int period; private final TimeUnit periodUnit; private final long minimumPeriod; private final ConcurrentHashMap<String, Long> lastRequestMap; /** * Construct a constant wait rate limiter with the default settings, limiting requests to 200 per minute. This is * suitable for a single node system. */ public ConstantWaitRateLimiter() { this(200, 1, TimeUnit.MINUTES); } /** * Construct a constant wait limiter with a custom rate limit. Avoid low rates as this will cause high latency * during busy periods. * @param cap The number of requests allowed in the given period. * @param period The period of time. * @param periodUnit Unit of the period of time. */ public ConstantWaitRateLimiter(int cap, int period, TimeUnit periodUnit) { this.cap = cap; this.period = period; this.periodUnit = periodUnit; this.lastRequestMap = new ConcurrentHashMap<String, Long>(); this.minimumPeriod = minimumPeriod(); } /** * Called before a request is made, this sleeps for the minimum amount of time that must be left to ensure no more * than the maximum number of requests are made in the configured period. With default configuration, the maximum * wait will be 300ms to give a rate of 200 per minute. If more than 300ms has passed since the previous request, * the wait will be zero. * @param account The account a request is about to be sent to. */ @Override
public void rateLimit(Account account) {
dubrousky/CMaker
src/cmake/filetypes/CMakeFile.java
// Path: src/cmake/global/CMakeLanguage.java // public class CMakeLanguage extends Language { // public static final CMakeLanguage INSTANCE = new CMakeLanguage(); // // private CMakeLanguage() { // super("CMake"); // } // }
import cmake.global.CMakeLanguage; import com.intellij.extapi.psi.PsiFileBase; import com.intellij.openapi.fileTypes.FileType; import com.intellij.psi.FileViewProvider; import org.jetbrains.annotations.NotNull; import javax.swing.*;
package cmake.filetypes; /** * CMake language file type used as root of the * cmake psi file elements holder. */ public class CMakeFile extends PsiFileBase{ public static CMakeFile create(@NotNull FileViewProvider viewProvider) { return new CMakeFile(viewProvider); } protected CMakeFile(@NotNull FileViewProvider viewProvider) {
// Path: src/cmake/global/CMakeLanguage.java // public class CMakeLanguage extends Language { // public static final CMakeLanguage INSTANCE = new CMakeLanguage(); // // private CMakeLanguage() { // super("CMake"); // } // } // Path: src/cmake/filetypes/CMakeFile.java import cmake.global.CMakeLanguage; import com.intellij.extapi.psi.PsiFileBase; import com.intellij.openapi.fileTypes.FileType; import com.intellij.psi.FileViewProvider; import org.jetbrains.annotations.NotNull; import javax.swing.*; package cmake.filetypes; /** * CMake language file type used as root of the * cmake psi file elements holder. */ public class CMakeFile extends PsiFileBase{ public static CMakeFile create(@NotNull FileViewProvider viewProvider) { return new CMakeFile(viewProvider); } protected CMakeFile(@NotNull FileViewProvider viewProvider) {
super(viewProvider, CMakeLanguage.INSTANCE);
dubrousky/CMaker
src/cmake/highlights/CMakeHighlighter.java
// Path: src/cmake/parsing/CMakeLexerAdapter.java // public class CMakeLexerAdapter extends FlexAdapter { // public CMakeLexerAdapter() { // super(new _CMakeLexer((Reader) null)); // } // }
import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.lexer.Lexer; import com.intellij.openapi.editor.DefaultLanguageHighlighterColors; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighterBase; import com.intellij.openapi.util.Pair; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import gnu.trove.THashMap; import org.jetbrains.annotations.NotNull; import cmake.psi.CMakeTypes; import cmake.parsing.CMakeLexerAdapter; import java.util.Map;
package cmake.highlights; /** * This is a simple highlighter based on the lexer output. * Annotator provides the psi-aware highlights. */ public class CMakeHighlighter extends SyntaxHighlighterBase { private static final Map<IElementType, TextAttributesKey> keys1; private static final Map<IElementType, TextAttributesKey> keys2; @NotNull @Override public Lexer getHighlightingLexer() {
// Path: src/cmake/parsing/CMakeLexerAdapter.java // public class CMakeLexerAdapter extends FlexAdapter { // public CMakeLexerAdapter() { // super(new _CMakeLexer((Reader) null)); // } // } // Path: src/cmake/highlights/CMakeHighlighter.java import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.lexer.Lexer; import com.intellij.openapi.editor.DefaultLanguageHighlighterColors; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighterBase; import com.intellij.openapi.util.Pair; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import gnu.trove.THashMap; import org.jetbrains.annotations.NotNull; import cmake.psi.CMakeTypes; import cmake.parsing.CMakeLexerAdapter; import java.util.Map; package cmake.highlights; /** * This is a simple highlighter based on the lexer output. * Annotator provides the psi-aware highlights. */ public class CMakeHighlighter extends SyntaxHighlighterBase { private static final Map<IElementType, TextAttributesKey> keys1; private static final Map<IElementType, TextAttributesKey> keys2; @NotNull @Override public Lexer getHighlightingLexer() {
return new CMakeLexerAdapter();
dubrousky/CMaker
src/cmake/global/CMakeLineProvider.java
// Path: src/cmake/icons/CMakeIcons.java // public class CMakeIcons { // public static final Icon FILE = IconLoader.getIcon("/icons/cmake.png"); // public static final Icon MACRO = IconLoader.getIcon("/icons/hashtag.png"); // public static final Icon FUN = IconLoader.getIcon("/icons/fun.jpg"); // public static final Icon LOOP = IconLoader.getIcon("/icons/loop.png"); // }
import cmake.icons.CMakeIcons; import cmake.psi.CMakeFbegin; import cmake.psi.CMakeLoop; import cmake.psi.CMakeMbegin; import com.intellij.codeInsight.daemon.RelatedItemLineMarkerInfo; import com.intellij.codeInsight.daemon.RelatedItemLineMarkerProvider; import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import java.util.Collection;
package cmake.global; /** * Provides gutter icons for function/macro/loop * elements. */ public class CMakeLineProvider extends RelatedItemLineMarkerProvider { @Override protected void collectNavigationMarkers(@NotNull PsiElement element, Collection<? super RelatedItemLineMarkerInfo> result) { if (element instanceof CMakeFbegin) { NavigationGutterIconBuilder<PsiElement> builder =
// Path: src/cmake/icons/CMakeIcons.java // public class CMakeIcons { // public static final Icon FILE = IconLoader.getIcon("/icons/cmake.png"); // public static final Icon MACRO = IconLoader.getIcon("/icons/hashtag.png"); // public static final Icon FUN = IconLoader.getIcon("/icons/fun.jpg"); // public static final Icon LOOP = IconLoader.getIcon("/icons/loop.png"); // } // Path: src/cmake/global/CMakeLineProvider.java import cmake.icons.CMakeIcons; import cmake.psi.CMakeFbegin; import cmake.psi.CMakeLoop; import cmake.psi.CMakeMbegin; import com.intellij.codeInsight.daemon.RelatedItemLineMarkerInfo; import com.intellij.codeInsight.daemon.RelatedItemLineMarkerProvider; import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import java.util.Collection; package cmake.global; /** * Provides gutter icons for function/macro/loop * elements. */ public class CMakeLineProvider extends RelatedItemLineMarkerProvider { @Override protected void collectNavigationMarkers(@NotNull PsiElement element, Collection<? super RelatedItemLineMarkerInfo> result) { if (element instanceof CMakeFbegin) { NavigationGutterIconBuilder<PsiElement> builder =
NavigationGutterIconBuilder.create(CMakeIcons.FUN).
dubrousky/CMaker
src/cmake/project/CMakeModuleType.java
// Path: src/cmake/icons/CMakeIcons.java // public class CMakeIcons { // public static final Icon FILE = IconLoader.getIcon("/icons/cmake.png"); // public static final Icon MACRO = IconLoader.getIcon("/icons/hashtag.png"); // public static final Icon FUN = IconLoader.getIcon("/icons/fun.jpg"); // public static final Icon LOOP = IconLoader.getIcon("/icons/loop.png"); // }
import cmake.icons.CMakeIcons; import com.intellij.ide.util.projectWizard.ModuleBuilder; import com.intellij.openapi.module.ModuleType; import org.jetbrains.annotations.NotNull; import javax.swing.*;
package cmake.project; /** * Created by alex on 1/16/15. */ public class CMakeModuleType extends ModuleType { public static final CMakeModuleType LIBRARY = new CMakeModuleType(); public static final CMakeModuleType APPLICATION = new CMakeModuleType(); protected CMakeModuleType( ) { super("CMAKE"); } @NotNull @Override public ModuleBuilder createModuleBuilder() { return new CMakeModuleBuilder(); } @NotNull @Override public String getName() { return "CMAKE"; } @NotNull @Override public String getDescription() { return "TODO: add description"; } @Override public Icon getBigIcon() {
// Path: src/cmake/icons/CMakeIcons.java // public class CMakeIcons { // public static final Icon FILE = IconLoader.getIcon("/icons/cmake.png"); // public static final Icon MACRO = IconLoader.getIcon("/icons/hashtag.png"); // public static final Icon FUN = IconLoader.getIcon("/icons/fun.jpg"); // public static final Icon LOOP = IconLoader.getIcon("/icons/loop.png"); // } // Path: src/cmake/project/CMakeModuleType.java import cmake.icons.CMakeIcons; import com.intellij.ide.util.projectWizard.ModuleBuilder; import com.intellij.openapi.module.ModuleType; import org.jetbrains.annotations.NotNull; import javax.swing.*; package cmake.project; /** * Created by alex on 1/16/15. */ public class CMakeModuleType extends ModuleType { public static final CMakeModuleType LIBRARY = new CMakeModuleType(); public static final CMakeModuleType APPLICATION = new CMakeModuleType(); protected CMakeModuleType( ) { super("CMAKE"); } @NotNull @Override public ModuleBuilder createModuleBuilder() { return new CMakeModuleBuilder(); } @NotNull @Override public String getName() { return "CMAKE"; } @NotNull @Override public String getDescription() { return "TODO: add description"; } @Override public Icon getBigIcon() {
return CMakeIcons.FILE;
dubrousky/CMaker
src/cmake/global/CMakeFindUsagesProvider.java
// Path: src/cmake/psi/CMakeNamedElement.java // public interface CMakeNamedElement extends PsiNameIdentifierOwner { // // } // // Path: src/cmake/parsing/CMakeLexerAdapter.java // public class CMakeLexerAdapter extends FlexAdapter { // public CMakeLexerAdapter() { // super(new _CMakeLexer((Reader) null)); // } // }
import cmake.psi.CMakeCommandName; import cmake.psi.CMakeNamedElement; import com.intellij.lang.HelpID; import com.intellij.lang.cacheBuilder.DefaultWordsScanner; import com.intellij.lang.cacheBuilder.WordOccurrence; import com.intellij.lang.cacheBuilder.WordsScanner; import com.intellij.lang.findUsages.FindUsagesProvider; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.ElementDescriptionUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import com.intellij.usageView.UsageViewLongNameLocation; import com.intellij.usageView.UsageViewNodeTextLocation; import com.intellij.usageView.UsageViewTypeLocation; import com.intellij.util.Processor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import cmake.psi.CMakeTypes; import cmake.parsing.CMakeLexerAdapter;
package cmake.global; /** * Created by alex on 12/30/14. */ public class CMakeFindUsagesProvider implements FindUsagesProvider { private static final DefaultWordsScanner WORDS_SCANNER =
// Path: src/cmake/psi/CMakeNamedElement.java // public interface CMakeNamedElement extends PsiNameIdentifierOwner { // // } // // Path: src/cmake/parsing/CMakeLexerAdapter.java // public class CMakeLexerAdapter extends FlexAdapter { // public CMakeLexerAdapter() { // super(new _CMakeLexer((Reader) null)); // } // } // Path: src/cmake/global/CMakeFindUsagesProvider.java import cmake.psi.CMakeCommandName; import cmake.psi.CMakeNamedElement; import com.intellij.lang.HelpID; import com.intellij.lang.cacheBuilder.DefaultWordsScanner; import com.intellij.lang.cacheBuilder.WordOccurrence; import com.intellij.lang.cacheBuilder.WordsScanner; import com.intellij.lang.findUsages.FindUsagesProvider; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.ElementDescriptionUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import com.intellij.usageView.UsageViewLongNameLocation; import com.intellij.usageView.UsageViewNodeTextLocation; import com.intellij.usageView.UsageViewTypeLocation; import com.intellij.util.Processor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import cmake.psi.CMakeTypes; import cmake.parsing.CMakeLexerAdapter; package cmake.global; /** * Created by alex on 12/30/14. */ public class CMakeFindUsagesProvider implements FindUsagesProvider { private static final DefaultWordsScanner WORDS_SCANNER =
new DefaultWordsScanner(new CMakeLexerAdapter(),
dubrousky/CMaker
src/cmake/global/CMakeFoldingBuilder.java
// Path: src/cmake/filetypes/CMakeFile.java // public class CMakeFile extends PsiFileBase{ // public static CMakeFile create(@NotNull FileViewProvider viewProvider) { // return new CMakeFile(viewProvider); // } // protected CMakeFile(@NotNull FileViewProvider viewProvider) { // super(viewProvider, CMakeLanguage.INSTANCE); // } // // @NotNull // @Override // public FileType getFileType() { // return CMakeFileType.INSTANCE; // } // // @Override // public String toString() { // return "CMake"; // } // // @Override // public Icon getIcon(int flags) { // return super.getIcon(flags); // } // }
import cmake.filetypes.CMakeFile; import com.intellij.lang.ASTNode; import com.intellij.lang.folding.FoldingBuilderEx; import com.intellij.lang.folding.FoldingDescriptor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.search.PsiElementProcessor; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import cmake.psi.CMakeTypes; import java.util.List;
package cmake.global; /** * Created by alex on 12/31/14. */ public class CMakeFoldingBuilder extends FoldingBuilderEx implements DumbAware { @NotNull @Override public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement root, @NotNull Document document, boolean quick) {
// Path: src/cmake/filetypes/CMakeFile.java // public class CMakeFile extends PsiFileBase{ // public static CMakeFile create(@NotNull FileViewProvider viewProvider) { // return new CMakeFile(viewProvider); // } // protected CMakeFile(@NotNull FileViewProvider viewProvider) { // super(viewProvider, CMakeLanguage.INSTANCE); // } // // @NotNull // @Override // public FileType getFileType() { // return CMakeFileType.INSTANCE; // } // // @Override // public String toString() { // return "CMake"; // } // // @Override // public Icon getIcon(int flags) { // return super.getIcon(flags); // } // } // Path: src/cmake/global/CMakeFoldingBuilder.java import cmake.filetypes.CMakeFile; import com.intellij.lang.ASTNode; import com.intellij.lang.folding.FoldingBuilderEx; import com.intellij.lang.folding.FoldingDescriptor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.search.PsiElementProcessor; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import cmake.psi.CMakeTypes; import java.util.List; package cmake.global; /** * Created by alex on 12/31/14. */ public class CMakeFoldingBuilder extends FoldingBuilderEx implements DumbAware { @NotNull @Override public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement root, @NotNull Document document, boolean quick) {
if (!(root instanceof CMakeFile)) return FoldingDescriptor.EMPTY;
dubrousky/CMaker
src/cmake/format/CMakeCodeStyleConfigurable.java
// Path: src/cmake/global/CMakeLanguage.java // public class CMakeLanguage extends Language { // public static final CMakeLanguage INSTANCE = new CMakeLanguage(); // // private CMakeLanguage() { // super("CMake"); // } // }
import cmake.global.CMakeLanguage; import com.intellij.application.options.CodeStyleAbstractConfigurable; import com.intellij.application.options.CodeStyleAbstractPanel; import com.intellij.application.options.TabbedLanguageCodeStylePanel; import com.intellij.lang.Language; import com.intellij.psi.codeStyle.CodeStyleSettings; import org.jetbrains.annotations.Nullable;
package cmake.format; /** * Created by alex on 1/13/15. */ public class CMakeCodeStyleConfigurable extends CodeStyleAbstractConfigurable { public CMakeCodeStyleConfigurable(CodeStyleSettings settings, CodeStyleSettings cloneSettings) { super(settings, cloneSettings, "CMake"); } @Override protected CodeStyleAbstractPanel createPanel(CodeStyleSettings codeStyleSettings) { return new CMakeCodeStylePanel(getCurrentSettings(), codeStyleSettings); } @Nullable @Override public String getHelpTopic() { return null; } class CMakeCodeStylePanel extends TabbedLanguageCodeStylePanel { protected CMakeCodeStylePanel(CodeStyleSettings currentSettings, CodeStyleSettings settings) {
// Path: src/cmake/global/CMakeLanguage.java // public class CMakeLanguage extends Language { // public static final CMakeLanguage INSTANCE = new CMakeLanguage(); // // private CMakeLanguage() { // super("CMake"); // } // } // Path: src/cmake/format/CMakeCodeStyleConfigurable.java import cmake.global.CMakeLanguage; import com.intellij.application.options.CodeStyleAbstractConfigurable; import com.intellij.application.options.CodeStyleAbstractPanel; import com.intellij.application.options.TabbedLanguageCodeStylePanel; import com.intellij.lang.Language; import com.intellij.psi.codeStyle.CodeStyleSettings; import org.jetbrains.annotations.Nullable; package cmake.format; /** * Created by alex on 1/13/15. */ public class CMakeCodeStyleConfigurable extends CodeStyleAbstractConfigurable { public CMakeCodeStyleConfigurable(CodeStyleSettings settings, CodeStyleSettings cloneSettings) { super(settings, cloneSettings, "CMake"); } @Override protected CodeStyleAbstractPanel createPanel(CodeStyleSettings codeStyleSettings) { return new CMakeCodeStylePanel(getCurrentSettings(), codeStyleSettings); } @Nullable @Override public String getHelpTopic() { return null; } class CMakeCodeStylePanel extends TabbedLanguageCodeStylePanel { protected CMakeCodeStylePanel(CodeStyleSettings currentSettings, CodeStyleSettings settings) {
super(CMakeLanguage.INSTANCE, currentSettings, settings);
dubrousky/CMaker
src/cmake/psi/CMakeElementType.java
// Path: src/cmake/global/CMakeLanguage.java // public class CMakeLanguage extends Language { // public static final CMakeLanguage INSTANCE = new CMakeLanguage(); // // private CMakeLanguage() { // super("CMake"); // } // }
import com.intellij.psi.tree.IElementType; import cmake.global.CMakeLanguage; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull;
package cmake.psi; /** * Created by alex on 12/22/14. */ public class CMakeElementType extends IElementType { public CMakeElementType(@NotNull @NonNls String debugName) {
// Path: src/cmake/global/CMakeLanguage.java // public class CMakeLanguage extends Language { // public static final CMakeLanguage INSTANCE = new CMakeLanguage(); // // private CMakeLanguage() { // super("CMake"); // } // } // Path: src/cmake/psi/CMakeElementType.java import com.intellij.psi.tree.IElementType; import cmake.global.CMakeLanguage; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; package cmake.psi; /** * Created by alex on 12/22/14. */ public class CMakeElementType extends IElementType { public CMakeElementType(@NotNull @NonNls String debugName) {
super(debugName, CMakeLanguage.INSTANCE);
dubrousky/CMaker
src/cmake/format/CMakeLanguageCodeStyleSettingsProvider.java
// Path: src/cmake/global/CMakeLanguage.java // public class CMakeLanguage extends Language { // public static final CMakeLanguage INSTANCE = new CMakeLanguage(); // // private CMakeLanguage() { // super("CMake"); // } // }
import cmake.global.CMakeLanguage; import com.intellij.application.options.IndentOptionsEditor; import com.intellij.application.options.SmartIndentOptionsEditor; import com.intellij.lang.Language; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.psi.codeStyle.LanguageCodeStyleSettingsProvider; import org.jetbrains.annotations.NotNull;
package cmake.format; /** * Created by alex on 1/13/15. */ public class CMakeLanguageCodeStyleSettingsProvider extends LanguageCodeStyleSettingsProvider { @NotNull @Override public Language getLanguage() {
// Path: src/cmake/global/CMakeLanguage.java // public class CMakeLanguage extends Language { // public static final CMakeLanguage INSTANCE = new CMakeLanguage(); // // private CMakeLanguage() { // super("CMake"); // } // } // Path: src/cmake/format/CMakeLanguageCodeStyleSettingsProvider.java import cmake.global.CMakeLanguage; import com.intellij.application.options.IndentOptionsEditor; import com.intellij.application.options.SmartIndentOptionsEditor; import com.intellij.lang.Language; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.psi.codeStyle.LanguageCodeStyleSettingsProvider; import org.jetbrains.annotations.NotNull; package cmake.format; /** * Created by alex on 1/13/15. */ public class CMakeLanguageCodeStyleSettingsProvider extends LanguageCodeStyleSettingsProvider { @NotNull @Override public Language getLanguage() {
return CMakeLanguage.INSTANCE;
dubrousky/CMaker
src/cmake/sdk/CMakeSdkType.java
// Path: src/cmake/icons/CMakeIcons.java // public class CMakeIcons { // public static final Icon FILE = IconLoader.getIcon("/icons/cmake.png"); // public static final Icon MACRO = IconLoader.getIcon("/icons/hashtag.png"); // public static final Icon FUN = IconLoader.getIcon("/icons/fun.jpg"); // public static final Icon LOOP = IconLoader.getIcon("/icons/loop.png"); // }
import cmake.icons.CMakeIcons; import com.intellij.openapi.projectRoots.*; import com.intellij.openapi.util.SystemInfo; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.io.File;
* * @param s * @param s1 * @return */ @Override public String suggestSdkName(String s, String s1) { return null; } @Nullable @Override public AdditionalDataConfigurable createAdditionalDataConfigurable(SdkModel sdkModel, SdkModificator sdkModificator) { // TODO: WTF? return null; } @Override public String getPresentableName() { return "CMake"; } @Override public void saveAdditionalData(SdkAdditionalData sdkAdditionalData, Element element) { // TODO: save sdk data in the project } @NotNull @Override public Icon getIcon() {
// Path: src/cmake/icons/CMakeIcons.java // public class CMakeIcons { // public static final Icon FILE = IconLoader.getIcon("/icons/cmake.png"); // public static final Icon MACRO = IconLoader.getIcon("/icons/hashtag.png"); // public static final Icon FUN = IconLoader.getIcon("/icons/fun.jpg"); // public static final Icon LOOP = IconLoader.getIcon("/icons/loop.png"); // } // Path: src/cmake/sdk/CMakeSdkType.java import cmake.icons.CMakeIcons; import com.intellij.openapi.projectRoots.*; import com.intellij.openapi.util.SystemInfo; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.io.File; * * @param s * @param s1 * @return */ @Override public String suggestSdkName(String s, String s1) { return null; } @Nullable @Override public AdditionalDataConfigurable createAdditionalDataConfigurable(SdkModel sdkModel, SdkModificator sdkModificator) { // TODO: WTF? return null; } @Override public String getPresentableName() { return "CMake"; } @Override public void saveAdditionalData(SdkAdditionalData sdkAdditionalData, Element element) { // TODO: save sdk data in the project } @NotNull @Override public Icon getIcon() {
return CMakeIcons.FILE;
dubrousky/CMaker
src/cmake/project/CMakeProjectTemplatesFactory.java
// Path: src/cmake/icons/CMakeIcons.java // public class CMakeIcons { // public static final Icon FILE = IconLoader.getIcon("/icons/cmake.png"); // public static final Icon MACRO = IconLoader.getIcon("/icons/hashtag.png"); // public static final Icon FUN = IconLoader.getIcon("/icons/fun.jpg"); // public static final Icon LOOP = IconLoader.getIcon("/icons/loop.png"); // }
import cmake.icons.CMakeIcons; import com.intellij.ide.util.projectWizard.ModuleBuilder; import com.intellij.ide.util.projectWizard.WizardContext; import com.intellij.platform.ProjectTemplate; import com.intellij.platform.ProjectTemplatesFactory; import com.intellij.platform.templates.BuilderBasedTemplate; import org.jetbrains.annotations.NotNull; import javax.swing.*;
package cmake.project; /** * Created by alex on 1/15/15. */ public class CMakeProjectTemplatesFactory extends ProjectTemplatesFactory { @NotNull @Override public String[] getGroups() { return new String[] { "Executable", "Static Library", "Dynamic Library"}; } @Override public Icon getGroupIcon(String group) {
// Path: src/cmake/icons/CMakeIcons.java // public class CMakeIcons { // public static final Icon FILE = IconLoader.getIcon("/icons/cmake.png"); // public static final Icon MACRO = IconLoader.getIcon("/icons/hashtag.png"); // public static final Icon FUN = IconLoader.getIcon("/icons/fun.jpg"); // public static final Icon LOOP = IconLoader.getIcon("/icons/loop.png"); // } // Path: src/cmake/project/CMakeProjectTemplatesFactory.java import cmake.icons.CMakeIcons; import com.intellij.ide.util.projectWizard.ModuleBuilder; import com.intellij.ide.util.projectWizard.WizardContext; import com.intellij.platform.ProjectTemplate; import com.intellij.platform.ProjectTemplatesFactory; import com.intellij.platform.templates.BuilderBasedTemplate; import org.jetbrains.annotations.NotNull; import javax.swing.*; package cmake.project; /** * Created by alex on 1/15/15. */ public class CMakeProjectTemplatesFactory extends ProjectTemplatesFactory { @NotNull @Override public String[] getGroups() { return new String[] { "Executable", "Static Library", "Dynamic Library"}; } @Override public Icon getGroupIcon(String group) {
return CMakeIcons.FILE;
dubrousky/CMaker
src/cmake/parsing/CMakeParserUtilImpl.java
// Path: src/cmake/filetypes/CMakeFile.java // public class CMakeFile extends PsiFileBase{ // public static CMakeFile create(@NotNull FileViewProvider viewProvider) { // return new CMakeFile(viewProvider); // } // protected CMakeFile(@NotNull FileViewProvider viewProvider) { // super(viewProvider, CMakeLanguage.INSTANCE); // } // // @NotNull // @Override // public FileType getFileType() { // return CMakeFileType.INSTANCE; // } // // @Override // public String toString() { // return "CMake"; // } // // @Override // public Icon getIcon(int flags) { // return super.getIcon(flags); // } // } // // Path: src/cmake/filetypes/CMakeFileType.java // public class CMakeFileType extends LanguageFileType { // public static final CMakeFileType INSTANCE = new CMakeFileType(); // private static final String[] DEFAULT_EXTENSIONS = {"cmake","txt"}; // // protected CMakeFileType() { // super(CMakeLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return "CMake"; // } // // @NotNull // @Override // public String getDescription() { // return "CMake build system file"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return DEFAULT_EXTENSIONS[0]; // } // // @Nullable // @Override // public Icon getIcon() { // return CMakeIcons.FILE; // } // // @Override // public boolean isReadOnly() { // return false; // } // // @Nullable // @Override // public String getCharset(@NotNull VirtualFile virtualFile, @NotNull byte[] bytes) { // Charset charset = EncodingRegistry.getInstance().getDefaultCharsetForPropertiesFiles(virtualFile); // if (charset == null) { // charset = CharsetToolkit.getDefaultSystemCharset(); // } // return charset.name(); // } // } // // Path: src/cmake/icons/CMakeIcons.java // public class CMakeIcons { // public static final Icon FILE = IconLoader.getIcon("/icons/cmake.png"); // public static final Icon MACRO = IconLoader.getIcon("/icons/hashtag.png"); // public static final Icon FUN = IconLoader.getIcon("/icons/fun.jpg"); // public static final Icon LOOP = IconLoader.getIcon("/icons/loop.png"); // }
import cmake.filetypes.CMakeFile; import cmake.filetypes.CMakeFileType; import cmake.icons.CMakeIcons; import cmake.psi.*; import com.intellij.lang.ASTNode; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFileFactory; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiRecursiveElementWalkingVisitor; import com.intellij.psi.search.FileTypeIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.PairProcessor; import com.intellij.util.indexing.FileBasedIndex; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List;
package cmake.parsing; /** * Created by alex on 1/6/15. */ public class CMakeParserUtilImpl { public static String getName(CMakeCommandName element) { return element.getText(); } public static PsiElement setName(CMakeCommandName element, String newName) { ASTNode commandNameNode = element.getFirstChild().getNode(); // FIXME: node replacement // if (commandNameNode != null) { // CMakeCommandName newNode = CMakeTypes.Factory.createElement(new CMakeN) // ASTNode newKeyNode = property.getFirstChild().getNode(); // element.getNode().replaceChild(commandNameNode, newKeyNode); // } return element; } public static class CMakeNamedElementFactory { // public static CMake createElement(Project project, String name) { // final CMakeFile file = createFile(project, name); // TODO: use tree walker to get command name in AST // return (SimpleProperty) file.getFirstChild(); // }
// Path: src/cmake/filetypes/CMakeFile.java // public class CMakeFile extends PsiFileBase{ // public static CMakeFile create(@NotNull FileViewProvider viewProvider) { // return new CMakeFile(viewProvider); // } // protected CMakeFile(@NotNull FileViewProvider viewProvider) { // super(viewProvider, CMakeLanguage.INSTANCE); // } // // @NotNull // @Override // public FileType getFileType() { // return CMakeFileType.INSTANCE; // } // // @Override // public String toString() { // return "CMake"; // } // // @Override // public Icon getIcon(int flags) { // return super.getIcon(flags); // } // } // // Path: src/cmake/filetypes/CMakeFileType.java // public class CMakeFileType extends LanguageFileType { // public static final CMakeFileType INSTANCE = new CMakeFileType(); // private static final String[] DEFAULT_EXTENSIONS = {"cmake","txt"}; // // protected CMakeFileType() { // super(CMakeLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return "CMake"; // } // // @NotNull // @Override // public String getDescription() { // return "CMake build system file"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return DEFAULT_EXTENSIONS[0]; // } // // @Nullable // @Override // public Icon getIcon() { // return CMakeIcons.FILE; // } // // @Override // public boolean isReadOnly() { // return false; // } // // @Nullable // @Override // public String getCharset(@NotNull VirtualFile virtualFile, @NotNull byte[] bytes) { // Charset charset = EncodingRegistry.getInstance().getDefaultCharsetForPropertiesFiles(virtualFile); // if (charset == null) { // charset = CharsetToolkit.getDefaultSystemCharset(); // } // return charset.name(); // } // } // // Path: src/cmake/icons/CMakeIcons.java // public class CMakeIcons { // public static final Icon FILE = IconLoader.getIcon("/icons/cmake.png"); // public static final Icon MACRO = IconLoader.getIcon("/icons/hashtag.png"); // public static final Icon FUN = IconLoader.getIcon("/icons/fun.jpg"); // public static final Icon LOOP = IconLoader.getIcon("/icons/loop.png"); // } // Path: src/cmake/parsing/CMakeParserUtilImpl.java import cmake.filetypes.CMakeFile; import cmake.filetypes.CMakeFileType; import cmake.icons.CMakeIcons; import cmake.psi.*; import com.intellij.lang.ASTNode; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFileFactory; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiRecursiveElementWalkingVisitor; import com.intellij.psi.search.FileTypeIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.PairProcessor; import com.intellij.util.indexing.FileBasedIndex; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; package cmake.parsing; /** * Created by alex on 1/6/15. */ public class CMakeParserUtilImpl { public static String getName(CMakeCommandName element) { return element.getText(); } public static PsiElement setName(CMakeCommandName element, String newName) { ASTNode commandNameNode = element.getFirstChild().getNode(); // FIXME: node replacement // if (commandNameNode != null) { // CMakeCommandName newNode = CMakeTypes.Factory.createElement(new CMakeN) // ASTNode newKeyNode = property.getFirstChild().getNode(); // element.getNode().replaceChild(commandNameNode, newKeyNode); // } return element; } public static class CMakeNamedElementFactory { // public static CMake createElement(Project project, String name) { // final CMakeFile file = createFile(project, name); // TODO: use tree walker to get command name in AST // return (SimpleProperty) file.getFirstChild(); // }
public static CMakeFile createFile(Project project, String text) {
dubrousky/CMaker
src/cmake/parsing/CMakeParserUtilImpl.java
// Path: src/cmake/filetypes/CMakeFile.java // public class CMakeFile extends PsiFileBase{ // public static CMakeFile create(@NotNull FileViewProvider viewProvider) { // return new CMakeFile(viewProvider); // } // protected CMakeFile(@NotNull FileViewProvider viewProvider) { // super(viewProvider, CMakeLanguage.INSTANCE); // } // // @NotNull // @Override // public FileType getFileType() { // return CMakeFileType.INSTANCE; // } // // @Override // public String toString() { // return "CMake"; // } // // @Override // public Icon getIcon(int flags) { // return super.getIcon(flags); // } // } // // Path: src/cmake/filetypes/CMakeFileType.java // public class CMakeFileType extends LanguageFileType { // public static final CMakeFileType INSTANCE = new CMakeFileType(); // private static final String[] DEFAULT_EXTENSIONS = {"cmake","txt"}; // // protected CMakeFileType() { // super(CMakeLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return "CMake"; // } // // @NotNull // @Override // public String getDescription() { // return "CMake build system file"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return DEFAULT_EXTENSIONS[0]; // } // // @Nullable // @Override // public Icon getIcon() { // return CMakeIcons.FILE; // } // // @Override // public boolean isReadOnly() { // return false; // } // // @Nullable // @Override // public String getCharset(@NotNull VirtualFile virtualFile, @NotNull byte[] bytes) { // Charset charset = EncodingRegistry.getInstance().getDefaultCharsetForPropertiesFiles(virtualFile); // if (charset == null) { // charset = CharsetToolkit.getDefaultSystemCharset(); // } // return charset.name(); // } // } // // Path: src/cmake/icons/CMakeIcons.java // public class CMakeIcons { // public static final Icon FILE = IconLoader.getIcon("/icons/cmake.png"); // public static final Icon MACRO = IconLoader.getIcon("/icons/hashtag.png"); // public static final Icon FUN = IconLoader.getIcon("/icons/fun.jpg"); // public static final Icon LOOP = IconLoader.getIcon("/icons/loop.png"); // }
import cmake.filetypes.CMakeFile; import cmake.filetypes.CMakeFileType; import cmake.icons.CMakeIcons; import cmake.psi.*; import com.intellij.lang.ASTNode; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFileFactory; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiRecursiveElementWalkingVisitor; import com.intellij.psi.search.FileTypeIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.PairProcessor; import com.intellij.util.indexing.FileBasedIndex; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List;
package cmake.parsing; /** * Created by alex on 1/6/15. */ public class CMakeParserUtilImpl { public static String getName(CMakeCommandName element) { return element.getText(); } public static PsiElement setName(CMakeCommandName element, String newName) { ASTNode commandNameNode = element.getFirstChild().getNode(); // FIXME: node replacement // if (commandNameNode != null) { // CMakeCommandName newNode = CMakeTypes.Factory.createElement(new CMakeN) // ASTNode newKeyNode = property.getFirstChild().getNode(); // element.getNode().replaceChild(commandNameNode, newKeyNode); // } return element; } public static class CMakeNamedElementFactory { // public static CMake createElement(Project project, String name) { // final CMakeFile file = createFile(project, name); // TODO: use tree walker to get command name in AST // return (SimpleProperty) file.getFirstChild(); // } public static CMakeFile createFile(Project project, String text) { String name = "cmake.dummy"; return (CMakeFile) PsiFileFactory.getInstance(project).
// Path: src/cmake/filetypes/CMakeFile.java // public class CMakeFile extends PsiFileBase{ // public static CMakeFile create(@NotNull FileViewProvider viewProvider) { // return new CMakeFile(viewProvider); // } // protected CMakeFile(@NotNull FileViewProvider viewProvider) { // super(viewProvider, CMakeLanguage.INSTANCE); // } // // @NotNull // @Override // public FileType getFileType() { // return CMakeFileType.INSTANCE; // } // // @Override // public String toString() { // return "CMake"; // } // // @Override // public Icon getIcon(int flags) { // return super.getIcon(flags); // } // } // // Path: src/cmake/filetypes/CMakeFileType.java // public class CMakeFileType extends LanguageFileType { // public static final CMakeFileType INSTANCE = new CMakeFileType(); // private static final String[] DEFAULT_EXTENSIONS = {"cmake","txt"}; // // protected CMakeFileType() { // super(CMakeLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return "CMake"; // } // // @NotNull // @Override // public String getDescription() { // return "CMake build system file"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return DEFAULT_EXTENSIONS[0]; // } // // @Nullable // @Override // public Icon getIcon() { // return CMakeIcons.FILE; // } // // @Override // public boolean isReadOnly() { // return false; // } // // @Nullable // @Override // public String getCharset(@NotNull VirtualFile virtualFile, @NotNull byte[] bytes) { // Charset charset = EncodingRegistry.getInstance().getDefaultCharsetForPropertiesFiles(virtualFile); // if (charset == null) { // charset = CharsetToolkit.getDefaultSystemCharset(); // } // return charset.name(); // } // } // // Path: src/cmake/icons/CMakeIcons.java // public class CMakeIcons { // public static final Icon FILE = IconLoader.getIcon("/icons/cmake.png"); // public static final Icon MACRO = IconLoader.getIcon("/icons/hashtag.png"); // public static final Icon FUN = IconLoader.getIcon("/icons/fun.jpg"); // public static final Icon LOOP = IconLoader.getIcon("/icons/loop.png"); // } // Path: src/cmake/parsing/CMakeParserUtilImpl.java import cmake.filetypes.CMakeFile; import cmake.filetypes.CMakeFileType; import cmake.icons.CMakeIcons; import cmake.psi.*; import com.intellij.lang.ASTNode; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFileFactory; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiRecursiveElementWalkingVisitor; import com.intellij.psi.search.FileTypeIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.PairProcessor; import com.intellij.util.indexing.FileBasedIndex; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; package cmake.parsing; /** * Created by alex on 1/6/15. */ public class CMakeParserUtilImpl { public static String getName(CMakeCommandName element) { return element.getText(); } public static PsiElement setName(CMakeCommandName element, String newName) { ASTNode commandNameNode = element.getFirstChild().getNode(); // FIXME: node replacement // if (commandNameNode != null) { // CMakeCommandName newNode = CMakeTypes.Factory.createElement(new CMakeN) // ASTNode newKeyNode = property.getFirstChild().getNode(); // element.getNode().replaceChild(commandNameNode, newKeyNode); // } return element; } public static class CMakeNamedElementFactory { // public static CMake createElement(Project project, String name) { // final CMakeFile file = createFile(project, name); // TODO: use tree walker to get command name in AST // return (SimpleProperty) file.getFirstChild(); // } public static CMakeFile createFile(Project project, String text) { String name = "cmake.dummy"; return (CMakeFile) PsiFileFactory.getInstance(project).
createFileFromText(name, CMakeFileType.INSTANCE, text);
dubrousky/CMaker
src/cmake/parsing/CMakeParserUtilImpl.java
// Path: src/cmake/filetypes/CMakeFile.java // public class CMakeFile extends PsiFileBase{ // public static CMakeFile create(@NotNull FileViewProvider viewProvider) { // return new CMakeFile(viewProvider); // } // protected CMakeFile(@NotNull FileViewProvider viewProvider) { // super(viewProvider, CMakeLanguage.INSTANCE); // } // // @NotNull // @Override // public FileType getFileType() { // return CMakeFileType.INSTANCE; // } // // @Override // public String toString() { // return "CMake"; // } // // @Override // public Icon getIcon(int flags) { // return super.getIcon(flags); // } // } // // Path: src/cmake/filetypes/CMakeFileType.java // public class CMakeFileType extends LanguageFileType { // public static final CMakeFileType INSTANCE = new CMakeFileType(); // private static final String[] DEFAULT_EXTENSIONS = {"cmake","txt"}; // // protected CMakeFileType() { // super(CMakeLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return "CMake"; // } // // @NotNull // @Override // public String getDescription() { // return "CMake build system file"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return DEFAULT_EXTENSIONS[0]; // } // // @Nullable // @Override // public Icon getIcon() { // return CMakeIcons.FILE; // } // // @Override // public boolean isReadOnly() { // return false; // } // // @Nullable // @Override // public String getCharset(@NotNull VirtualFile virtualFile, @NotNull byte[] bytes) { // Charset charset = EncodingRegistry.getInstance().getDefaultCharsetForPropertiesFiles(virtualFile); // if (charset == null) { // charset = CharsetToolkit.getDefaultSystemCharset(); // } // return charset.name(); // } // } // // Path: src/cmake/icons/CMakeIcons.java // public class CMakeIcons { // public static final Icon FILE = IconLoader.getIcon("/icons/cmake.png"); // public static final Icon MACRO = IconLoader.getIcon("/icons/hashtag.png"); // public static final Icon FUN = IconLoader.getIcon("/icons/fun.jpg"); // public static final Icon LOOP = IconLoader.getIcon("/icons/loop.png"); // }
import cmake.filetypes.CMakeFile; import cmake.filetypes.CMakeFileType; import cmake.icons.CMakeIcons; import cmake.psi.*; import com.intellij.lang.ASTNode; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFileFactory; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiRecursiveElementWalkingVisitor; import com.intellij.psi.search.FileTypeIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.PairProcessor; import com.intellij.util.indexing.FileBasedIndex; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List;
stringBuilder.append(" : "); stringBuilder.append(element.getFirstChild().getText()); } else { if (args.getTextLength() > 0) { stringBuilder.append(args.getArgument().getText()) .append("("); for (PsiElement a : args.getSeparatedArgumentList()) { stringBuilder.append(" "); stringBuilder.append(a.getText()); } stringBuilder.append(" ) : ") .append(element.getFirstChild().getText()); } } return stringBuilder.toString(); } @Nullable @Override public String getLocationString() { return element.getContainingFile().getName(); } @Nullable @Override public Icon getIcon(boolean unused) { if(element.getFirstChild().getText().contains("function"))
// Path: src/cmake/filetypes/CMakeFile.java // public class CMakeFile extends PsiFileBase{ // public static CMakeFile create(@NotNull FileViewProvider viewProvider) { // return new CMakeFile(viewProvider); // } // protected CMakeFile(@NotNull FileViewProvider viewProvider) { // super(viewProvider, CMakeLanguage.INSTANCE); // } // // @NotNull // @Override // public FileType getFileType() { // return CMakeFileType.INSTANCE; // } // // @Override // public String toString() { // return "CMake"; // } // // @Override // public Icon getIcon(int flags) { // return super.getIcon(flags); // } // } // // Path: src/cmake/filetypes/CMakeFileType.java // public class CMakeFileType extends LanguageFileType { // public static final CMakeFileType INSTANCE = new CMakeFileType(); // private static final String[] DEFAULT_EXTENSIONS = {"cmake","txt"}; // // protected CMakeFileType() { // super(CMakeLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return "CMake"; // } // // @NotNull // @Override // public String getDescription() { // return "CMake build system file"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return DEFAULT_EXTENSIONS[0]; // } // // @Nullable // @Override // public Icon getIcon() { // return CMakeIcons.FILE; // } // // @Override // public boolean isReadOnly() { // return false; // } // // @Nullable // @Override // public String getCharset(@NotNull VirtualFile virtualFile, @NotNull byte[] bytes) { // Charset charset = EncodingRegistry.getInstance().getDefaultCharsetForPropertiesFiles(virtualFile); // if (charset == null) { // charset = CharsetToolkit.getDefaultSystemCharset(); // } // return charset.name(); // } // } // // Path: src/cmake/icons/CMakeIcons.java // public class CMakeIcons { // public static final Icon FILE = IconLoader.getIcon("/icons/cmake.png"); // public static final Icon MACRO = IconLoader.getIcon("/icons/hashtag.png"); // public static final Icon FUN = IconLoader.getIcon("/icons/fun.jpg"); // public static final Icon LOOP = IconLoader.getIcon("/icons/loop.png"); // } // Path: src/cmake/parsing/CMakeParserUtilImpl.java import cmake.filetypes.CMakeFile; import cmake.filetypes.CMakeFileType; import cmake.icons.CMakeIcons; import cmake.psi.*; import com.intellij.lang.ASTNode; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFileFactory; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiRecursiveElementWalkingVisitor; import com.intellij.psi.search.FileTypeIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.PairProcessor; import com.intellij.util.indexing.FileBasedIndex; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; stringBuilder.append(" : "); stringBuilder.append(element.getFirstChild().getText()); } else { if (args.getTextLength() > 0) { stringBuilder.append(args.getArgument().getText()) .append("("); for (PsiElement a : args.getSeparatedArgumentList()) { stringBuilder.append(" "); stringBuilder.append(a.getText()); } stringBuilder.append(" ) : ") .append(element.getFirstChild().getText()); } } return stringBuilder.toString(); } @Nullable @Override public String getLocationString() { return element.getContainingFile().getName(); } @Nullable @Override public Icon getIcon(boolean unused) { if(element.getFirstChild().getText().contains("function"))
return CMakeIcons.FUN;
dubrousky/CMaker
src/cmake/psi/CMakeTokenType.java
// Path: src/cmake/global/CMakeLanguage.java // public class CMakeLanguage extends Language { // public static final CMakeLanguage INSTANCE = new CMakeLanguage(); // // private CMakeLanguage() { // super("CMake"); // } // }
import com.intellij.psi.tree.IElementType; import cmake.global.CMakeLanguage;
package cmake.psi; /** * Created by alex on 1/4/15. */ public class CMakeTokenType extends IElementType { public CMakeTokenType(String debugName) {
// Path: src/cmake/global/CMakeLanguage.java // public class CMakeLanguage extends Language { // public static final CMakeLanguage INSTANCE = new CMakeLanguage(); // // private CMakeLanguage() { // super("CMake"); // } // } // Path: src/cmake/psi/CMakeTokenType.java import com.intellij.psi.tree.IElementType; import cmake.global.CMakeLanguage; package cmake.psi; /** * Created by alex on 1/4/15. */ public class CMakeTokenType extends IElementType { public CMakeTokenType(String debugName) {
super(debugName, CMakeLanguage.INSTANCE);
dubrousky/CMaker
src/cmake/icons/CMakeIconProvider.java
// Path: src/cmake/filetypes/CMakeFile.java // public class CMakeFile extends PsiFileBase{ // public static CMakeFile create(@NotNull FileViewProvider viewProvider) { // return new CMakeFile(viewProvider); // } // protected CMakeFile(@NotNull FileViewProvider viewProvider) { // super(viewProvider, CMakeLanguage.INSTANCE); // } // // @NotNull // @Override // public FileType getFileType() { // return CMakeFileType.INSTANCE; // } // // @Override // public String toString() { // return "CMake"; // } // // @Override // public Icon getIcon(int flags) { // return super.getIcon(flags); // } // }
import cmake.filetypes.CMakeFile; import com.intellij.ide.IconProvider; import com.intellij.openapi.project.DumbAware; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.Nullable; import javax.swing.*;
package cmake.icons; /** * Created by alex on 1/1/15. */ public class CMakeIconProvider extends IconProvider implements DumbAware { @Nullable @Override public Icon getIcon(PsiElement psiElement, int i) {
// Path: src/cmake/filetypes/CMakeFile.java // public class CMakeFile extends PsiFileBase{ // public static CMakeFile create(@NotNull FileViewProvider viewProvider) { // return new CMakeFile(viewProvider); // } // protected CMakeFile(@NotNull FileViewProvider viewProvider) { // super(viewProvider, CMakeLanguage.INSTANCE); // } // // @NotNull // @Override // public FileType getFileType() { // return CMakeFileType.INSTANCE; // } // // @Override // public String toString() { // return "CMake"; // } // // @Override // public Icon getIcon(int flags) { // return super.getIcon(flags); // } // } // Path: src/cmake/icons/CMakeIconProvider.java import cmake.filetypes.CMakeFile; import com.intellij.ide.IconProvider; import com.intellij.openapi.project.DumbAware; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.Nullable; import javax.swing.*; package cmake.icons; /** * Created by alex on 1/1/15. */ public class CMakeIconProvider extends IconProvider implements DumbAware { @Nullable @Override public Icon getIcon(PsiElement psiElement, int i) {
if( psiElement instanceof CMakeFile)
dubrousky/CMaker
src/cmake/highlights/settings/CMakeColorsPage.java
// Path: src/cmake/highlights/CMakeHighlighter.java // public class CMakeHighlighter extends SyntaxHighlighterBase { // private static final Map<IElementType, TextAttributesKey> keys1; // private static final Map<IElementType, TextAttributesKey> keys2; // @NotNull // @Override // public Lexer getHighlightingLexer() { // return new CMakeLexerAdapter(); // } // // // TODO: Add text highlighting attributes // // TODO: Add mapping between token and its highlighting properties // // Highlighting styles // public static final TextAttributesKey KEYWORD = TextAttributesKey.createTextAttributesKey( // "Keyword", // DefaultLanguageHighlighterColors.KEYWORD // ); // // public static final TextAttributesKey COMMENT = TextAttributesKey.createTextAttributesKey( // "Line comment", // DefaultLanguageHighlighterColors.LINE_COMMENT // ); // // public static final TextAttributesKey STRING = TextAttributesKey.createTextAttributesKey( // "Srting literal", // DefaultLanguageHighlighterColors.STRING // ); // // public static final TextAttributesKey BRACES = TextAttributesKey.createTextAttributesKey( // "CMAKE.BRACES", // DefaultLanguageHighlighterColors.BRACES // ); // // public static final TextAttributesKey BADCHAR = TextAttributesKey.createTextAttributesKey( // "CMAKE.BADCHAR", // DefaultLanguageHighlighterColors.INVALID_STRING_ESCAPE // ); // // public static final TextAttributesKey VAREXP = TextAttributesKey.createTextAttributesKey( // "CMAKE.VAREXP", // DefaultLanguageHighlighterColors.IDENTIFIER // ); // // public static final TextAttributesKey ESCAPED_CHAR = TextAttributesKey.createTextAttributesKey( // "CMAKE.ESCAPED_CHAR", // DefaultLanguageHighlighterColors.VALID_STRING_ESCAPE // ); // // public static final TextAttributesKey BLOCK_COMMENT = TextAttributesKey.createTextAttributesKey( // "CMAKE.BLOCK_COMMENT", // DefaultLanguageHighlighterColors.BLOCK_COMMENT // ); // // public static final TextAttributesKey NUMBER = TextAttributesKey.createTextAttributesKey( // "CMAKE.NUMBER", // DefaultLanguageHighlighterColors.NUMBER // ); // // public static final TextAttributesKey IDENTIFIER = TextAttributesKey.createTextAttributesKey( // "CMAKE.IDENTIFIER", // DefaultLanguageHighlighterColors.IDENTIFIER // ); // // static { // keys1 = new THashMap<IElementType, TextAttributesKey>(); // keys2 = new THashMap<IElementType, TextAttributesKey>(); // // TODO: Populate maps here // keys1.put(CMakeTypes.LINE_COMMENT, COMMENT); // keys1.put(CMakeTypes.BRACKET_COMMENT, COMMENT); // keys1.put(CMakeTypes.QUOTED_ARGUMENT, STRING); // keys1.put(CMakeTypes.LPAR, BRACES); // keys1.put(CMakeTypes.RPAR, BRACES); // keys1.put(TokenType.BAD_CHARACTER, BADCHAR); // //keys1.put(CMakeTypes.ESCAPED_CHAR,ESCAPED_CHAR); // keys1.put(CMakeTypes.BRACKET_COMMENT,BLOCK_COMMENT); // // Keywords moved to the annotator // } // @NotNull // @Override // public TextAttributesKey[] getTokenHighlights(IElementType iElementType) { // return SyntaxHighlighterBase.pack(keys1.get(iElementType), keys2.get(iElementType)); // } // //TODO: Fill the map to use it in the ColorsPage // public static final Map<TextAttributesKey, Pair<String, HighlightSeverity>> DISPLAY_NAMES = new THashMap<TextAttributesKey, Pair<String, HighlightSeverity>>(6); // // static { // DISPLAY_NAMES.put(KEYWORD, new Pair<String, HighlightSeverity>("Keyword",null)); // DISPLAY_NAMES.put(BRACES, new Pair<String, HighlightSeverity>("Braces", null)); // DISPLAY_NAMES.put(STRING, new Pair<String, HighlightSeverity>("String", null)); // DISPLAY_NAMES.put(COMMENT, new Pair<String, HighlightSeverity>("Comment", null)); // DISPLAY_NAMES.put(IDENTIFIER, new Pair<String, HighlightSeverity>("Identifier", null)); // DISPLAY_NAMES.put(BADCHAR, Pair.create("Bad Character", HighlightSeverity.WARNING)); // } // } // // Path: src/cmake/icons/CMakeIcons.java // public class CMakeIcons { // public static final Icon FILE = IconLoader.getIcon("/icons/cmake.png"); // public static final Icon MACRO = IconLoader.getIcon("/icons/hashtag.png"); // public static final Icon FUN = IconLoader.getIcon("/icons/fun.jpg"); // public static final Icon LOOP = IconLoader.getIcon("/icons/loop.png"); // }
import cmake.highlights.CMakeHighlighter; import cmake.icons.CMakeIcons; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.options.colors.AttributesDescriptor; import com.intellij.openapi.options.colors.ColorDescriptor; import com.intellij.openapi.options.colors.ColorSettingsPage; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.Map;
package cmake.highlights.settings; /** * Configures highlighting colors. Should be registered * at plugin.xml. */ public class CMakeColorsPage implements ColorSettingsPage { // Table of private static final AttributesDescriptor[] ATTRS; static {
// Path: src/cmake/highlights/CMakeHighlighter.java // public class CMakeHighlighter extends SyntaxHighlighterBase { // private static final Map<IElementType, TextAttributesKey> keys1; // private static final Map<IElementType, TextAttributesKey> keys2; // @NotNull // @Override // public Lexer getHighlightingLexer() { // return new CMakeLexerAdapter(); // } // // // TODO: Add text highlighting attributes // // TODO: Add mapping between token and its highlighting properties // // Highlighting styles // public static final TextAttributesKey KEYWORD = TextAttributesKey.createTextAttributesKey( // "Keyword", // DefaultLanguageHighlighterColors.KEYWORD // ); // // public static final TextAttributesKey COMMENT = TextAttributesKey.createTextAttributesKey( // "Line comment", // DefaultLanguageHighlighterColors.LINE_COMMENT // ); // // public static final TextAttributesKey STRING = TextAttributesKey.createTextAttributesKey( // "Srting literal", // DefaultLanguageHighlighterColors.STRING // ); // // public static final TextAttributesKey BRACES = TextAttributesKey.createTextAttributesKey( // "CMAKE.BRACES", // DefaultLanguageHighlighterColors.BRACES // ); // // public static final TextAttributesKey BADCHAR = TextAttributesKey.createTextAttributesKey( // "CMAKE.BADCHAR", // DefaultLanguageHighlighterColors.INVALID_STRING_ESCAPE // ); // // public static final TextAttributesKey VAREXP = TextAttributesKey.createTextAttributesKey( // "CMAKE.VAREXP", // DefaultLanguageHighlighterColors.IDENTIFIER // ); // // public static final TextAttributesKey ESCAPED_CHAR = TextAttributesKey.createTextAttributesKey( // "CMAKE.ESCAPED_CHAR", // DefaultLanguageHighlighterColors.VALID_STRING_ESCAPE // ); // // public static final TextAttributesKey BLOCK_COMMENT = TextAttributesKey.createTextAttributesKey( // "CMAKE.BLOCK_COMMENT", // DefaultLanguageHighlighterColors.BLOCK_COMMENT // ); // // public static final TextAttributesKey NUMBER = TextAttributesKey.createTextAttributesKey( // "CMAKE.NUMBER", // DefaultLanguageHighlighterColors.NUMBER // ); // // public static final TextAttributesKey IDENTIFIER = TextAttributesKey.createTextAttributesKey( // "CMAKE.IDENTIFIER", // DefaultLanguageHighlighterColors.IDENTIFIER // ); // // static { // keys1 = new THashMap<IElementType, TextAttributesKey>(); // keys2 = new THashMap<IElementType, TextAttributesKey>(); // // TODO: Populate maps here // keys1.put(CMakeTypes.LINE_COMMENT, COMMENT); // keys1.put(CMakeTypes.BRACKET_COMMENT, COMMENT); // keys1.put(CMakeTypes.QUOTED_ARGUMENT, STRING); // keys1.put(CMakeTypes.LPAR, BRACES); // keys1.put(CMakeTypes.RPAR, BRACES); // keys1.put(TokenType.BAD_CHARACTER, BADCHAR); // //keys1.put(CMakeTypes.ESCAPED_CHAR,ESCAPED_CHAR); // keys1.put(CMakeTypes.BRACKET_COMMENT,BLOCK_COMMENT); // // Keywords moved to the annotator // } // @NotNull // @Override // public TextAttributesKey[] getTokenHighlights(IElementType iElementType) { // return SyntaxHighlighterBase.pack(keys1.get(iElementType), keys2.get(iElementType)); // } // //TODO: Fill the map to use it in the ColorsPage // public static final Map<TextAttributesKey, Pair<String, HighlightSeverity>> DISPLAY_NAMES = new THashMap<TextAttributesKey, Pair<String, HighlightSeverity>>(6); // // static { // DISPLAY_NAMES.put(KEYWORD, new Pair<String, HighlightSeverity>("Keyword",null)); // DISPLAY_NAMES.put(BRACES, new Pair<String, HighlightSeverity>("Braces", null)); // DISPLAY_NAMES.put(STRING, new Pair<String, HighlightSeverity>("String", null)); // DISPLAY_NAMES.put(COMMENT, new Pair<String, HighlightSeverity>("Comment", null)); // DISPLAY_NAMES.put(IDENTIFIER, new Pair<String, HighlightSeverity>("Identifier", null)); // DISPLAY_NAMES.put(BADCHAR, Pair.create("Bad Character", HighlightSeverity.WARNING)); // } // } // // Path: src/cmake/icons/CMakeIcons.java // public class CMakeIcons { // public static final Icon FILE = IconLoader.getIcon("/icons/cmake.png"); // public static final Icon MACRO = IconLoader.getIcon("/icons/hashtag.png"); // public static final Icon FUN = IconLoader.getIcon("/icons/fun.jpg"); // public static final Icon LOOP = IconLoader.getIcon("/icons/loop.png"); // } // Path: src/cmake/highlights/settings/CMakeColorsPage.java import cmake.highlights.CMakeHighlighter; import cmake.icons.CMakeIcons; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.options.colors.AttributesDescriptor; import com.intellij.openapi.options.colors.ColorDescriptor; import com.intellij.openapi.options.colors.ColorSettingsPage; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.Map; package cmake.highlights.settings; /** * Configures highlighting colors. Should be registered * at plugin.xml. */ public class CMakeColorsPage implements ColorSettingsPage { // Table of private static final AttributesDescriptor[] ATTRS; static {
ATTRS = new AttributesDescriptor[CMakeHighlighter.DISPLAY_NAMES.size()];
dubrousky/CMaker
src/cmake/highlights/settings/CMakeColorsPage.java
// Path: src/cmake/highlights/CMakeHighlighter.java // public class CMakeHighlighter extends SyntaxHighlighterBase { // private static final Map<IElementType, TextAttributesKey> keys1; // private static final Map<IElementType, TextAttributesKey> keys2; // @NotNull // @Override // public Lexer getHighlightingLexer() { // return new CMakeLexerAdapter(); // } // // // TODO: Add text highlighting attributes // // TODO: Add mapping between token and its highlighting properties // // Highlighting styles // public static final TextAttributesKey KEYWORD = TextAttributesKey.createTextAttributesKey( // "Keyword", // DefaultLanguageHighlighterColors.KEYWORD // ); // // public static final TextAttributesKey COMMENT = TextAttributesKey.createTextAttributesKey( // "Line comment", // DefaultLanguageHighlighterColors.LINE_COMMENT // ); // // public static final TextAttributesKey STRING = TextAttributesKey.createTextAttributesKey( // "Srting literal", // DefaultLanguageHighlighterColors.STRING // ); // // public static final TextAttributesKey BRACES = TextAttributesKey.createTextAttributesKey( // "CMAKE.BRACES", // DefaultLanguageHighlighterColors.BRACES // ); // // public static final TextAttributesKey BADCHAR = TextAttributesKey.createTextAttributesKey( // "CMAKE.BADCHAR", // DefaultLanguageHighlighterColors.INVALID_STRING_ESCAPE // ); // // public static final TextAttributesKey VAREXP = TextAttributesKey.createTextAttributesKey( // "CMAKE.VAREXP", // DefaultLanguageHighlighterColors.IDENTIFIER // ); // // public static final TextAttributesKey ESCAPED_CHAR = TextAttributesKey.createTextAttributesKey( // "CMAKE.ESCAPED_CHAR", // DefaultLanguageHighlighterColors.VALID_STRING_ESCAPE // ); // // public static final TextAttributesKey BLOCK_COMMENT = TextAttributesKey.createTextAttributesKey( // "CMAKE.BLOCK_COMMENT", // DefaultLanguageHighlighterColors.BLOCK_COMMENT // ); // // public static final TextAttributesKey NUMBER = TextAttributesKey.createTextAttributesKey( // "CMAKE.NUMBER", // DefaultLanguageHighlighterColors.NUMBER // ); // // public static final TextAttributesKey IDENTIFIER = TextAttributesKey.createTextAttributesKey( // "CMAKE.IDENTIFIER", // DefaultLanguageHighlighterColors.IDENTIFIER // ); // // static { // keys1 = new THashMap<IElementType, TextAttributesKey>(); // keys2 = new THashMap<IElementType, TextAttributesKey>(); // // TODO: Populate maps here // keys1.put(CMakeTypes.LINE_COMMENT, COMMENT); // keys1.put(CMakeTypes.BRACKET_COMMENT, COMMENT); // keys1.put(CMakeTypes.QUOTED_ARGUMENT, STRING); // keys1.put(CMakeTypes.LPAR, BRACES); // keys1.put(CMakeTypes.RPAR, BRACES); // keys1.put(TokenType.BAD_CHARACTER, BADCHAR); // //keys1.put(CMakeTypes.ESCAPED_CHAR,ESCAPED_CHAR); // keys1.put(CMakeTypes.BRACKET_COMMENT,BLOCK_COMMENT); // // Keywords moved to the annotator // } // @NotNull // @Override // public TextAttributesKey[] getTokenHighlights(IElementType iElementType) { // return SyntaxHighlighterBase.pack(keys1.get(iElementType), keys2.get(iElementType)); // } // //TODO: Fill the map to use it in the ColorsPage // public static final Map<TextAttributesKey, Pair<String, HighlightSeverity>> DISPLAY_NAMES = new THashMap<TextAttributesKey, Pair<String, HighlightSeverity>>(6); // // static { // DISPLAY_NAMES.put(KEYWORD, new Pair<String, HighlightSeverity>("Keyword",null)); // DISPLAY_NAMES.put(BRACES, new Pair<String, HighlightSeverity>("Braces", null)); // DISPLAY_NAMES.put(STRING, new Pair<String, HighlightSeverity>("String", null)); // DISPLAY_NAMES.put(COMMENT, new Pair<String, HighlightSeverity>("Comment", null)); // DISPLAY_NAMES.put(IDENTIFIER, new Pair<String, HighlightSeverity>("Identifier", null)); // DISPLAY_NAMES.put(BADCHAR, Pair.create("Bad Character", HighlightSeverity.WARNING)); // } // } // // Path: src/cmake/icons/CMakeIcons.java // public class CMakeIcons { // public static final Icon FILE = IconLoader.getIcon("/icons/cmake.png"); // public static final Icon MACRO = IconLoader.getIcon("/icons/hashtag.png"); // public static final Icon FUN = IconLoader.getIcon("/icons/fun.jpg"); // public static final Icon LOOP = IconLoader.getIcon("/icons/loop.png"); // }
import cmake.highlights.CMakeHighlighter; import cmake.icons.CMakeIcons; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.options.colors.AttributesDescriptor; import com.intellij.openapi.options.colors.ColorDescriptor; import com.intellij.openapi.options.colors.ColorSettingsPage; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.Map;
package cmake.highlights.settings; /** * Configures highlighting colors. Should be registered * at plugin.xml. */ public class CMakeColorsPage implements ColorSettingsPage { // Table of private static final AttributesDescriptor[] ATTRS; static { ATTRS = new AttributesDescriptor[CMakeHighlighter.DISPLAY_NAMES.size()]; TextAttributesKey[] keys = CMakeHighlighter.DISPLAY_NAMES.keySet().toArray(new TextAttributesKey[0]); for (int i = 0; i < keys.length; i++) { TextAttributesKey key = keys[i]; String name = CMakeHighlighter.DISPLAY_NAMES.get(key).getFirst(); ATTRS[i] = new AttributesDescriptor(name, key); } } @NotNull public String getDisplayName() { return "CMake";//CMakeBundle.message(""); } public Icon getIcon() {
// Path: src/cmake/highlights/CMakeHighlighter.java // public class CMakeHighlighter extends SyntaxHighlighterBase { // private static final Map<IElementType, TextAttributesKey> keys1; // private static final Map<IElementType, TextAttributesKey> keys2; // @NotNull // @Override // public Lexer getHighlightingLexer() { // return new CMakeLexerAdapter(); // } // // // TODO: Add text highlighting attributes // // TODO: Add mapping between token and its highlighting properties // // Highlighting styles // public static final TextAttributesKey KEYWORD = TextAttributesKey.createTextAttributesKey( // "Keyword", // DefaultLanguageHighlighterColors.KEYWORD // ); // // public static final TextAttributesKey COMMENT = TextAttributesKey.createTextAttributesKey( // "Line comment", // DefaultLanguageHighlighterColors.LINE_COMMENT // ); // // public static final TextAttributesKey STRING = TextAttributesKey.createTextAttributesKey( // "Srting literal", // DefaultLanguageHighlighterColors.STRING // ); // // public static final TextAttributesKey BRACES = TextAttributesKey.createTextAttributesKey( // "CMAKE.BRACES", // DefaultLanguageHighlighterColors.BRACES // ); // // public static final TextAttributesKey BADCHAR = TextAttributesKey.createTextAttributesKey( // "CMAKE.BADCHAR", // DefaultLanguageHighlighterColors.INVALID_STRING_ESCAPE // ); // // public static final TextAttributesKey VAREXP = TextAttributesKey.createTextAttributesKey( // "CMAKE.VAREXP", // DefaultLanguageHighlighterColors.IDENTIFIER // ); // // public static final TextAttributesKey ESCAPED_CHAR = TextAttributesKey.createTextAttributesKey( // "CMAKE.ESCAPED_CHAR", // DefaultLanguageHighlighterColors.VALID_STRING_ESCAPE // ); // // public static final TextAttributesKey BLOCK_COMMENT = TextAttributesKey.createTextAttributesKey( // "CMAKE.BLOCK_COMMENT", // DefaultLanguageHighlighterColors.BLOCK_COMMENT // ); // // public static final TextAttributesKey NUMBER = TextAttributesKey.createTextAttributesKey( // "CMAKE.NUMBER", // DefaultLanguageHighlighterColors.NUMBER // ); // // public static final TextAttributesKey IDENTIFIER = TextAttributesKey.createTextAttributesKey( // "CMAKE.IDENTIFIER", // DefaultLanguageHighlighterColors.IDENTIFIER // ); // // static { // keys1 = new THashMap<IElementType, TextAttributesKey>(); // keys2 = new THashMap<IElementType, TextAttributesKey>(); // // TODO: Populate maps here // keys1.put(CMakeTypes.LINE_COMMENT, COMMENT); // keys1.put(CMakeTypes.BRACKET_COMMENT, COMMENT); // keys1.put(CMakeTypes.QUOTED_ARGUMENT, STRING); // keys1.put(CMakeTypes.LPAR, BRACES); // keys1.put(CMakeTypes.RPAR, BRACES); // keys1.put(TokenType.BAD_CHARACTER, BADCHAR); // //keys1.put(CMakeTypes.ESCAPED_CHAR,ESCAPED_CHAR); // keys1.put(CMakeTypes.BRACKET_COMMENT,BLOCK_COMMENT); // // Keywords moved to the annotator // } // @NotNull // @Override // public TextAttributesKey[] getTokenHighlights(IElementType iElementType) { // return SyntaxHighlighterBase.pack(keys1.get(iElementType), keys2.get(iElementType)); // } // //TODO: Fill the map to use it in the ColorsPage // public static final Map<TextAttributesKey, Pair<String, HighlightSeverity>> DISPLAY_NAMES = new THashMap<TextAttributesKey, Pair<String, HighlightSeverity>>(6); // // static { // DISPLAY_NAMES.put(KEYWORD, new Pair<String, HighlightSeverity>("Keyword",null)); // DISPLAY_NAMES.put(BRACES, new Pair<String, HighlightSeverity>("Braces", null)); // DISPLAY_NAMES.put(STRING, new Pair<String, HighlightSeverity>("String", null)); // DISPLAY_NAMES.put(COMMENT, new Pair<String, HighlightSeverity>("Comment", null)); // DISPLAY_NAMES.put(IDENTIFIER, new Pair<String, HighlightSeverity>("Identifier", null)); // DISPLAY_NAMES.put(BADCHAR, Pair.create("Bad Character", HighlightSeverity.WARNING)); // } // } // // Path: src/cmake/icons/CMakeIcons.java // public class CMakeIcons { // public static final Icon FILE = IconLoader.getIcon("/icons/cmake.png"); // public static final Icon MACRO = IconLoader.getIcon("/icons/hashtag.png"); // public static final Icon FUN = IconLoader.getIcon("/icons/fun.jpg"); // public static final Icon LOOP = IconLoader.getIcon("/icons/loop.png"); // } // Path: src/cmake/highlights/settings/CMakeColorsPage.java import cmake.highlights.CMakeHighlighter; import cmake.icons.CMakeIcons; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.options.colors.AttributesDescriptor; import com.intellij.openapi.options.colors.ColorDescriptor; import com.intellij.openapi.options.colors.ColorSettingsPage; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.Map; package cmake.highlights.settings; /** * Configures highlighting colors. Should be registered * at plugin.xml. */ public class CMakeColorsPage implements ColorSettingsPage { // Table of private static final AttributesDescriptor[] ATTRS; static { ATTRS = new AttributesDescriptor[CMakeHighlighter.DISPLAY_NAMES.size()]; TextAttributesKey[] keys = CMakeHighlighter.DISPLAY_NAMES.keySet().toArray(new TextAttributesKey[0]); for (int i = 0; i < keys.length; i++) { TextAttributesKey key = keys[i]; String name = CMakeHighlighter.DISPLAY_NAMES.get(key).getFirst(); ATTRS[i] = new AttributesDescriptor(name, key); } } @NotNull public String getDisplayName() { return "CMake";//CMakeBundle.message(""); } public Icon getIcon() {
return CMakeIcons.FILE;
dubrousky/CMaker
src/cmake/parsing/CMakeParserDefinition.java
// Path: src/cmake/filetypes/CMakeFile.java // public class CMakeFile extends PsiFileBase{ // public static CMakeFile create(@NotNull FileViewProvider viewProvider) { // return new CMakeFile(viewProvider); // } // protected CMakeFile(@NotNull FileViewProvider viewProvider) { // super(viewProvider, CMakeLanguage.INSTANCE); // } // // @NotNull // @Override // public FileType getFileType() { // return CMakeFileType.INSTANCE; // } // // @Override // public String toString() { // return "CMake"; // } // // @Override // public Icon getIcon(int flags) { // return super.getIcon(flags); // } // } // // Path: src/cmake/global/CMakeLanguage.java // public class CMakeLanguage extends Language { // public static final CMakeLanguage INSTANCE = new CMakeLanguage(); // // private CMakeLanguage() { // super("CMake"); // } // }
import cmake.filetypes.CMakeFile; import cmake.global.CMakeLanguage; import com.intellij.lang.ASTNode; import com.intellij.lang.Language; import com.intellij.lang.ParserDefinition; import com.intellij.lang.PsiParser; import com.intellij.lexer.Lexer; import com.intellij.openapi.project.Project; import com.intellij.psi.FileViewProvider; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IFileElementType; import com.intellij.psi.tree.TokenSet; import org.jetbrains.annotations.NotNull; import cmake.psi.CMakeTypes;
package cmake.parsing; /** * Created by alex on 12/21/14. */ public class CMakeParserDefinition implements ParserDefinition { public static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE); public static final TokenSet COMMENTS = TokenSet.create(CMakeTypes.LINE_COMMENT, CMakeTypes.BRACKET_COMMENT); public static final TokenSet STRINGS = TokenSet.create(CMakeTypes.QUOTED_ARGUMENT);
// Path: src/cmake/filetypes/CMakeFile.java // public class CMakeFile extends PsiFileBase{ // public static CMakeFile create(@NotNull FileViewProvider viewProvider) { // return new CMakeFile(viewProvider); // } // protected CMakeFile(@NotNull FileViewProvider viewProvider) { // super(viewProvider, CMakeLanguage.INSTANCE); // } // // @NotNull // @Override // public FileType getFileType() { // return CMakeFileType.INSTANCE; // } // // @Override // public String toString() { // return "CMake"; // } // // @Override // public Icon getIcon(int flags) { // return super.getIcon(flags); // } // } // // Path: src/cmake/global/CMakeLanguage.java // public class CMakeLanguage extends Language { // public static final CMakeLanguage INSTANCE = new CMakeLanguage(); // // private CMakeLanguage() { // super("CMake"); // } // } // Path: src/cmake/parsing/CMakeParserDefinition.java import cmake.filetypes.CMakeFile; import cmake.global.CMakeLanguage; import com.intellij.lang.ASTNode; import com.intellij.lang.Language; import com.intellij.lang.ParserDefinition; import com.intellij.lang.PsiParser; import com.intellij.lexer.Lexer; import com.intellij.openapi.project.Project; import com.intellij.psi.FileViewProvider; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IFileElementType; import com.intellij.psi.tree.TokenSet; import org.jetbrains.annotations.NotNull; import cmake.psi.CMakeTypes; package cmake.parsing; /** * Created by alex on 12/21/14. */ public class CMakeParserDefinition implements ParserDefinition { public static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE); public static final TokenSet COMMENTS = TokenSet.create(CMakeTypes.LINE_COMMENT, CMakeTypes.BRACKET_COMMENT); public static final TokenSet STRINGS = TokenSet.create(CMakeTypes.QUOTED_ARGUMENT);
public static final IFileElementType FILE = new IFileElementType(Language.<CMakeLanguage>findInstance(CMakeLanguage.class));
dubrousky/CMaker
src/cmake/parsing/CMakeParserDefinition.java
// Path: src/cmake/filetypes/CMakeFile.java // public class CMakeFile extends PsiFileBase{ // public static CMakeFile create(@NotNull FileViewProvider viewProvider) { // return new CMakeFile(viewProvider); // } // protected CMakeFile(@NotNull FileViewProvider viewProvider) { // super(viewProvider, CMakeLanguage.INSTANCE); // } // // @NotNull // @Override // public FileType getFileType() { // return CMakeFileType.INSTANCE; // } // // @Override // public String toString() { // return "CMake"; // } // // @Override // public Icon getIcon(int flags) { // return super.getIcon(flags); // } // } // // Path: src/cmake/global/CMakeLanguage.java // public class CMakeLanguage extends Language { // public static final CMakeLanguage INSTANCE = new CMakeLanguage(); // // private CMakeLanguage() { // super("CMake"); // } // }
import cmake.filetypes.CMakeFile; import cmake.global.CMakeLanguage; import com.intellij.lang.ASTNode; import com.intellij.lang.Language; import com.intellij.lang.ParserDefinition; import com.intellij.lang.PsiParser; import com.intellij.lexer.Lexer; import com.intellij.openapi.project.Project; import com.intellij.psi.FileViewProvider; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IFileElementType; import com.intellij.psi.tree.TokenSet; import org.jetbrains.annotations.NotNull; import cmake.psi.CMakeTypes;
} @Override public IFileElementType getFileNodeType() { return FILE; } @NotNull @Override public TokenSet getWhitespaceTokens() { return WHITE_SPACES; } @NotNull @Override public TokenSet getCommentTokens() { return COMMENTS; } @NotNull @Override public TokenSet getStringLiteralElements() { return STRINGS; } @NotNull @Override public PsiElement createElement(ASTNode astNode) { return CMakeTypes.Factory.createElement(astNode); } @Override public PsiFile createFile(FileViewProvider fileViewProvider) {
// Path: src/cmake/filetypes/CMakeFile.java // public class CMakeFile extends PsiFileBase{ // public static CMakeFile create(@NotNull FileViewProvider viewProvider) { // return new CMakeFile(viewProvider); // } // protected CMakeFile(@NotNull FileViewProvider viewProvider) { // super(viewProvider, CMakeLanguage.INSTANCE); // } // // @NotNull // @Override // public FileType getFileType() { // return CMakeFileType.INSTANCE; // } // // @Override // public String toString() { // return "CMake"; // } // // @Override // public Icon getIcon(int flags) { // return super.getIcon(flags); // } // } // // Path: src/cmake/global/CMakeLanguage.java // public class CMakeLanguage extends Language { // public static final CMakeLanguage INSTANCE = new CMakeLanguage(); // // private CMakeLanguage() { // super("CMake"); // } // } // Path: src/cmake/parsing/CMakeParserDefinition.java import cmake.filetypes.CMakeFile; import cmake.global.CMakeLanguage; import com.intellij.lang.ASTNode; import com.intellij.lang.Language; import com.intellij.lang.ParserDefinition; import com.intellij.lang.PsiParser; import com.intellij.lexer.Lexer; import com.intellij.openapi.project.Project; import com.intellij.psi.FileViewProvider; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IFileElementType; import com.intellij.psi.tree.TokenSet; import org.jetbrains.annotations.NotNull; import cmake.psi.CMakeTypes; } @Override public IFileElementType getFileNodeType() { return FILE; } @NotNull @Override public TokenSet getWhitespaceTokens() { return WHITE_SPACES; } @NotNull @Override public TokenSet getCommentTokens() { return COMMENTS; } @NotNull @Override public TokenSet getStringLiteralElements() { return STRINGS; } @NotNull @Override public PsiElement createElement(ASTNode astNode) { return CMakeTypes.Factory.createElement(astNode); } @Override public PsiFile createFile(FileViewProvider fileViewProvider) {
return CMakeFile.create(fileViewProvider);