how to pass data to onTestSuccess method in Listener class of TESTNG for each iteration from #Test method used dataprovider - annotations

, i have a #Test method with dataprovider , i have a Listener.class , my target is that when my #Test method is success, the status of case in testrail is setted as "Passed" automatically in onTestSuccess Method of Listener class , this process is ok, but when i use dataprovider for #Test Method, this causes the problem
i want that same method must be worked (let say) three times because of dataprovider and different case id data must be sent to onTestSuccess method for each iteration from #Test method
My Listener.class
package com.myproject.test.listeners;
import java.lang.reflect.Method;
import org.testng.IClass;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ISuite;
import org.testng.ISuiteListener;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
public class Listener implements ITestListener, ISuiteListener, IInvokedMethodListener {
...
public void onTestStart(ITestResult result) {
}
public void onTestSuccess(ITestResult result) {
try {
Program pr = new Program();
System.out.println("onTestSuccess Method for :" + result.getName());
String TestID = null;
String TestRunID = null;
for (Method testMethod : result.getTestClass().getRealClass().getMethods()) {
if (testMethod.getName().equals(result.getName()) && testMethod.isAnnotationPresent(UseAsTestRailId.class)) {
UseAsTestRailId useAsTestName = testMethod.getAnnotation(UseAsTestRailId.class);
TestID = Integer.toString(useAsTestName.testRailCaseId());
TestRunID = Integer.toString(useAsTestName.testRailRunId());
System.out.println("Case ID---> " + TestID + " Run ID--> " + TestRunID);
// 1 = Passed
pr.enterTestResult(TestRunID, TestID, 1);
}
}
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
...
}
My test class (SettingsTests.java) including my #Test method (checkCurrentPasswordFormatIsValidatedTest)
#Listeners(com.test.listeners.Listener.class)
//listener annotation row is written in BaseTest class
public class SettingsTests extends BaseTest {
...
/**
* Test Case - C5001275 - Check that "Please enter at least 8 characters."
* message is displayed when entered value into "Current Password" field in
* wrong format This case will run two times!
*
* #param currentPasswordValue
*/
#Test(dataProvider = "currentPasswordTestWithWrongValue")
#UseAsTestRailId(testRailCaseId = 5001275,testRailRunId = 56662)
// aim is that to send different case id for each iteration,now even if method works twice , only one testRailCaseId is sent
public void checkCurrentPasswordFormatIsValidatedTest(String currentPasswordValue) {
logger.trace("STARTING TEST: checkCurrentPasswordFormatisValidatedTest");
logger.trace("Test Step : Enter current password in wrong format");
settingsPageObject.enterCurrentPassword(currentPasswordValue);
logger.trace("Test Step : Click on the button 'UPDATE' ");
settingsPageObject.clickOnUpdateButton();
logger.trace("Expected Result: The message 'Please enter at least 8 characters.' is displayed on screen.");
Assert.assertEquals(settingsPageObject.getCurrentPasswordWrongText(), "Please enter at least 8 characters.");
}
#DataProvider(name = "currentPasswordTestWithWrongValue")
public static Object[][] validateTestWithCurrentPasswordInWrongFormat() {
return new Object[][] { { RandomStringUtils.randomAlphabetic(7) }, { RandomStringUtils.randomAlphabetic(1) } };
}
...
}
My annotation class (UseAsTestRailId.java)
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface UseAsTestRailId
{
int testRailCaseId() default 0;
int testRailRunId() default 0;
String[] tags() default "";
}
Some #Test methods to set two case status, some #Test methods to set three case status in testRail,so the more dataprovider data set needed the more case id needed , it must be dynamical

You can use the setattribute value in the testresult object to set custom value. Get the currentresult from Reporter : Reporter.getCurrentTestresult and then setAttribute ("TC_id",sasdf) and use that in your ontestsuccess using the getAttribute ("TC_id") on result object.

Related

Kafka Connect Custom Transformation : Override of apply() method seems to have no effect, but overriding newRecord method in key and value works

I am trying to create a custom connector following the pattern used in the samples
https://github.com/apache/kafka/blob/trunk/connect/transforms/src/main/java/org/apache/kafka/connect/transforms/ExtractField.java
https://github.com/confluentinc/kafka-connect-insert-uuid/blob/master/src/main/java/com/github/cjmatta/kafka/connect/smt/InsertUuid.java
I have overriden the apply method to add a small string to the payload
public R apply(R record) {
log.info("Transformation apply has started...");
String newValue = record.value().toString() + " this has been transformed" ;
log.info("Message changed to : " + newValue);
return newRecord(record, null, newValue);
}
This has no effect at all. The output is not changed. I also do not see the log info messages anywhere in the generated log.
However if I override the newRecord method of the Value class I am able to see the message being updated. Also i see the info messages being logged.
protected R newRecord(R record, Schema updatedSchema, Object updatedValue) {
log.info("Message Value being changed to :");
return record.newRecord(record.topic(), record.kafkaPartition(), record.keySchema(), record.key(),
updatedSchema, "This is updated : " + updatedValue.toString(), record.timestamp());
}
This results in the output message being updated as expected. Note that the payload in the message is a string payload and does not have any particular structure.
I was thinking that this payload manipulation can occur in apply() method as well. Also I do not see this apply() method being called in the transformation run. The payload is not affected and the messages are not logged.
Am I missing something here. Is the apply() method being called or used incorrectly. Any guidance is appreciated.
Note : Overriding the newRecord method of the key class also works.
The full source code of the transformation is below
package com.xxxxx.yyyyy.kafka.connect.transform;
import org.apache.kafka.connect.connector.ConnectRecord;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.transforms.HoistField;
import org.apache.kafka.connect.transforms.Transformation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
public abstract class SampleTransform<R extends ConnectRecord<R>> implements Transformation<R> {
private static Logger log = LoggerFactory.getLogger(SampleTransform.class);
#Override
public void configure(Map<String, ?> map) {
}
#Override
public R apply(R record) {
log.info("Transformation apply has started..."); //This does not work
String newValue = record.value().toString() + " this has been transformed" ;
log.info("Message changed to : " + newValue);
return newRecord(record, null, "Message is fully changed"); //Output does not change
}
protected abstract Schema operatingSchema(R record);
protected abstract Object operatingValue(R record);
protected abstract R newRecord(R record, Schema updatedSchema, Object updatedValue);
public static class Key<R extends ConnectRecord<R>> extends HoistField<R> {
#Override
protected Schema operatingSchema(R record) {
return record.keySchema();
}
#Override
protected Object operatingValue(R record) {
return record.key();
}
#Override
protected R newRecord(R record, Schema updatedSchema, Object updatedValue) {
log.info("Key being changed to : " + updatedValue.toString()); //This is logged
return record.newRecord(record.topic(), record.kafkaPartition(), updatedSchema, updatedValue, record.valueSchema(), record.value(), record.timestamp());
}
}
public static class Value<R extends ConnectRecord<R>> extends HoistField<R> {
#Override
protected Schema operatingSchema(R record) {
return record.valueSchema();
}
#Override
protected Object operatingValue(R record) {
return record.value();
}
#Override
protected R newRecord(R record, Schema updatedSchema, Object updatedValue) {
log.info("Message Value being changed to :"); // This is logged
return record.newRecord(record.topic(), record.kafkaPartition(), record.keySchema(), record.key(), updatedSchema, "This is updated : " + updatedValue.toString(), record.timestamp()); //This works
}
}
}
The issue is, that you extends org.apache.kafka.connect.transforms.HoistField instead of your Transformation - SampleTransform

MIMEMessage and MIMEMessage mock test case fails with assertion error on EmailUtil

What I'm trying to achieve - Simple unit test for my EmailUtil which i have written for a Spring MVC application.
Where I'm stuck - Though i have mocked the MIMEmessage and JavaMailSender, test case failing in MimeMessageHelper.set**** methods.
Appreciate any help on this as I have tried few different ways even using PowerMock and no luck for last couple of days.
EmailUtil.Java
import java.util.List;
import javax.activation.DataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import com.dashboard.domain.Attachment;
import com.dashboard.domain.Email;
public class EmailUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(EmailUtil.class
.getName());
/**
* Private constructor to make sure that no one creating instance
*/
private EmailUtil() {
}
/**
* Functionality to send the mail. This method used the mail sender
* configuration from spring-context file.
*
* #param email
* #param mailSender
* #throws MessagingException
*/
public static void sendEmail(JavaMailSender mailSender, Email email)
throws MessagingException {
LOGGER.info("Start of the method: sendEmail");
MimeMessage mimeMessage = mailSender.createMimeMessage();
// use the true flag to indicate you need a multi part message
boolean hasAttachments = email.getAttachments() != null
&& !email.getAttachments().isEmpty();
LOGGER.info(" mimeMessage - {} ",mimeMessage);
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,
hasAttachments);
LOGGER.info(" MimeMessageHelper - {} ",helper);
helper.setTo(email.getTo());
helper.setFrom(email.getFrom());
helper.setCc(email.getCc());
helper.setSubject(email.getSubject());
helper.setText(email.getText(), true);
List<Attachment> attachments = email.getAttachments();
if (!attachments.isEmpty()) {
for (Attachment attachment : attachments) {
String filename = attachment.getFilename();
DataSource dataSource = new ByteArrayDataSource(
attachment.getData(), attachment.getMimeType());
if (attachment.isInline()) {
helper.addInline(filename, dataSource);
} else {
helper.addAttachment(filename, dataSource);
}
}
}
mailSender.send(mimeMessage);
LOGGER.info("End of the method: sendEmail");
}
}
EmailUtilTest.Java
import static org.easymock.EasyMock.expect;
import javax.mail.Address;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import org.easymock.EasyMock;
import org.easymock.Mock;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import com.dashboard.domain.ApplicationConstant;
import com.dashboard.domain.Email;
/**
* PowerMockDemo
* #author s.arumugam
*
*/
#RunWith(PowerMockRunner.class)
#PrepareForTest(EmailUtil.class)
public class EmailUtilTest {
Email email = new Email();
#Mock
JavaMailSender javaMailSender;
#Mock
MimeMessage mimeMessage;
#Mock
MimeMessageHelper mimeMessageHelper;
#Before
public void initList() {
email.setFrom(ApplicationConstant.DEFAULT_MAIL_ID.getValue());
email.setSubject("Subject");
email.setTo("to.email#userdomain.com");
email.setCc("admin#dashboard.com");
email.setText("Body of the email");
}
#Test
public void sendEmailTest() throws Exception{
mimeMessageHelper.setSubject(email.getSubject());
mimeMessageHelper.setFrom(new InternetAddress(email.getFrom(), true));
mimeMessageHelper.setCc(new InternetAddress(email.getCc()[0], true));
mimeMessageHelper.setTo(new InternetAddress(email.getTo()[0], true));
mimeMessageHelper.setText(email.getText());
expect(javaMailSender.createMimeMessage()).andReturn(mimeMessage);
Address sendTo[]={new InternetAddress(email.getTo()[0])};
mimeMessage.setRecipients(RecipientType.TO,sendTo);
EasyMock.expectLastCall().times(1);
EasyMock.replay(mimeMessage);
EasyMock.replay(javaMailSender);
EmailUtil.sendEmail(javaMailSender, email);
EasyMock.verify(mimeMessage);
EasyMock.verify(javaMailSender);
}
}
Error Message:
java.lang.AssertionError: Unexpected method call MimeMessage.setRecipients(To, [to.email#userdomain.com]):
MimeMessage.setRecipients(To, [to.email#userdomain.com]): expected: 1, actual: 0 at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44) at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:94) at org.easymock.internal.ClassProxyFactory$MockMethodInterceptor.intercept(ClassProxyFactory.java:97) at $javax.mail.internet.MimeMessage$$EnhancerByCGLIB$$a6025b60.setRecipients(<generated>) at org.springframework.mail.javamail.MimeMessageHelper.setTo(MimeMessageHelper.java:581) at org.springframework.mail.javamail.MimeMessageHelper.setTo(MimeMessageHelper.java:595) at com.dashboard.util.EmailUtil.sendEmail(EmailUtil.java:50)
Ohh.. I managed to fix the issue.. purely by random trial and error..! That says I need to get into deep understanding of how these mock utils works.. Working test case below with a hope someone can find a complete working example with test case;
#RunWith(EasyMockRunner.class)
public class EmailUtilTest extends EasyMockSupport{
#Mock
JavaMailSender mailSender;
#Mock
MimeMessage mimeMessage;
#Test
public void testSendEmail() throws MessagingException{
Email email = new Email();
email.setFrom("from.email#dashboard.com");
email.setSubject("Subject");
email.setTo("to.email#userdomain.com");
email.setCc("admin#dashboard.com");
email.setText("Body of the email");
EasyMock.expect(mailSender.createMimeMessage()).andReturn(mimeMessage);
mailSender.send(mimeMessage);
EasyMock.expectLastCall();
EasyMock.replay(mailSender);
EmailUtil.sendEmail(mailSender, email);
EasyMock.verify(mailSender);
}
}
The reason you are getting java.lang.AssertionError is because EasyMock uses the equals() method to compare parameters passed to methods, and you cannot use equals() to compare arrays.
Address toAddress = new InternetAddress("a#b.com");
Address[] a1 = { toAddress };
Address[] a2 = { toAddress };
if (a1.equals(a2)) { // this will be false
// so this won't happen
}
Thankfully, EasyMock provides us with several different argument matchers. In this case we should use EasyMock.aryEq(). So in order to mock out the call to setRecipients() method:
mimeMessage.setRecipients(EasyMock.eq(RecipientType.TO) , EasyMock.aryEq(sendTo));
I'm not sure how the accepted answer is working without changes to the EmailUtil class.

Change 2nd parameter of method 'PlaceAutocompleteAdapter' from 'GeoDataClient' to 'GoogleApiClient'

i ma making AutoCompleteTextView in my adapter for which when i make object of PlaceAutocompleteAdapter when i pass GoogleApiClient object as second parameter to my PlaceAutocompleteAdapter it gives me red error and sys to pass GEODataClient object instead of GoogleApiClient
while the code for my Fragment containing map is this
package com.example.anonymous.ghar_ka_khana;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import android.Manifest;
import android.widget.AutoCompleteTextView;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Executor;
public class GoogleFragment extends Fragment implements OnMapReadyCallback,LocationListener,GoogleApiClient.OnConnectionFailedListener {
private MapFragment m;
private GoogleMap mMap;
FusedLocationProviderClient fusedLocationProviderClient;
private int REQUEST_PERMISSIONS_REQUEST_CODE = 125;
protected Location mLastLocation;
private AutoCompleteTextView autoCompleteTextView;
private PlaceAutocompleteAdapter autocompleteAdapter;
private String mLatitiudelabel;
private String mLongitudelabel;
private GoogleApiClient mGoogleApiClient;
private static LatLngBounds Lat_Long_Bounds = new LatLngBounds(new LatLng(-40,-168),new LatLng(71,136));
View v;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Log.i("pahlywala", "onCreateView");
v = inflater.inflate(R.layout.fragment_google, container, false);
mGoogleApiClient = new GoogleApiClient
.Builder(getActivity())
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(new DrawerActivity(), this)
.build();
autoCompleteTextView = (AutoCompleteTextView)v.findViewById(R.id.mapsearch);
autocompleteAdapter = new PlaceAutocompleteAdapter(getActivity(),mGoogleApiClient,Lat_Long_Bounds,null);
autoCompleteTextView.setAdapter(autocompleteAdapter);
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mLatitiudelabel = "Latitude";
mLongitudelabel = "Longitude";
FragmentManager fragmentManager = getActivity().getFragmentManager();
final MapFragment myMapFragment = (MapFragment) fragmentManager.findFragmentById(R.id.googlemap);
myMapFragment.getMapAsync(this);
Log.i("pahlywalass", "onViewCreated");
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mMap=googleMap;
mMap.addMarker(new MarkerOptions()
.position(new LatLng(0, 0))
.title("Marker"));
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStart() {
super.onStart();
if (!checkPermissions()) {
requestPermissions();
} else {
getLastLocation();
}
}
private boolean checkPermissions() {
int permissionState = ActivityCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION);
return permissionState == PackageManager.PERMISSION_GRANTED;
}
private void requestPermissions() {
boolean shouldProvideRationale =
ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION);
// Provide an additional rationale to the user. This would happen if the user denied the
// request previously, but didn't check the "Don't ask again" checkbox.
if (shouldProvideRationale) {
Log.i("displaying permission", "Displaying permission rationale to provide additional context.");
/* showSnackbar("warning", android.R.string.ok,
new View.OnClickListener() {
#Override
public void onClick(View view) {
// Request permission
startLocationPermissionRequest();
}
});*/
} else {
Log.i("requesting permission", "Requesting permission");
// Request permission. It's possible this can be auto answered if device policy
// sets the permission in a given state or the user denied the permission
// previously and checked "Never ask again".
startLocationPermissionRequest();
}
}
private void startLocationPermissionRequest() {
ActivityCompat.requestPermissions(new DrawerActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
Log.i("onRequestPerm", "onRequestPermissionResult");
if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
if (grantResults.length <= 0) {
// If user interaction was interrupted, the permission request is cancelled and you
// receive empty arrays.
Log.i("onRequestPerm", "User interaction was cancelled.");
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted.
getLastLocation();
} else {
// Permission denied.
// Notify the user via a SnackBar that they have rejected a core permission for the
// app, which makes the Activity useless. In a real app, core permissions would
// typically be best requested during a welcome-screen flow.
// Additionally, it is important to remember that a permission might have been
// rejected without asking the user for permission (device policy or "Never ask
// again" prompts). Therefore, a user interface affordance is typically implemented
// when permissions are denied. Otherwise, your app could appear unresponsive to
// touches or interactions which have required permissions.
/*showSnackbar(R.string.textwarn, R.string.settings,
new View.OnClickListener() {
#Override
public void onClick(View view) {
// Build intent that displays the App settings screen.
Intent intent = new Intent();
intent.setAction(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package",
BuildConfig.APPLICATION_ID, null);
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});*/
}
}
}
private void getLastLocation() {
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
fusedLocationProviderClient.getLastLocation()
.addOnCompleteListener(getActivity(), new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
if (task.isSuccessful() && task.getResult() != null) {
mLastLocation = task.getResult();
Log.i("Longitutde", mLastLocation.getLongitude()+"");
Log.i("Longitutde", mLastLocation.getLatitude()+"");
LatLng cur_Latlng=new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude()); // giving your marker to zoom to your location area.
mMap.addMarker(new MarkerOptions()
.position(cur_Latlng)
.title("umair"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(cur_Latlng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
Geocoder geocoder;
List<Address> addresses = null;
geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
addresses = geocoder.getFromLocation(mLastLocation.getLatitude(),mLastLocation.getLongitude(), 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
} catch (IOException e) {
e.printStackTrace();
}
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
/*String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();*/
Log.i("pat", ""+city);
}
else {
Log.i("getlasts", "getLastLocation:exception", task.getException());
}
}
});
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
while the code for PlaceAutoCompleteAdapter is following
package com.example.anonymous.ghar_ka_khana;
/**
* Created by Anonymous on 2/19/2018.
*/
import android.content.Context;
import android.graphics.Typeface;
import android.text.style.CharacterStyle;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.data.DataBufferUtils;
import com.google.android.gms.location.places.AutocompleteFilter;
import com.google.android.gms.location.places.AutocompletePrediction;
import com.google.android.gms.location.places.AutocompletePredictionBufferResponse;
import com.google.android.gms.location.places.GeoDataClient;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.tasks.RuntimeExecutionException;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Adapter that handles Autocomplete requests from the Places Geo Data Client.
* {#link AutocompletePrediction} results from the API are frozen and stored directly in this
* adapter. (See {#link AutocompletePrediction#freeze()}.)
*/
public class PlaceAutocompleteAdapter
extends ArrayAdapter<AutocompletePrediction> implements Filterable {
private static final String TAG = "PlaceAutocompleteAd";
private static final CharacterStyle STYLE_BOLD = new StyleSpan(Typeface.BOLD);
/**
* Current results returned by this adapter.
*/
private ArrayList<AutocompletePrediction> mResultList;
/**
* Handles autocomplete requests.
*/
private GeoDataClient mGeoDataClient;
/**
* The bounds used for Places Geo Data autocomplete API requests.
*/
private LatLngBounds mBounds;
/**
* The autocomplete filter used to restrict queries to a specific set of place types.
*/
private AutocompleteFilter mPlaceFilter;
/**
* Initializes with a resource for text rows and autocomplete query bounds.
*
* #see android.widget.ArrayAdapter#ArrayAdapter(android.content.Context, int)
*/
public PlaceAutocompleteAdapter(Context context, GeoDataClient geoDataClient,
LatLngBounds bounds, AutocompleteFilter filter) {
super(context, android.R.layout.simple_expandable_list_item_2, android.R.id.text1);
mGeoDataClient = geoDataClient;
mBounds = bounds;
mPlaceFilter = filter;
}
/**
* Sets the bounds for all subsequent queries.
*/
public void setBounds(LatLngBounds bounds) {
mBounds = bounds;
}
/**
* Returns the number of results received in the last autocomplete query.
*/
#Override
public int getCount() {
return mResultList.size();
}
/**
* Returns an item from the last autocomplete query.
*/
#Override
public AutocompletePrediction getItem(int position) {
return mResultList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
// Sets the primary and secondary text for a row.
// Note that getPrimaryText() and getSecondaryText() return a CharSequence that may contain
// styling based on the given CharacterStyle.
AutocompletePrediction item = getItem(position);
TextView textView1 = (TextView) row.findViewById(android.R.id.text1);
TextView textView2 = (TextView) row.findViewById(android.R.id.text2);
textView1.setText(item.getPrimaryText(STYLE_BOLD));
textView2.setText(item.getSecondaryText(STYLE_BOLD));
return row;
}
/**
* Returns the filter for the current set of autocomplete results.
*/
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
// We need a separate list to store the results, since
// this is run asynchronously.
ArrayList<AutocompletePrediction> filterData = new ArrayList<>();
// Skip the autocomplete query if no constraints are given.
if (constraint != null) {
// Query the autocomplete API for the (constraint) search string.
filterData = getAutocomplete(constraint);
}
results.values = filterData;
if (filterData != null) {
results.count = filterData.size();
} else {
results.count = 0;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
// The API returned at least one result, update the data.
mResultList = (ArrayList<AutocompletePrediction>) results.values;
notifyDataSetChanged();
} else {
// The API did not return any results, invalidate the data set.
notifyDataSetInvalidated();
}
}
#Override
public CharSequence convertResultToString(Object resultValue) {
// Override this method to display a readable result in the AutocompleteTextView
// when clicked.
if (resultValue instanceof AutocompletePrediction) {
return ((AutocompletePrediction) resultValue).getFullText(null);
} else {
return super.convertResultToString(resultValue);
}
}
};
}
/**
* Submits an autocomplete query to the Places Geo Data Autocomplete API.
* Results are returned as frozen AutocompletePrediction objects, ready to be cached.
* Returns an empty list if no results were found.
* Returns null if the API client is not available or the query did not complete
* successfully.
* This method MUST be called off the main UI thread, as it will block until data is returned
* from the API, which may include a network request.
*
* #param constraint Autocomplete query string
* #return Results from the autocomplete API or null if the query was not successful.
* #see GeoDataClient#getAutocompletePredictions(String, LatLngBounds, AutocompleteFilter)
* #see AutocompletePrediction#freeze()
*/
private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) {
Log.i(TAG, "Starting autocomplete query for: " + constraint);
// Submit the query to the autocomplete API and retrieve a PendingResult that will
// contain the results when the query completes.
Task<AutocompletePredictionBufferResponse> results =
mGeoDataClient.getAutocompletePredictions(constraint.toString(), mBounds,
mPlaceFilter);
// This method should have been called off the main UI thread. Block and wait for at most
// 60s for a result from the API.
try {
Tasks.await(results, 60, TimeUnit.SECONDS);
} catch (ExecutionException | InterruptedException | TimeoutException e) {
e.printStackTrace();
}
try {
AutocompletePredictionBufferResponse autocompletePredictions = results.getResult();
Log.i(TAG, "Query completed. Received " + autocompletePredictions.getCount()
+ " predictions.");
// Freeze the results immutable representation that can be stored safely.
return DataBufferUtils.freezeAndClose(autocompletePredictions);
} catch (RuntimeExecutionException e) {
// If the query did not complete successfully return null
Toast.makeText(getContext(), "Error contacting API: " + e.toString(),
Toast.LENGTH_SHORT).show();
Log.e(TAG, "Error getting autocomplete prediction API call", e);
return null;
}
}
}
my gradle file is following
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.example.anonymous.ghar_ka_khana"
minSdkVersion 17
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.google.firebase:firebase-database:11.8.0'
//11.0.4
implementation 'com.android.support:support-v4:26.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.google.android.gms:play-services:11.8.0'
implementation 'com.firebaseui:firebase-ui-auth:3.1.3'
// FirebaseUI for Firebase Auth
implementation 'com.firebaseui:firebase-ui-database:3.1.3'
// FirebaseUI for Firebase Realtime Database
implementation 'com.firebaseui:firebase-ui-firestore:3.1.3'
// FirebaseUI for Cloud Firestore
compile 'com.google.firebase:firebase-firestore:11.8.0'
//Firestore dependency
implementation 'com.firebaseui:firebase-ui-storage:3.1.3'
// FirebaseUI for Cloud Storage
implementation 'com.facebook.android:facebook-login:4.29.0'
// Required only if Facebook login support is required
implementation 'de.hdodenhof:circleimageview:2.2.0'
implementation 'com.github.florent37:materialtextfield:1.0.7'
compile 'com.scalified:fab:1.1.3'
compile 'com.google.firebase:firebase-storage:11.8.0'
compile 'com.google.firebase:firebase-auth:11.8.0'
compile 'com.github.glomadrian:Grav:1.1'
implementation('com.mikepenz:materialdrawer:6.0.6#aar') {
transitive = true
}
compile 'com.wdullaer:materialdatetimepicker:3.5.1'
implementation 'com.android.support:design:26.1.0'
implementation 'com.android.support:recyclerview-v7:26.1.0'
implementation 'com.android.support:support-annotations:26.1.0'
implementation 'com.google.android.gms:play-services:11.8.0'
implementation 'com.google.android.gms:play-services-location:11.8.0'
}
apply plugin: 'com.google.gms.google-services'
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
def requested = details.requested
if (requested.group == 'com.android.support') {
if (!requested.name.startsWith("multidex")) {
details.useVersion '26.1.0'
}
}
}
}
Ok. I've got the solution instead of using:
autocompleteAdapter = new PlaceAutocompleteAdapter(getActivity(),mGoogleApiClient,Lat_Long_Bounds,null);
you will have to use:
autocompleteAdapter = new PlaceAutocompleteAdapter(getActivity(),Places.getGeoDataClient(getActivity(), null),Lat_Long_Bounds,null);

