Second Test Method is having nullpointerexception error - eclipse

I am doing automation testing of an Ios app using appium server.
I have implemented two classes. First one is having UI elements finding attributes, actions and a constructor. And the other one is having test methods and driver configurations.
This is my first class that is LoginPage.java
public class LoginPage {
String orgIdentifer;
String personIdentifer;
String userPasswrod;
IOSDriver<IOSElement> driver;
public LoginPage() {
}
public LoginPage(IOSDriver<IOSElement> driver) {
this.driver = driver;
// PageFactory.initElements(new AppiumFieldDecorator(driver), this);
PageFactory.initElements(new AppiumFieldDecorator(driver), this);
}
public boolean validateLoginpage(){
boolean elements = false;
if(organizationIdentifier.isDisplayed()){
if(personIdentifier.isDisplayed()){
if(password.isDisplayed()){
if(loginButton.isDisplayed()){
elements = true;
}
}
}
}
else{
elements = false;
}
return elements;
}
int sum()
{
int a=5;
int b=6;
return a+b;
}
public void firstThreePopoClick()
{
firstPopUp.click();
secondPopUp.click();
thirdPopUp.click();
organizationIdentifier.sendKeys("testauto");
personIdentifier.sendKeys("manager");
password.sendKeys("123456");
//OKPopupBtn.click();
}
public boolean TestdoLoginWIthValues()
{
boolean element=false;
loginButton.click();
if(logoutDoneButtonWheel.isDisplayed())
{
element=true;
}
return element;
}
public boolean loginTestCase()
{
logoutDoneButtonWheel.click();
boolean check=false;
if(acceptPopupBtn.isDisplayed())
{
check=true;
}
else
{
check=false;
}
return check;
}
#FindBy(name = "Allow")
public MobileElement firstPopUp;
//#CacheLookup
// #FindBy(name = "Allow")
#FindBy(name = "OK")
public MobileElement secondPopUp;
#FindBy(name = "Ok")
public MobileElement thirdPopUp;
#FindBy(xpath = "/XCUIElementTypeApplication[#name=\"Human Focus Dev\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[2]/XCUIElementTypeTextField[1]")
public MobileElement organizationIdentifier;
#FindBy(xpath = "//XCUIElementTypeApplication[#name=\"Human Focus Dev\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[2]/XCUIElementTypeTextField[2]")
public MobileElement personIdentifier;
#FindBy(xpath = "//XCUIElementTypeApplication[#name=\"Human Focus Dev\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[2]/XCUIElementTypeSecureTextField")
public MobileElement password;
#FindBy(id = "Login")
public MobileElement loginButton;
#FindBy(xpath = "//XCUIElementTypeButton[#name=\"Done\"]")
public MobileElement logoutDoneButtonWheel;
#FindBy(name = "Accept")
public MobileElement acceptPopupBtn;
#CacheLookup
#FindBy(name = "Ok")
public MobileElement OKPopupBtn;
}
And this is my second class that is TestClass.java
class TesClass {
String appiumPort ="4723";
String serverIp ="127.0.0.1";
static IOSDriver<IOSElement> driver;
LoginPage lPage=null;
DesiredCapabilities cap;
#Order(1)
#Test
void test() throws MalformedURLException {
cap= new DesiredCapabilities();
cap.setCapability("deviceName", "Muhammad’s iPhone");
cap.setCapability("platformName", "iOS");
cap.setCapability("platformVersion","12.1.2");
cap.setCapability("automationName", "XCUITest");
cap.setCapability("app", "/Users/ahmsam/Downloads/MainApp-2.ipa");
cap.setCapability("xcodeOrgId","BNL4VQ2576");
cap.setCapability("xcodeSigningId","iPhone Developer");
cap.setCapability("udid","240476512a6dd29a2f82fc8211ef4ea1bf6b5891");
cap.setCapability("updateWDABundleId","5SN9XXLNWB.uk.org.humanfocus.WildCard.Dev");
String serverUrl = "http://" + serverIp + ":" + appiumPort + "/wd/hub";
driver = new IOSDriver<IOSElement>(new URL(serverUrl), cap);
driver.manage().timeouts().implicitlyWait(55,TimeUnit.SECONDS);
lPage=new LoginPage(driver);
lPage.firstThreePopoClick();
boolean check= lPage.TestdoLoginWIthValues();
// = lPage.loginTestCase();
Assert.assertTrue(check);
//fail("Not yet implemented");
}
#Order(2)
#Test
void test1()
{
System.out.println("came in test1 method");
boolean check1=lPage.TestdoLoginWIthValues();
System.out.println("Now here");
Assert.assertTrue(check1==true);
}
}
My first test case runs successfully but second test methods gives the following error.
i am using
Eclipse IDE : Version: 2019-06 (4.12.0)
Appium : Version 1.13.0 (1.13.0.20190505.5)
Junit 5
java.lang.NullPointerException
at TesClass.test1(TesClass.java:65)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:628)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:117)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:184)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:180)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:127)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:68)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)

