JUnit Test Case for stmt if (obj == null) return false; - object

I am trying to write a JUnit Test Case for the below Java Code:
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof Crop))
return false;
Crop other = (Crop) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
}
The Test case i wote is below:
public void testCrop() {
Crop cp = new Crop();
Object obj = false;
cp.equals(obj);
assertSame(obj instanceof Crop, false);
}
public void testCrop1() {
Crop other = (Crop) obj;
// assertSame(other.equals(obj), true);
assertEquals(obj, other);
}
The test case for instanceof is working fine, but while checking if(obj == null) return false; the test case is failing:

You could use assertFalse
public void testEqualsNullIsFalse() {
Crop crop = new Crop();
assertFalse(crop.equals(null));
}

Test case has to be something like
Crop cp = new Crop();
Object obj = null;
bool expected = false;
assertEquals(expected,cp.equals(obj));
NB if you are trying do something like the as operator, have a look at this
how to emulate as operator in Java

Related

Acumatica Pagination Implementation for Processing Screen does not returns all applicable values

I have tried to implement pagination for my custom processing screen but not getting all the required values in the grid.
If I am using below code, where I did not implemented pagination and directly using BQL in the foreach() loop for getting the records, I am getting all the applicable values.
public PXCancel<KNPIPaymentFilter> cancel;
public PXFilter<KNPIPaymentFilter> KNPIFilter;
[PXFilterable]
public PXFilteredProcessing<SOOrder, KNPIPaymentFilter> KNPIProcessOrders;
protected bool _PayMethodChanged = false;
protected bool _PayActionChanged = false;
public virtual void KNPIPaymentFilter_RowUpdated(PXCache sender, PXRowUpdatedEventArgs e)
{
_PayMethodChanged = !sender.ObjectsEqual<KNPIPaymentFilter.paymentMethodID>(e.Row, e.OldRow);
_PayActionChanged = !sender.ObjectsEqual<KNPIPaymentFilter.payPalInvAction>(e.Row, e.OldRow);
}
public IEnumerable kNPIProcessOrders()
{
if (_PayMethodChanged || _PayActionChanged)
KNPIProcessOrders.Cache.Clear();
KNPIPaymentFilter filter = PXCache<KNPIPaymentFilter>.CreateCopy(KNPIFilter.Current);
if (filter.PayPalInvAction == KNPIConstants.SL)
yield break;
foreach (SOOrder order in PXSelect<SOOrder, Where<SOOrder.orderType, Equal<SOOrderTypeConstants.salesOrder>, And<SOOrder.paymentMethodID, Equal<Required<KNPIPaymentFilter.paymentMethodID>>,
And<SOOrder.status, NotEqual<SOOrderStatus.completed>>>>>.Select(this, this.KNPIFilter.Current.PaymentMethodID))
{
KNPIPayments PayPalPayment = new PXSelect<KNPIPayments, Where<KNPIPayments.acmOrderNbr, Equal<Required<KNPIPayments.acmOrderNbr>>,
And<KNPIPayments.acmOrderType, Equal<Required<KNPIPayments.acmOrderType>>>>, OrderBy<Desc<KNPIPayments.lineNbr>>>
(this).SelectWindowed(0, 1, order.OrderNbr, order.OrderType);
if (filter.PayPalInvAction == KNPIConstants.RE)
{
if (PayPalPayment == null || (PayPalPayment != null && PayPalPayment.PayPalInvoiceStatus == KNPIConstants.CANCELLED))
yield return order;
}
else if (filter.PayPalInvAction == KNPIConstants.CH)
{
if (PayPalPayment != null && PayPalPayment.PayPalInvoiceStatus == KNPIConstants.SENT)
yield return order;
}
}
KNPIProcessOrders.Cache.IsDirty = false;
}
But when I am implementing pagination logic like below, I am not getting any of the record in the grid. I have debugged the code and found out in the list object it is loading only 19 records initially but after that other records are not at all loading in the object.
public PXCancel<KNPIPaymentFilter> cancel;
public PXFilter<KNPIPaymentFilter> KNPIFilter;
[PXFilterable]
public PXFilteredProcessing<SOOrder, KNPIPaymentFilter> KNPIProcessOrders;
protected bool _PayMethodChanged = false;
protected bool _PayActionChanged = false;
public virtual void KNPIPaymentFilter_RowUpdated(PXCache sender, PXRowUpdatedEventArgs e)
{
_PayMethodChanged = !sender.ObjectsEqual<KNPIPaymentFilter.paymentMethodID>(e.Row, e.OldRow);
_PayActionChanged = !sender.ObjectsEqual<KNPIPaymentFilter.payPalInvAction>(e.Row, e.OldRow);
}
public IEnumerable kNPIProcessOrders()
{
if (_PayMethodChanged || _PayActionChanged)
KNPIProcessOrders.Cache.Clear();
KNPIPaymentFilter filter = PXCache<KNPIPaymentFilter>.CreateCopy(KNPIFilter.Current);
if (filter.PayPalInvAction == KNPIConstants.SL)
yield break;
PXSelectBase<SOOrder> cmd = new PXSelect<SOOrder, Where<SOOrder.orderType, Equal<SOOrderTypeConstants.salesOrder>, And<SOOrder.status, NotEqual<SOOrderStatus.completed>,
And<SOOrder.paymentMethodID, Equal<Optional<KNPIPaymentFilter.paymentMethodID>>>>>>(this);
int startRow = PXView.StartRow;
int totalRows = 0;
List<object> list = cmd.View.Select(new[] { KNPIFilter.Current }, null, PXView.Searches,
PXView.SortColumns, PXView.Descendings, PXView.Filters, ref startRow, PXView.MaximumRows, ref totalRows);
foreach (SOOrder order in list)
{
KNPIPayments PayPalPayment = new PXSelect<KNPIPayments, Where<KNPIPayments.acmOrderNbr, Equal<Required<KNPIPayments.acmOrderNbr>>,
And<KNPIPayments.acmOrderType, Equal<Required<KNPIPayments.acmOrderType>>>>, OrderBy<Desc<KNPIPayments.lineNbr>>>
(this).SelectWindowed(0, 1, order.OrderNbr, order.OrderType);
if (this.KNPIFilter.Current.PayPalInvAction == KNPIConstants.RE)
{
if (PayPalPayment == null || (PayPalPayment != null && PayPalPayment.PayPalInvoiceStatus == KNPIConstants.CANCELLED))
yield return order;
}
else if (this.KNPIFilter.Current.PayPalInvAction == KNPIConstants.CH)
{
if (PayPalPayment != null && PayPalPayment.PayPalInvoiceStatus == KNPIConstants.SENT)
yield return order;
}
}
PXView.StartRow = 0;
KNPIProcessOrders.Cache.IsDirty = false;
}
Can someone please help me out, as what I am doing wrong or what I am missing here.