Error setting database config property for IDatabaseConnection (HSQLDB)

I've included fully testable code below, which generates the following error when supplied with a dataset xml containing empty fields. A sample dataset.xml is also below.
java.lang.IllegalArgumentException: table.column=places.CITY value is
empty but must contain a value (to disable this feature check, set
DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS to true)
The thread here is similar but is different since it uses multiple dbTester.getConnection() whereas my code only uses one, yet has the same error. The main problem relates to this line databaseConfig.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, Boolean.TRUE); .
It seems to be ignored entirely. I've tried putting the init code inside the #Test method but the error remains.
dataset.xml
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
<places address="123 Up Street" city="Chicago" id="001"/>
<places address="456 Down Street" city="" id="002"/>
<places address="789 Right Street" city="Boston" id="003"/>
</dataset>
Code:
import org.dbunit.IDatabaseTester;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.operation.DatabaseOperation;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class DBConnectionIT {
IDatabaseTester databaseTester = null;
IDatabaseConnection iConn = null;
Connection connection = null;
#Before
public void init() throws Exception {
databaseTester = new JdbcDatabaseTester(org.hsqldb.jdbcDriver.class.getName(), "jdbc:hsqldb:mem:testdb;sql.syntax_pgs=true", "sa", "");
iConn = databaseTester.getConnection();
DatabaseConfig databaseConfig = iConn.getConfig();
databaseConfig.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, Boolean.TRUE);
connection = iConn.getConnection();
createTable(connection);
IDataSet dataSet = new FlatXmlDataSetBuilder().build(new File("dataset.xml"));
databaseTester.setDataSet(dataSet);
databaseTester.setSetUpOperation(DatabaseOperation.CLEAN_INSERT);
databaseTester.setTearDownOperation(DatabaseOperation.DELETE_ALL);
databaseTester.onSetup();
}
#Test
public void testDBUnit() {
try {
PreparedStatement pst = connection.prepareStatement("select * from places");
ResultSet rs = pst.executeQuery();
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void createTable(Connection conn) throws Exception {
PreparedStatement pp = conn.prepareStatement(
"CREATE TABLE PLACES" +
"(address VARCHAR(255), " +
"city TEXT, " +
"id VARCHAR(255) NOT NULL primary key)");
pp.executeUpdate();
pp.close();
}
}
EDIT (based on César Rodríguez's answer):
I've now refactored out this method in the parent class:
protected void setUpDatabaseConfig(DatabaseConfig databaseConfig) {
databaseConfig.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, Boolean.TRUE);
}
and created a sub-class which #Overrides this method, but it's saying this sub-class is not being used. How do I address this class (DBConnectionOverride) in the parent class, to solve my problem?
class DBConnectionOverride extends DBConnectionIT {
#Override
protected void setUpDatabaseConfig(DatabaseConfig databaseConfig) {
databaseConfig.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, true);
}
}
I've stumbled upon the correct answer, at least the one which solves my problem. It related to this line all along databaseTester.onSetup() which could simply be replaced with DatabaseOperation.CLEAN_INSERT.execute(iConn, dataSet);. Feel free comment on why this seemed to have fixed the error.
You must override method setUpDatabaseConfig(DatabaseConfig config) as follows:
#Override
protected void setUpDatabaseConfig(DatabaseConfig config) {
config.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, true);
}
Hope it helps
for me it's work:
IDatabaseConnection dbConn = new DatabaseDataSourceConnection(getDataSource());
dbConn.getConfig().setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, true);
DatabaseOperation.CLEAN_INSERT.execute(dbConn, getiDataSet(loadDBData.source()));