Tests are executed separately one from each other.
In the second test, you forgot to initialize the lPage object on this line:
boolean check1=lPage.TestdoLoginWIthValues();
Before to do that, you should use the constructor for LoginPage class.

Related

javax.ejb.EJBTransactionRolledbackException : For keycloak user spi provider

Below is my pom.xml
<properties>
<keycloak.version>4.3.0.Final</keycloak.version>
<version.hibernate.javax.persistence>1.0.0.Final</version.hibernate.javax.persistence>
<version.jboss-ejb-api>1.0.0.Final</version.jboss-ejb-api>
</properties>
<dependencies>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-core</artifactId>
<version>${keycloak.version}</version>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-server-spi-private</artifactId>
<version>${keycloak.version}</version>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-server-spi</artifactId>
<version>${keycloak.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.3.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>${version.hibernate.javax.persistence}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.ejb</groupId>
<artifactId>jboss-ejb-api_3.2_spec</artifactId>
<version>${version.jboss-ejb-api}</version>
<scope>provided</scope>
</dependency>
</dependencies>
The exception that I am getting here is:
2018-09-08 16:36:12,303 WARN [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-4) SQL Error: 0, SQLState: null
2018-09-08 16:36:12,304 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-4) IJ031070: Transaction cannot proceed: STATUS_MARKED_ROLLBACK
2018-09-08 16:36:12,313 ERROR [org.jboss.as.ejb3.invocation] (default task-4) WFLYEJB0034: EJB Invocation failed on component NeemiyaUsersProvider for method public org.keycloak.models.UserModel com.neemiya.keycloak.userstoragespi.NeemiyaUsersProvider.getUserByUsername(java.lang.String,org.keycloak.models.RealmModel): javax.ejb.EJBTransactionRolledbackException: org.hibernate.exception.GenericJDBCException: could not prepare statement
at org.jboss.as.ejb3.tx.CMTTxInterceptor.handleInCallerTx(CMTTxInterceptor.java:160)
at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:257)
at org.jboss.as.ejb3.tx.CMTTxInterceptor.required(CMTTxInterceptor.java:334)
at org.jboss.as.ejb3.tx.CMTTxInterceptor.processInvocation(CMTTxInterceptor.java:240)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.ejb3.component.interceptors.CurrentInvocationContextInterceptor.processInvocation(CurrentInvocationContextInterceptor.java:41)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not prepare statement
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1692)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602)
at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:492)
at com.neemiya.keycloak.userstoragespi.NeemiyaUsersProvider.getUserByUsername(NeemiyaUsersProvider.java:76)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.as.ee.component.ManagedReferenceMethodInterceptor.processInvocation(ManagedReferenceMethodInterceptor.java:52)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.ejb3.component.invocationmetrics.ExecutionTimeInterceptor.processInvocation(ExecutionTimeInterceptor.java:43)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
package com.neemiya.keycloak.userstoragespi;
import java.util.UUID;
import javax.ejb.Local;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.jboss.logging.Logger;
import org.keycloak.component.ComponentModel;
import org.keycloak.credential.CredentialInput;
import org.keycloak.credential.CredentialInputValidator;
import org.keycloak.credential.CredentialModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.cache.CachedUserModel;
import org.keycloak.models.cache.OnUserCache;
import org.keycloak.storage.StorageId;
import org.keycloak.storage.UserStorageProvider;
import org.keycloak.storage.user.UserLookupProvider;
import com.neemiya.keycloak.userstoragespi.entity.UserAccountMapping;
import com.neemiya.keycloak.userstoragespi.entity.UserCredentialEntity;
import com.neemiya.keycloak.userstoragespi.entity.UserEntity;
import com.neemiya.keycloak.userstoragespi.utils.Crypto;
#Stateful(passivationCapable = false)
#Local(NeemiyaUsersProvider.class)
public class NeemiyaUsersProvider
implements UserStorageProvider, UserLookupProvider, CredentialInputValidator, OnUserCache {
private static final Logger logger = Logger.getLogger(NeemiyaUsersProvider.class);
public static final String PASSWORD_CACHE_KEY = UserAdapter.class.getName() + ".password";
private static final String GET_USER_FOR_USERNAME = "select uc from UserCredentialEntity uc where uc.username=:username";
private static final String GET_USER_ACCOUNT_MAPPING_FOR_OWNER = "select uam from UserAccountMapping uam where uam.userId = :userId and"
+ " uam.requestedByUserId =:userId and uam.role = com.neemiya.keycloak.userstoragespi.enums.ROLE.owner and "
+ " uam.request_status = com.neemiya.keycloak.userstoragespi.enums.REQUEST_STATUS.completed";
#PersistenceContext
protected EntityManager em;
protected ComponentModel model;
protected KeycloakSession session;
public void setModel(ComponentModel model) {
this.model = model;
}
public void setSession(KeycloakSession session) {
this.session = session;
}
#Override
public void close() {
}
#Override
public UserModel getUserById(String id, RealmModel realm) {
logger.info("getUserById: " + id);
try {
String persistenceId = StorageId.externalId(id);
UUID persistenceUUID = UUID.fromString(persistenceId);
UserCredentialEntity credentialEntity = em.find(UserCredentialEntity.class, persistenceUUID);
if (credentialEntity == null) {
logger.info("could not find user by id: " + id);
return null;
}
TypedQuery<UserAccountMapping> uamQuery = em.createQuery(GET_USER_ACCOUNT_MAPPING_FOR_OWNER,
UserAccountMapping.class);
uamQuery.setParameter("userId", credentialEntity.getUserEntity().getUserId());
UserAccountMapping uam = uamQuery.getSingleResult();
credentialEntity.setAccountId(uam.getAccountId());
return new UserAdapter(session, realm, model, credentialEntity);
} catch (Exception e) {
logger.error("Couldn't fetch user by id " + e.getMessage());
}
return null;
}
#Override
public UserModel getUserByUsername(String username, RealmModel realm) {
logger.info("getUserByUsername: " + username);
try {
TypedQuery<UserCredentialEntity> query = em.createQuery(GET_USER_FOR_USERNAME, UserCredentialEntity.class);
query.setParameter("username", username);
UserCredentialEntity credentialEntity = query.getSingleResult();
if (credentialEntity == null) {
logger.error("could not find username: " + username);
return null;
}
UserEntity entity = credentialEntity.getUserEntity();
if (entity == null) {
logger.error("Couldn't fetch user for given username ");
return null;
}
TypedQuery<UserAccountMapping> uamQuery = em.createQuery(GET_USER_ACCOUNT_MAPPING_FOR_OWNER,
UserAccountMapping.class);
uamQuery.setParameter("userId", entity.getUserId());
UserAccountMapping uam = uamQuery.getSingleResult();
if (uam == null) {
logger.error("Couldn't find an owner mapping for this user ");
return null;
}
credentialEntity.setAccountId(uam.getAccountId());
logger.info("Fetch USerCredentialEntity :: " + credentialEntity.toString());
return new UserAdapter(session, realm, model, credentialEntity);
} catch (Exception e) {
logger.error("Couldn't validate user credentials " + e.getMessage());
}
return null;
}
#Override
public UserModel getUserByEmail(String email, RealmModel realm) {
return null;
}
#Override
public void onCache(RealmModel realm, CachedUserModel user, UserModel delegate) {
String password = ((UserAdapter) delegate).getPassword();
if (password != null) {
user.getCachedWith().put(PASSWORD_CACHE_KEY, password);
}
}
#Override
public boolean supportsCredentialType(String credentialType) {
return CredentialModel.PASSWORD.equals(credentialType);
}
#Override
public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) {
return supportsCredentialType(credentialType) && getPassword(user) != null;
}
#Override
public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) {
if (!supportsCredentialType(input.getType()) || !(input instanceof UserCredentialModel))
return false;
try {
UserCredentialModel cred = (UserCredentialModel) input;
String password = getPassword(user);
String encryptedPassword = Crypto.encryptSHA1(cred.getValue());
if (password != null) {
if (password.equals(encryptedPassword)) {
return true;
} else {
UserModel model = getUserByUsername(user.getUsername(), realm);
String currentPassword = getPassword(model);
boolean isPasswordValid = currentPassword.equals(encryptedPassword);
if (isPasswordValid) {
logger.info(
"It appears user has changed his password.Invalidating Cache and getting latest password from db");
((CachedUserModel) user).getCachedWith().put(PASSWORD_CACHE_KEY, currentPassword);
return isPasswordValid;
}
}
}
} catch (Exception e) {
logger.error("Couldn't validate user credentials " + e.getMessage());
}
return false;
}
public String getPassword(UserModel user) {
String password = null;
if (user instanceof CachedUserModel) {
password = (String) ((CachedUserModel) user).getCachedWith().get(PASSWORD_CACHE_KEY);
} else if (user instanceof UserAdapter) {
password = ((UserAdapter) user).getPassword();
}
return password;
}
public EntityManager getEm() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
}