Bluetooth LE with Android Studio: Write Characteristic with buttons

I am new to Android and Bluetooth and suffering with this problem.
I want to write on a specific characteristic if two buttons are touched.
If I touch the first button a number between 0-9 should be count with +1. With the other button the number should be decrease with -1.
As a fundament i use the BluetootleGatt Example App from Google.
In the DeviceControlActivity i changed the following code:
private final ExpandableListView.OnChildClickListener servicesListClickListner =
new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
int childPosition, long id) {
if (mGattCharacteristics != null) {
final BluetoothGattCharacteristic characteristic =
mGattCharacteristics.get(groupPosition).get(childPosition);
final int charaProp = characteristic.getProperties(); //The properties contain a bit mask of property flags indicating
//the features of this characteristic.
if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
// If there is an active notification on a characteristic, clear
// it first so it doesn't update the data field on the user interface.
if (mNotifyCharacteristic != null) {
mBluetoothLeService.setCharacteristicNotification(
mNotifyCharacteristic, false);
mNotifyCharacteristic = null;
}
mBluetoothLeService.readCharacteristic(characteristic);
}
if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY ) > 0) {
mNotifyCharacteristic = characteristic;
mBluetoothLeService.setCharacteristicNotification(
characteristic, true);
}
if ((charaProp | BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {
characteristic.setWriteType(BluetoothGattCharacteristic.PERMISSION_WRITE);
addListenerOnButton();
}
return true;
}
return false;
}
};
Here is my addListenerOnButton() for the two buttons:
public void addListenerOnButton() {
mArrowUp = (ImageButton) findViewById(R.id.arrow_up);
mArrowUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mBluetoothLeService.writeCharacteristicUp();
}
});
mArrowDown = (ImageButton) findViewById(R.id.arrow_down);
mArrowDown.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mBluetoothLeService.writeCharacteristicDown();
}
});
}
They will call the two writeCharacteristic Methods in the BluetoothLeService-Class. For example i post here only the writeCharacteristicUp()-Method:
public boolean writeCharacteristicUp() {
//check mBluetoothGatt is available
if (mBluetoothGatt == null) {
Log.e(TAG, "lost connection");
return false;
}
BluetoothGattService Service = mBluetoothGatt.getService(UUID_DO_LOGGER_TEST);
if (Service == null) {
Log.e(TAG, "service not found!");
return false;
}
BluetoothGattCharacteristic charac = Service
.getCharacteristic(UUID_TEST_NUMBER);
if (charac == null) {
Log.e(TAG, "char not found!");
return false;
}
byte[] value0 = new byte[1];
value0[0] = (byte) 0; //Constant of 0 for comparison later
byte[] value1 = new byte[1];
value1[0] = (byte) 1; //Constant of 1 for comparison later
byte[] value2 = new byte[1];
value2[0] = (byte) 2; //Constant of 1 for comparison later
byte[] value3 = new byte[1];
value3[0] = (byte) 3; //Constant of 1 for comparison later
byte[] value4 = new byte[1];
value4[0] = (byte) 4; //Constant of 1 for comparison later
byte[] value5 = new byte[1];
value5[0] = (byte) 5; //Constant of 1 for comparison later
byte[] value6 = new byte[1];
value6[0] = (byte) 6; //Constant of 1 for comparison later
byte[] value7 = new byte[1];
value7[0] = (byte) 7; //Constant of 1 for comparison later
byte[] value8 = new byte[1];
value8[0] = (byte) 8; //Constant of 1 for comparison later
byte[] value9 = new byte[1];
value9[0] = (byte) 9; //Constant of 1 for comparison later
byte[] actualvalue = charac.getValue();
if (actualvalue == value0) {
charac.setValue(value1);
}
if (actualvalue == value1) {
charac.setValue(value2);
}
if (actualvalue == value2) {
charac.setValue(value3);
}
if (actualvalue == value3) {
charac.setValue(value4);
}
if (actualvalue == value4) {
charac.setValue(value5);
}
if (actualvalue == value5) {
charac.setValue(value6);
}
if (actualvalue == value6) {
charac.setValue(value7);
}
if (actualvalue == value7) {
charac.setValue(value8);
}
if (actualvalue == value8) {
charac.setValue(value9);
}
if (actualvalue == value9) {
charac.setValue(value0);
}
// charac.setValue(value0);
// byte[] actualvaluenew1 = charac.getValue();
boolean status = mBluetoothGatt.writeCharacteristic(charac);
// byte[] actualvaluenew2 = charac.getValue();
return status;
}
The problem is that the
boolean status = mBluetoothGatt.writeCharacteristic(charac)
does not work, the status will be false. And so the actual value is not displayed on the Screen in the corresponding TextView. Why?
Also i found out that the if-grinds are not working because charac.setValue(value0) is only working outside the if-grinds?
I would suggest you press and hold control key and click to BluetoothGatt#writeCharacteristic(ch) function in your code. Then Android Studio will view BluetoothGatt#writeCharacteristic(BluetoothGattCharacteristic characteristic) function:
public boolean writeCharacteristic(BluetoothGattCharacteristic characteristic) {
if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE) == 0
&& (characteristic.getProperties() &
BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) == 0) return false;
if (VDBG) Log.d(TAG, "writeCharacteristic() - uuid: " + characteristic.getUuid());
if (mService == null || mClientIf == 0 || characteristic.getValue() == null) return false;
BluetoothGattService service = characteristic.getService();
if (service == null) return false;
BluetoothDevice device = service.getDevice();
if (device == null) return false;
synchronized(mDeviceBusy) {
if (mDeviceBusy) return false;
mDeviceBusy = true;
}
try {
mService.writeCharacteristic(mClientIf, device.getAddress(),
service.getType(), service.getInstanceId(),
new ParcelUuid(service.getUuid()), characteristic.getInstanceId(),
new ParcelUuid(characteristic.getUuid()),
characteristic.getWriteType(), AUTHENTICATION_NONE,
characteristic.getValue());
} catch (RemoteException e) {
Log.e(TAG,"",e);
mDeviceBusy = false;
return false;
}
return true;
}
Put a breakpoint inside the method and do debugging. Here are the possible reasons why you get false based on the source code:
The remote BLE device does not have Write or Write with No Response access
Either your service is null or the characteristic value you set is null
Your device is already doing another BLE process with the remote device
In my opinion, most probably the 2nd item is the reason.