Control Netbeans from Commandline: attach Debugger from Shell-script

I'm using a daemon-script which is monitoring a remote server. When the remote server is up, i want that Netbeans automatically connects it's Debugger to the remote Server.
Is it possible to control this behavior from commandline?
To type Something like
netbeans --attach-debugger 192.168.178.34:9009
inside a terminal to do that? Or what other ways do i have to get access to Netbeans-internal stuff? (until now, i was just a "user" of Netbeans so i don't know the internals and how to access them very well)
Or will i have to write a Netbeans Plugin to do that? If yes, can you give me a good starting point to add that functionality?
Ok since there is no option to attach the Debugger from commandline, i wrote a Netbeans Plugin with the help of this blog entry and this thread from the NB-mailinglist. Now i'm able to call my plugin actions from the Commandline.
So build a simple NetBeans Module, which contains 2 important classes.
This is the class which gets the commandline parameters and forwards them to my Action:
import java.awt.event.ActionEvent;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import javax.swing.Action;
import org.netbeans.api.sendopts.CommandException;
import org.netbeans.spi.sendopts.Env;
import org.netbeans.spi.sendopts.OptionProcessor;
import org.netbeans.spi.sendopts.Option;
import org.openide.ErrorManager;
import org.openide.cookies.InstanceCookie;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataObject;
import org.openide.util.lookup.ServiceProvider;
import org.openide.windows.WindowManager;
#ServiceProvider(service = OptionProcessor.class)
public class TriggerActionCommandLine extends OptionProcessor {
//Here we specify "runAction" as the new key in the command,
//but it could be any other string you like, of course:
private static Option action = Option.requiredArgument(Option.NO_SHORT_NAME, "debug");
private static final Logger logger = Logger.getLogger(AttachDebugger.class.getName());
#Override
public Set<org.netbeans.spi.sendopts.Option> getOptions() {
return Collections.singleton(action);
}
#Override
protected void process(Env env, Map<Option, String[]> values) throws CommandException {
final String[] args = (String[]) values.get(action);
if (args.length > 0) {
//Set the value to be the first argument from the command line,
//i.e., this is "GreetAction", for example:
final String ip = args[0];
//Wait until the UI is constructed,
//otherwise you will fail to retrieve your action:
WindowManager.getDefault().invokeWhenUIReady(new Runnable() {
#Override
public void run() {
//Then find & perform the action:
Action a = findAction(AttachDebugger.ACTION_NAME);
// forward IP address to Action
ActionEvent e = new ActionEvent(this, 1, ip);
a.actionPerformed(e);
}
});
}
}
public Action findAction(String actionName) {
FileObject myActionsFolder = FileUtil.getConfigFile("Actions/PSFActions");
FileObject[] myActionsFolderKids = myActionsFolder.getChildren();
for (FileObject fileObject : myActionsFolderKids) {
logger.info(fileObject.getName());
//Probably want to make this more robust,
//but the point is that here we find a particular Action:
if (fileObject.getName().contains(actionName)) {
try {
DataObject dob = DataObject.find(fileObject);
InstanceCookie ic = dob.getLookup().lookup(InstanceCookie.class);
if (ic != null) {
Object instance = ic.instanceCreate();
if (instance instanceof Action) {
Action a = (Action) instance;
return a;
}
}
} catch (Exception e) {
ErrorManager.getDefault().notify(ErrorManager.WARNING, e);
return null;
}
}
}
return null;
}
}
This is my Plugin Action which attaches the Debugger to the given remote address:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.netbeans.api.debugger.jpda.DebuggerStartException;
import org.netbeans.api.debugger.jpda.JPDADebugger;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.awt.ActionRegistration;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionID;
import org.python.util.PythonInterpreter;
#ActionID(category = "PSFActions", id = "de.mackaz.AttachDebugger")
#ActionRegistration(displayName = "#CTL_AttachDebuggerAction")
#ActionReferences({
#ActionReference(path = "Menu/Tools", position = 1800, separatorBefore = 1750, separatorAfter = 1850)
})
public final class AttachDebugger implements ActionListener {
private static final Logger logger = Logger.getLogger(AttachDebugger.class.getName());
public static final String ACTION_NAME="AttachDebugger";
#Override
public void actionPerformed(ActionEvent e) {
String ip;
if (!e.getActionCommand().contains("Attach Debugger")) {
ip = e.getActionCommand();
} else {
ip = lookupIP();
}
try {
logger.log(Level.INFO, "Attaching Debugger to IP {0}", ip);
JPDADebugger.attach(
ip,
9009,
new Object[]{null});
} catch (DebuggerStartException ex) {
int msgType = NotifyDescriptor.ERROR_MESSAGE;
String msg = "Failed to connect debugger to remote IP " + ip;
NotifyDescriptor errorDescriptor = new NotifyDescriptor.Message(msg, msgType);
DialogDisplayer.getDefault().notify(errorDescriptor);
}
}
}
Now i can attach the Netbeans debugger to a specific address by calling netbeans/bin/netbeans --debug 192.168.178.79