Resource Access Exception

When trying to resolve the test described in Where exactly is the NullPointer Exception?, I used a seemingly simpler approach, being the resource test the next:
public class CustomerResourceFunctionalTesting {
private static final String SERVER_URL = "http://localhost:8080/api/v0/";
#Rule
public ExpectedException thrown = ExpectedException.none();
private int createCustomer(String name) {
CustomerDto customerDto = new CustomerDto(name, name + " address");
return new RestBuilder2<Integer>(SERVER_URL).path(CustomerResource.CUSTOMERS)
.body(customerDto).clazz(Integer.class).post().build();
}
private int createCustomer() {
return this.createCustomer("customer1");
}
#Test
public void testReadCustomers() {
List<CustomerDto> customerDtoList = Arrays.asList(new RestBuilder2<CustomerDto[]>
(SERVER_URL).path(CustomerResource.CUSTOMERS).clazz(CustomerDto[].class).get().build());
assertEquals(0, customerDtoList.size());
int id = this.createCustomer();
customerDtoList = Arrays.asList(new RestBuilder2<CustomerDto[]>
(SERVER_URL).path(CustomerResource.CUSTOMERS).clazz(CustomerDto[].class)
.get().build());
assertEquals(1, customerDtoList.size());
this.deleteCustomer(id);
}
private void deleteCustomer(int id) {
new RestBuilder<Object>
(SERVER_URL).path(CustomerResource.CUSTOMERS).path(CustomerResource.CUSTOMER_ID)
.expand(id).delete().build();
}
}
And the RestBuilder a bit different:
public class RestBuilder2<T> {
private RestTemplate restTemplate = new RestTemplate();
private String uri;
private List<Object> expandList;
private Map<String, String> headerValues;
private String authorization = null;
private Object body = null;
private MultiValueMap<String, String> params;
private Class<T> clazz;
private HttpMethod method;
public RestBuilder2(String serverUri) {
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
this.uri = serverUri;
this.expandList = new ArrayList<>();
headerValues = new HashMap<>();
params = new HttpHeaders();
}
public RestBuilder2<T> path(String path) {
this.uri = this.uri + path;
return this;
}
public RestBuilder2<T> expand(Object... values) {
for (Object value : values) {
this.expandList.add(value);
}
return this;
}
public RestBuilder2<T> pathId(int path) {
this.uri = this.uri + "/" + path;
return this;
}
public RestBuilder2<T> pathId(String path) {
this.uri = this.uri + "/" + path;
return this;
}
public RestBuilder2<T> authorization(String authorizationValue) {
this.authorization = authorizationValue;
return this;
}
public RestBuilder2<T> basicAuth(String nick, String pass) {
String auth = nick + ":" + pass;
String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
String authHeader = "Basic " + encodedAuth;
this.authorization = authHeader;
return this;
}
public RestBuilder2<T> param(String key, String value) {
this.params.add(key, value);
return this;
}
public RestBuilder2<T> header(String key, String value) {
this.headerValues.put(key, value);
return this;
}
public RestBuilder2<T> body(Object body) {
this.body = body;
return this;
}
public RestBuilder2<T> notError() {
restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
protected boolean hasError(HttpStatus statusCode) {
return false;
}
});
return this;
}
public RestBuilder2<T> clazz(Class<T> clazz) {
this.clazz = clazz;
return this;
}
private HttpHeaders headers() {
HttpHeaders headers = new HttpHeaders();
for (String key : headerValues.keySet()) {
headers.set(key, headerValues.get(key));
}
if (authorization != null) {
headers.set("Authorization", authorization);
}
return headers;
}
private URI uri() {
UriComponents uriComponents;
if (params.isEmpty()) {
uriComponents = UriComponentsBuilder.fromHttpUrl(uri).build();
} else {
uriComponents = UriComponentsBuilder.fromHttpUrl(uri).queryParams(params).build();
}
if (!expandList.isEmpty()) {
uriComponents = uriComponents.expand(expandList.toArray());
}
return uriComponents.encode().toUri();
}
public T build() {
if (body != null && !method.equals(HttpMethod.GET)) {
return restTemplate.exchange(this.uri(), method, new HttpEntity<Object>(body, this.headers()), clazz).getBody();
} else {
return restTemplate.exchange(this.uri(), method, new HttpEntity<Object>(this.headers()), clazz).getBody();
}
}
public RestBuilder2<T> post() {
this.method = HttpMethod.POST;
return this;
}
public RestBuilder2<T> get() {
this.method = HttpMethod.GET;
return this;
}
public RestBuilder2<T> put() {
this.method = HttpMethod.PUT;
return this;
}
public RestBuilder2<T> patch() {
this.method = HttpMethod.PATCH;
return this;
}
public RestBuilder2<T> delete() {
this.method = HttpMethod.DELETE;
return this;
}
}
But then I take an error whose trace is:
org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:8080/api/v0/customers": Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:674)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:636)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:557)
at account.persistence.resources.RestBuilder2.build(RestBuilder2.java:143)
at account.persistence.resources.CustomerResource2FunctionalTesting.testReadCustomers(CustomerResource2FunctionalTesting.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Caused by: org.apache.http.conn.HttpHostConnectException: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:159)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:373)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:381)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:237)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:111)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
at org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpComponentsClientHttpRequest.java:89)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:660)
... 29 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
The rest of implied parts of the application is the same as the indicated in the link post, except for not using any RestService.
I think that, in this case, I could not get the NullPointerException, but before I need to resolve the ResourceAccess Exception.