Spring HibernateTemplate in multithread

I have a method in Struts action to deal with sending system-message,so I use Executors.newCachedThreadPool() to call a new thread run that, but when I operate sending again,the thread seemed be dead.Here is my code :
public String sendMessage(){
if(!validateSystemMessage(systemMessage)){
return ERROR;
}
systemMessage.setEnable(false);
systemMessage.setContent(systemMessage.getContent());
systemMessage.setTitle(systemMessage.getTitle());
systemMessage.setMessageTime(new Date());
systemMessageDao.saveOrUpdate(systemMessage);
**ExecutorService executor = Executors.newCachedThreadPool();
SendMessage sendMessage=new SendMessage(systemMessage.getSmId());
LOGGER.info("-- systemMessage---"+systemMessage.getSmId());
sendMessage.setSystemMessageDao(systemMessageDao);
sendMessage.setUserMessageDao(userMessageDao);
String[] ids = userIds.split(",");
LOGGER.info("-- ids.length---"+ids.length);
sendMessage.setUserIds(ids);
executor.submit(sendMessage);**
systemMessage=null;
message=SUCCESS;
return SUCCESS;
}
public class SendMessage implements Callable<Boolean>{
#Override
public Boolean call() throws Exception{
SystemMessage msg = null;
msg = this.systemMessageDao.findSystemMessageById(msgId);
List<Long> userIdsSended = this.userMessageDao.findUserIdsByMsgId(msgId);//thread seemed be dead here
List<Long> listUserIds = new ArrayList<Long>();
for (String userId : userIds) {
Long id=Long.valueOf(userId);
if (userIdsSended != null && userIdsSended.contains(id)) {
continue;
}
listUserIds.add(id);
}
if (listUserIds != null && !listUserIds.isEmpty()) {
this.userMessageDao.save(msgId, listUserIds);
}
msg.setEnable(true);
this.systemMessageDao.saveOrUpdate(msg);
return true;
}
}
public SystemMessage findSystemMessageById(Long smId) {
List<SystemMessage> list = this.getHibernateTemplate().find("from SystemMessage systemMessage where systemMessage.smId = ?", new Object[] { smId });
return list.size() != 0 ? list.get(0) : null;
}
if I send again after few minutes, it run normal, I think the difference is newCachedThreadPool run a new thread .But why in a thread it can't run again? is it the problem with hibernateTemplate or session ?