Getting "No Persistence provider for EntityManager named" when Maven build is run with Junit testcases

When running the maven build with Junit getting "No Persistence provider for EntityManager named" error.Not able to identify what is missing in my code.
Main class:
public class ApprovalHistory {
#PersistenceContext(unitName = "Approval_History")
private Logger logger = LoggerFactory.getLogger(ApprovalHistory.class);
public EntityManagerFactory emfactory = null;
final String JDBC_URL_H2DB = "jdbc:h2:file:./APApproval/ApprovalHistoryH2DB";
final String JDBC_USERNAME_H2DB = "";
final String JDBC_PASSWORD_H2DB = "";
final String JDBC_DRIVER_SQL = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
final String JDBC_DRIVER_H2 = "org.h2.Driver";
final String JDBC_DRIVER_HSQL = "org.hsqldb.jdbc.JDBCDriver";
final String PERSISTANCE_UNIT_NAME = "Approval_History";
final String SELECT_BO_TABLE = "SELECT bobj FROM BusinessObjectTable bobj where bobj.docId =:";
final String SELECT_COMMENT_TABLE = "SELECT comment FROM CommentTable comment where comment.actionTable.id IN :";
final String SELECT_REASON_TABLE = "SELECT reason FROM ReasonTable reason where reason.actionTable.id IN :";
public ApprovalHistory()
{
try {
createEntityManagerFactory();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void insertData(List<ApprovalHistoryModel> historyList){
if(historyList != null && !historyList.isEmpty())
{
EntityManager entitymanager = null;
try
{
entitymanager = getEntityManager();
entitymanager.getTransaction().begin();
ApprovalHistoryModel firstItem = historyList.get(0);
ActionTable a = new ActionTable(firstItem.actionType, firstItem.tenantId, firstItem.comment, firstItem.reason);
for(ApprovalHistoryModel h : historyList)
{
a.getBusinessObjects().add(new BusinessObjectTable(h.userName, h.taskId, h.docId, h.objectIdentifier1, h.objectIdentifier2, h.objectIdentifier3,h.tenantId));
}
entitymanager.persist(a);
entitymanager.getTransaction().commit();
}
catch (RuntimeException e) {
if(entitymanager!=null && entitymanager.getTransaction().isActive()) {
entitymanager.getTransaction().rollback();
}
throw e;
}
finally{
closeEntityManager(entitymanager);
}
}
}
public List<ApprovalHistoryModel> getApprovalHistory(String docID) throws Exception
{
logger.info("=ApprovalConnector=: start of getApprovalHistory()");
List<ApprovalHistoryModel> historyModels = new ArrayList<ApprovalHistoryModel>();
if(docID!=null && !docID.isEmpty()) {
EntityManager entitymanager = null;
try
{
entitymanager = getEntityManager();
TypedQuery<BusinessObjectTable> bobjquery = entitymanager.createQuery(SELECT_BO_TABLE+"DocID ",BusinessObjectTable.class);
bobjquery.setParameter("DocID", docID);
List<BusinessObjectTable> bobjs = bobjquery.getResultList();
if(bobjs!=null){
for (BusinessObjectTable bobj : bobjs) {
ActionTable a = bobj.getActionTable();
ApprovalHistoryModel history = new ApprovalHistoryModel();
history.docId = bobj.getDocId();
history.taskId = bobj.getApprovalItemId();
history.userName = bobj.getUserName();
logger.debug("=ApprovalConnector=: getApprovalHistory(): documentID - "+bobj.getDocId());
history.actionType = a.getActionType();
logger.debug("=ApprovalConnector=: getApprovalHistory(): actionType - "+ history.actionType);
history.actionDate = ISODateTimeFormat.dateTime().print(new DateTime(a.getActionDate()));
history.objectIdentifier1 = bobj.getObjectIdentifier1();
history.objectIdentifier2=bobj.getObjectIdentifier2();
history.objectIdentifier3 = bobj.getObjectIdentifier3();
history.tenantId = a.getTenantId();
history.comment = a.getComment()!=null?a.getComment().getComment():"";
history.reason = a.getReason()!=null?a.getReason().getReason():"";
historyModels.add(history);
}
}
logger.info("=ApprovalConnector=: end of getApprovalHistory()");
}
finally{
closeEntityManager(entitymanager);
}
}
return historyModels;
}
public void createEntityManagerFactory() throws Exception
{
Map<String, String> persistenceMap = new HashMap<String, String>();
String jdbcDriver = getJdbcDriverName(JDBC_URL_H2DB);
persistenceMap.put("javax.persistence.jdbc.driver", jdbcDriver);
persistenceMap.put("javax.persistence.jdbc.url", JDBC_URL_H2DB);
if (!JDBC_USERNAME_H2DB.isEmpty()) {
persistenceMap.put("javax.persistence.jdbc.user", JDBC_USERNAME_H2DB);
}
if (!JDBC_PASSWORD_H2DB.isEmpty()) {
persistenceMap.put("javax.persistence.jdbc.password", JDBC_PASSWORD_H2DB);
}
persistenceMap.put("eclipselink.session-name",System.currentTimeMillis() + "");
this.emfactory = Persistence.createEntityManagerFactory(PERSISTANCE_UNIT_NAME, persistenceMap);
}
public EntityManager getEntityManager()
{
EntityManager entitymanager = this.emfactory.createEntityManager();
return entitymanager;
}
public void closeEntityManager(EntityManager entitymanager)
{
if(entitymanager!=null)
entitymanager.close();
}
public void closeEntityManagerFactory()
{
if(this.emfactory!=null)
this.emfactory.close();
}
private String getJdbcDriverName(String jdbcUrl) {
if (jdbcUrl.startsWith("jdbc:sqlserver"))
return JDBC_DRIVER_SQL;
if (jdbcUrl.startsWith("jdbc:h2"))
return JDBC_DRIVER_H2;
if (jdbcUrl.startsWith("jdbc:hsqldb"))
return JDBC_DRIVER_HSQL;
return null;
}
Test Calss:
public class ApprovalHistoryTest {
ApprovalHistory approvalHistory = new ApprovalHistory();
#Before
public void setUp() throws Exception {
List<ApprovalHistoryModel> actionHistoryModels = new ArrayList<ApprovalHistoryModel>();
for(int i=0;i<=2;i++){
ApprovalHistoryModel history = new ApprovalHistoryModel();
String comment = "comment no. " + i;
String reason = "reason no. " + i;
String userName = "User" + i;
history.taskId = "321YZ61_0026CV7Z0000XB" + i;
history.actionDate = ISODateTimeFormat.dateTime().print(new DateTime(new Date()));
history.actionType = i;
history.comment = comment.trim();
history.docId = "321YZ61_026CV7Z0000TD" + i;
history.userName = userName;
history.reason = reason;
actionHistoryModels.add(history);
}
approvalHistory.insertData(actionHistoryModels);
}
#After
public void tearDown() throws Exception {
DeleteApprovalHistory history = new DeleteApprovalHistory();
try{
history.purgeRecord(0,"DAYS");
approvalHistory.closeEntityManagerFactory();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Test()
public void test() {
//ApprovalHistory approvalHistory = new ApprovalHistory();
List<ApprovalHistoryModel> historyList = new ArrayList<ApprovalHistoryModel>();
for(int i=0;i<=2;i++){
ApprovalHistoryModel history = new ApprovalHistoryModel();
try {
Thread.sleep(1000);
historyList=approvalHistory.getApprovalHistory(history.docId);
assertEquals("321YZ61_0026CV7Z0000XB" + i,historyList.get(i).taskId);`enter code here`
assertEquals("comment no. " + i,historyList.get(i).comment);
assertEquals("User" + i,historyList.get(i).userName);
assertEquals("reason no. " + i,historyList.get(i).reason);
assertEquals(i,historyList.get(i).actionType);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="Approval_History" transaction-type="RESOURCE_LOCAL">
<class>com.perceptivesoftware.apapproval.history.ActionTable</class>
<class>com.perceptivesoftware.apapproval.history.BusinessObjectTable</class>
<class>com.perceptivesoftware.apapproval.history.CommentTable</class>
<class>com.perceptivesoftware.apapproval.history.ReasonTable</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<properties>
<property name="eclipselink.ddl-generation" value="create-or-extend-tables" />
<property name="eclipselink.logging.level.sql" value="FINE"/>
<property name="eclipselink.logging.parameters" value="true"/>
<property name="eclipselink.multitenant.tenants-share-cache" value="true" />
</properties>
</persistence-unit>
</persistence>
Error::
Running ApprovalHistoryTest javax.persistence.PersistenceException: No
Persistence provider for EntityManager named Approval_History at
javax.persistence.Persistence.createEntityManagerFactory(Unknown
Source) at
com.perceptivesoftware.apapproval.history.ApprovalHistory.createEntityManagerFactory(ApprovalHistory.java:167)
at
com.perceptivesoftware.apapproval.history.ApprovalHistory.(ApprovalHistory.java:48)
at ApprovalHistoryTest.(ApprovalHistoryTest.java:20) at
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at
org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:187)
at
org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:236)
at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at
org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:233)
at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231) at
org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60) at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229) at
org.junit.runners.ParentRunner.access$000(ParentRunner.java:50) at
org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222) at
org.junit.runners.ParentRunner.run(ParentRunner.java:300) at
org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at
org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at
org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497) at
org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at
org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at
org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at
org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at
org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
javax.persistence.PersistenceException: No Persistence provider for
EntityManager named Approval_History at
javax.persistence.Persistence.createEntityManagerFactory(Unknown
Source) at
com.perceptivesoftware.apapproval.history.ApprovalHistory.createEntityManagerFactory(ApprovalHistory.java:167)
at
com.perceptivesoftware.apapproval.history.ApprovalHistory.(ApprovalHistory.java:48)
at
com.perceptivesoftware.apapproval.history.DeleteApprovalHistory.purgeRecord(DeleteApprovalHistory.java:46)
at ApprovalHistoryTest.tearDown(ApprovalHistoryTest.java:50) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497) at
org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at
org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:36)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263) at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231) at
org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60) at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229) at
org.junit.runners.ParentRunner.access$000(ParentRunner.java:50) at
org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222) at
org.junit.runners.ParentRunner.run(ParentRunner.java:300) at
org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at
org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at
org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497) at
org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at
org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at
org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at
org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at
org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
You've annotated the wrong attribute:
#PersistenceContext(unitName = "Approval_History")
private Logger logger = LoggerFactory.getLogger(ApprovalHistory.class);
Should be:
#PersistenceContext(unitName = "Approval_History")
public EntityManager em;
The #PersistenceContext annotation injects an EntityManager into your code, which is created from the EntityManagerFactory associated with the persistence unit that you specify ("Approval_History" in your case).