Get entity object's property names excluding entitycollection and entityreference

I am working on a method that compares two objects using reflection. The object types are objects created from entity framework. When I use GetProperties() I am getting EntityCollection and EntityReference properties. I only want the properties that belong to the object and not any associated properties or references from foreign keys.
I've tried the following How to get all names of properties in an Entity?.
I thought about passing an array of properties to compare but I don't want to have to type them in for each object type. I am open to some suggestions even those that don't use reflection.
public bool CompareEntities<T>(T oldEntity, T newEntity)
{
bool same = true;
PropertyInfo[] properties = oldEntity.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
var oldValue = property.GetValue(oldEntity, null);
var newValue = property.GetValue(newEntity, null);
if (oldValue != null && newValue != null)
{
if (!oldValue.Equals(newValue))
{
same = false;
break;
}
}
else if ((oldValue == null && newValue != null) || (oldValue != null && newValue == null))
{
same = false;
break;
}
}
return same;
}
Using the suggestions from #Eranga and https://stackoverflow.com/a/5381986/1129035 I was able to come up with a workable solution.
Since some of the properties in the root object are a GenericType there needs to be two different if statements. Only if the current property is an EntityCollection skip over it.
public bool CompareEntities<T>(T oldEntity, T newEntity)
{
bool same = true;
PropertyInfo[] properties = oldEntity.GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
.Where(pi => !(pi.PropertyType.IsSubclassOf(typeof(EntityObject)))
&& !(pi.PropertyType.IsSubclassOf(typeof(EntityReference)))
).ToArray();
foreach (PropertyInfo property in properties)
{
if (property.PropertyType.IsGenericType)
{
if (property.PropertyType.GetGenericTypeDefinition() == typeof(EntityCollection<>))
{
continue;
}
}
var oldValue = property.GetValue(oldEntity, null);
var newValue = property.GetValue(newEntity, null);
if (oldValue != null && newValue != null)
{
if (!oldValue.Equals(newValue))
{
same = false;
break;
}
}
else if ((oldValue == null && newValue != null) || (oldValue != null && newValue == null))
{
same = false;
break;
}
}
return same;
}
Try filtering out EntityObject type and EntityCollection properties.
var properties = oldEntity.GetType().GetProperties().
Where(pi => !(pi.PropertyType.IsSubclassOf(typeof(EntityObject))
|| pi.PropertyType.IsSubclassOf(typeof(EntityCollection));
make it easy for yourself and do this instead
PropertyInfo[] properties = oldEntity.GetType().GetProperties(pi=> pi.PropertyType.NameSpace=="System").ToArray();

SD Card's Free Size

I want to check the free size available on My Device's SD Card. I know FileConnection API. How can I check the free size of the SD Card ?
The idea is to open the cfcard file connection and call availableSize() on it. to get the proper memory card location read it from the System.getProperty(...). In some devices the aforesaid property may fail hence constructing new path from the memory card name system property.
NOTE: In certain devices the hostname must be 'localhost', hence change the return string in getFilehost() appropriately.
PS: Since this is a code snippet certain form / command references may throw null pointer please resolve it accordingly.
Below code with get you the available size in 'BYTES' of the memory card
String memoryCardPath = System.getProperty("fileconn.dir.memorycard");
addToLogs(memoryCardPath);
if (null == memoryCardPath) {
displayAlert(null);
}
nativeHostname(memoryCardPath);
addToLogs(nativeHostname);
String path = buildPath(memoryCardPath.substring(getFilehost().length()));
addToLogs(path);
long availableSize = getAvailableSize(path);
addToLogs(String.valueOf(availableSize)+" Bytes");
if(availableSize == 0L) {
String memoryCardName = System.getProperty("fileconn.dir.memorycard.name");
addToLogs(memoryCardName);
path = buildPath(memoryCardName + "/");
addToLogs(path);
availableSize = getAvailableSize(path);
addToLogs(String.valueOf(availableSize)+" Bytes");
if(availableSize == 0L) {
displayAlert(null);
return;
}
}
displayAlert(String.valueOf(availableSize));
Supporting methods
public String buildPath(String foldername) {
if(null == foldername) {
foldername = "";
}
addToLogs("[BP]"+getFilehost());
addToLogs("[BP]"+foldername);
return new StringBuffer().append(getFilehost()).append(foldername).toString();
}
String nativeHostname = null;
public void nativeHostname(String url) {
String host = url.substring("file://".length());
addToLogs("[NH]"+host);
int index = host.indexOf('/');
addToLogs("[NH]"+String.valueOf(index));
if(index > 0) {
nativeHostname = host.substring(0, index);
} else {
nativeHostname = "/";
}
addToLogs("[NH]"+nativeHostname);
}
public boolean tryLocalhost = false;
public String getFilehost() {
final StringBuffer buf = new StringBuffer().append("file://");
if (null != nativeHostname && nativeHostname.length() > 0) {
buf.append(nativeHostname);
}
addToLogs("[GFH] "+buf.toString());
return buf.toString();
}
public long getAvailableSize(String path) {
FileConnection fcon = null;
try {
fcon = (FileConnection) Connector.open(path, Connector.READ);
if(null != fcon && fcon.exists()) {
return fcon.availableSize();
} else {
return 0L;
}
} catch (IOException ex) {
ex.printStackTrace();
addToLogs("[GAS]"+"ERROR : "+ex.getMessage());
return 0L;
} finally {
try {
fcon.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void displayAlert(String text) {
Alert alert = new Alert(
null == text ? "Warning" : "Info",
null == text ? "Memory card not available" : text,
null,
null == text ? AlertType.WARNING : AlertType.INFO);
alert.setTimeout(Alert.FOREVER);
Display.getDisplay(this).setCurrent(alert, Display.getDisplay(this).getCurrent());
}
public void addToLogs(String log) {
log = null == log ? "null" : log;
getFormLogs().append(new StringItem("", log+"\n"));
}

Resources