Cannot play music using MusicService in Fragment

I have a fragment that gives me the listView of all songs that that I have stored on my phone. When I click on a particular song in my list, I should be able to play it using a MusicService.
This fragment (menu2_Fragment) is initialized in an ActionBarActivity when a particular drawer item is selected. See following code:
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch(position){
case 0:
objFragment = new menu1_Fragment();
getSupportActionBar().setTitle("Scan for Users");
break;
case 1:
objFragment = new menu2_Fragment();
getSupportActionBar().setTitle("Your Music");
// objFragment = new MyMusicFragment();
break;
case 2:
objFragment = new menu3_Fragment();
getSupportActionBar().setTitle("Popular Music");
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
This is the Fragment code:
package com.example.cs446.soundscope;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.MediaController;
import com.example.cs446.soundscope.Adapter.SongAdapter;
import com.example.cs446.soundscope.data.Song;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* Created by val on 27/02/15.
*/
public class menu2_Fragment extends Fragment implements MediaController.MediaPlayerControl{
View rootview;
private ArrayList<Song> songList;
private ListView songView;
private MusicService musicSrv;
private Intent playIntent;
private boolean musicBound=false;
private MusicController controller;
private boolean paused=false;
private boolean playbackPaused=false;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
rootview = inflater.inflate(R.layout.activity_main,container, false);
songView = (ListView)rootview.findViewById(R.id.song_list);
songList = new ArrayList<Song>();
getSongList();
//sort all of the songList by title
Collections.sort(songList, new Comparator<Song>() {
//function that does the sorting
#Override
public int compare(Song lhs, Song rhs) {
return lhs.getTitle().compareTo(rhs.getTitle());
}
});
SongAdapter songAdt = new SongAdapter(getActivity(),songList);
songView.setAdapter(songAdt);
setController();
//startActivity(new Intent(this, MainActivity.class));
return rootview;
}
//get the song information for your filesystem
public void getSongList(){
//use the contentResolver to retrieve the uri for the music file
//a cursor instance is created with the contentResolver
ContentResolver musicResolver = this.getActivity().getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
//store the songs into the song list array list
if(musicCursor!=null && musicCursor.moveToFirst()){
//get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new Song(thisId, thisTitle, thisArtist));
}
while (musicCursor.moveToNext());
}
}
public void songPicked(View view){
musicSrv.setSong(Integer.parseInt(view.getTag().toString()));
musicSrv.playSong();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
//set the controller up
private void setController(){
controller = new MusicController(getActivity());
controller.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
playNext();
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
playPrev();
}
});
controller.setMediaPlayer(this);
controller.setAnchorView(getActivity().findViewById(R.id.song_list));
controller.setEnabled(true);
}
#Override
public void onStart() {
super.onStart();
if(playIntent==null){
playIntent = new Intent(getActivity(), MusicService.class);
this.getActivity().bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
this.getActivity().startService(playIntent);
}
}
#Override
public void onPause(){
super.onPause();
paused=true;
}
#Override
public void onResume(){
super.onResume();
if(paused){
setController();
paused=false;
}
}
#Override
public void onStop() {
controller.hide();
super.onStop();
}
//connect to the service
private ServiceConnection musicConnection = new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.MusicBinder binder = (MusicService.MusicBinder)service;
//get service
musicSrv = binder.getService();
//pass list
musicSrv.setList(songList);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
//play next
private void playNext(){
musicSrv.playNext();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
//play previous
private void playPrev(){
musicSrv.playPrev();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
#Override
public void onDestroy() {
this.getActivity().stopService(playIntent);
musicSrv=null;
super.onDestroy();
}
#Override
public void start() {
musicSrv.go();
}
#Override
public void pause() {
playbackPaused=true;
musicSrv.pausePlayer();
}
#Override
public int getDuration() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getDur();
else return 0;
}
#Override
public int getCurrentPosition() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getPosn();
else return 0;
}
#Override
public void seekTo(int pos) {
musicSrv.seek(pos);
}
#Override
public boolean isPlaying() {
if(musicSrv!=null && musicBound)
return musicSrv.isPng();
return false;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
}
When I click on an item in the ListView, instead of playing the song my app crashes and I receive the following error message:
03-02 00:46:29.142 6485-6485/com.example.cs446.soundscope E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.cs446.soundscope, PID: 6485
java.lang.IllegalStateException: Could not find a method songPicked(View) in the activity class com.example.cs446.soundscope.ListNearbyUsers for onClick handler on view class android.widget.LinearLayout
at android.view.View$1.onClick(View.java:3994)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NoSuchMethodException: songPicked [class android.view.View]
at java.lang.Class.getMethod(Class.java:664)
at java.lang.Class.getMethod(Class.java:643)
at android.view.View$1.onClick(View.java:3987)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
The playing music functionality works fine when it's not implemented inside a Fragment, but instead implemented inside an Activity. Has anyone seen an error like this before?
It means that you didn't declare andoid:onClick="songPicked" in your fragment layout.
And I know you are coming from tutsplus :)

"java.lang.NullPointerException" Error when trying to insert data to sqlite (Android)

I face the error :
1566-1566/com.example.rom.romproject E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.rom.romproject, PID: 1566
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3823)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3818)
            at android.view.View.performClick(View.java:4438)
            at android.view.View$PerformClick.run(View.java:18422)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.rom.romproject.ContactView.contactFavorite(ContactView.java:37)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at android.view.View$1.onClick(View.java:3818)
            at android.view.View.performClick(View.java:4438)
            at android.view.View$PerformClick.run(View.java:18422)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
This happens when im clicking on a button i created.
The button purpose is to insert Data into my sql table.
The SQL class :
public class sqlDatabaseAdapter
{
sqlHelper helper;
public sqlDatabaseAdapter(Context context)
{
helper = new sqlHelper(context);
}
public long insertData(String name, String phone)
{
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues content = new ContentValues();
content.put(sqlHelper.NAME, name);
content.put(sqlHelper.PHONE, phone);
return db.insert(helper.TABLE_NAME, null, content);
}
static class sqlHelper extends SQLiteOpenHelper
{
static final String DATABASE_NAME = "ContactDB";
static final String TABLE_NAME = "Favorites";
static final int DB_VERSION = 1;
static final String UID = "_id";
static final String NAME = "Name";
static final String PHONE = "Phone";
static final String CREATE_TABLE = "CREATE TABLE "+ TABLE_NAME +" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255), "+PHONE+" VARCHAR(255));";
static final String DROP_TABLE = "DROP TABLE IF EXISTS"+TABLE_NAME;
private Context context;
public sqlHelper(Context context)
{
super(context, DATABASE_NAME, null, DB_VERSION);
this.context = context;
Message.Message(context, "Constructor Called");
}
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(CREATE_TABLE);
Message.Message(context, "onCreate Called");
} catch( SQLException e)
{
Message.Message(context, "" + e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
try {
db.execSQL(DROP_TABLE);
onCreate(db);
Message.Message(context, "OnUpgrade Called");
} catch(SQLException e)
{
Message.Message(context, "" + e);
}
}
}
}
Now, im not rly sure at the source of the problem , so i will post both of my activites.
Btw : the info im trying to insert to the SQL is a contact name and phone
(that i get from the main activity list view).
Main Activity ( List view of phone contacts ) :
public class MainActivity extends ListActivity {
ListView l;
Cursor cursor;
SimpleCursorAdapter listAdapter;
sqlDatabaseAdapter helper;
#Override
public int getSelectedItemPosition()
{
return super.getSelectedItemPosition();
}
#Override
public long getSelectedItemId()
{
return super.getSelectedItemId();
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
startManagingCursor(cursor);
String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID};
int[] to = {android.R.id.text1,android.R.id.text2};
listAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2,cursor,from,to);
setListAdapter(listAdapter);
l = getListView();
l.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
helper = new sqlDatabaseAdapter(this);
helper.helper.getWritableDatabase();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
TextView _tempName= (TextView)v.findViewById(android.R.id.text1);
String _temp = _tempName.getText().toString();
TextView _tempPhone = (TextView)v.findViewById(android.R.id.text2);
String _temp2 = _tempPhone.getText().toString();
Intent intent = new Intent(this, ContactView.class);
intent.putExtra("contactName", _temp);
intent.putExtra("contactPhone", _temp2);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The second activity (where the button is ) :
public class ContactView extends ActionBarActivity {
Button _Call;
Button _Favorite;
FavoriteContact contact = new FavoriteContact();
sqlDatabaseAdapter helper;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_view);
_Call = (Button)findViewById(R.id.bCall);
_Favorite = (Button)findViewById(R.id.bFavorite);
contact.setName(getIntent().getExtras().getString("contactName"));
contact.setPhone(getIntent().getExtras().getString("contactPhone"));
setTitle(contact.getName());
}
public void contactFavorite(View view)
{
long id = 0L;
id = helper.insertData(contact.getName(), contact.getPhone());
/*
if( id < 0)
{
Message.Message(this, "Unsuccessful");
}
else
{
Message.Message(this, "Successfully inserted to favorite contacts ");
}
*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_contact_view, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Contact class i created and FavoriteContact class :
(favoritecontact extends Contact)
public class Contact
{
private String Name = null;
private String Phone = null;
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
public class FavoriteContact extends Contact
{
private Boolean isFavorite;
public Boolean getIsFavorite() {
return isFavorite;
}
public void setIsFavorite(Boolean isFavorite) {
this.isFavorite = isFavorite;
}
}
i think i gave everything i need...
sorry for my bad english and its my first time posting here so i dont rly know how it works :D
thanks for every bit of help .
The variable helper is never initialized in ContactView.