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

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).

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.

Use JMockit test the RESTful API,RestTemplate,error missing invocation

I am learning to use the JMockit to test my Restful API.The missing invocation error is abusing me.
The Restful API:
#RestController
public class AgentInfoRest {
#Autowired
AgentInfoRepository agentInfoRepository;
private Logger logger = LoggerFactory.getLogger(AgentInfoRest.class);
#RequestMapping("/allagentInfo")
RestResponse getAllAgentInfo()
{
RestResponse restResponse = new RestResponse();
logger.info("getAllAgentInfo has no request parameter");
Collection<AgentInfo> result = agentInfoRepository.getAllAgents();
if(result.isEmpty())
{
restResponse.setRetCode(-1);
restResponse.setRetMsg("Request success,no such record in db");
}
restResponse.setResult(result);
return restResponse;
}
}
The Test Class:
public class AgentInfoRestTest {
String host = "http://127.0.0.1:8080";
#Test
public void getAllAgentInfoTest(#Mocked final AgentInfoRepository agentInfoRepository) {
RestTemplate restTemplate = new RestTemplate();
RestResponse restResponse = new RestResponse();
AgentInfoRest agentInfoRest = new AgentInfoRest();
new StrictExpectations() {
{
agentInfoRepository.getAllAgents(); result = null; times = 1;
}
};
String url = "/allagentInfo";
ResponseEntity<RestResponse> result = restTemplate.getForEntity(host + url, RestResponse.class);
new FullVerifications() {
{
}
};
}
}
The Error:
mockit.internal.MissingInvocation: Missing invocation of:
com.egoo.dao.repository.freelink.AgentInfoRepository#getAllAgents()
on mock instance: com.egoo.dao.repository.freelink.$Impl_AgentInfoRepository#50a7bc6e
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:253)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: Missing invocation
at com.egoo.dao.rest.freelink.AgentInfoRestTest$1.(AgentInfoRestTest.java:33)
at com.egoo.dao.rest.freelink.AgentInfoRestTest.getAllAgentInfoTest(AgentInfoRestTest.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.lang.reflect.Method.invoke(Method.java:498)
... 7 more

JBoss-A-MQ encountered an UnknownHostException in JMS messaging application

I have a sample JMS messaging application as shown in below snippet. When I executing the program (specifically when starting the connection) I get an UnknowHostException.
The reason for the exception is clientid property get's null.
Application:
public class MessagingTestApp {
private static final String MY_JMS_CONNECTION_FACTORY_NAME = "myJmsFactory";
private static final String EXCHANGE_NAME = "topicExchange";
private static final String JNDI_PROPERTIES_FILE_NAME = "jndi.properties";
private static final String COULD_NOT_LOAD_JNDI_PROPERTIES_MESSAGE = "Could not load JNDI properties....";
private static final boolean NON_TRANSACTED = false;
private static final Logger LOG = Logger.getLogger(MessagingTestApp.class);
public MessagingTestApp() {}
public static void main(String[] args) {
MessagingTestApp messagingTestApp = new MessagingTestApp();
messagingTestApp.runTest();
}
private void runTest() {
try {
Properties properties = new Properties();
properties.load(loadPropertiesFile());
Context context = new InitialContext(properties);
ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup(MY_JMS_CONNECTION_FACTORY_NAME);
Connection connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
Destination destination = (Destination) context.lookup(EXCHANGE_NAME);
MessageProducer messageProducer = session.createProducer(destination);
MessageConsumer messageConsumer = session.createConsumer(destination);
TextMessage message = session.createTextMessage("Hello JMS!");
messageProducer.send(message);
message = (TextMessage) messageConsumer.receive();
System.out.println(message.getText());
connection.close();
context.close();
} catch (Exception e) {
LOG.error(e);
e.printStackTrace();
}
}
private InputStream loadPropertiesFile() {
Thread currentThread = Thread.currentThread();
ClassLoader contextClassLoader = currentThread.getContextClassLoader();
InputStream propertiesStream = contextClassLoader.getResourceAsStream(JNDI_PROPERTIES_FILE_NAME);
if (propertiesStream != null) {
return propertiesStream;
} else {
System.out.println(COULD_NOT_LOAD_JNDI_PROPERTIES_MESSAGE);
return null;
}
}
}
JNDI properties file:
java.naming.factory.initial = org.apache.qpid.amqp_1_0.jms.jndi.PropertiesFileInitialContextFactory
java.naming.provider.url = src/main/resources/jndi.properties
connectionfactory.myJmsFactory = amqp://admin:admin#clientid/test?
brokerlist = 'tcp://localhost:5672'
destination.topicExchange = amq.topic
Stack-trace:
javax.jms.JMSException: java.net.UnknownHostException: clientid
at org.apache.qpid.amqp_1_0.jms.impl.ConnectionImpl.connect(ConnectionImpl.java:112)
at org.apache.qpid.amqp_1_0.jms.impl.ConnectionImpl.start(ConnectionImpl.java:266)
at com.adc.efg.MessagingTestApp.runTest(MessagingTestApp.java:39)
at com.adc.efg.MessagingTestApp.main(MessagingTestApp.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: org.apache.qpid.amqp_1_0.client.ConnectionException: java.net.UnknownHostException: clientid
at org.apache.qpid.amqp_1_0.client.Connection.<init>(Connection.java:271)
at org.apache.qpid.amqp_1_0.client.Connection.<init>(Connection.java:135)
at org.apache.qpid.amqp_1_0.jms.impl.ConnectionImpl.connect(ConnectionImpl.java:105)
... 8 more
Caused by: java.net.UnknownHostException: clientid
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at org.apache.qpid.amqp_1_0.client.Connection.<init>(Connection.java:159)
... 10 more
I'm new to both JBoss-AMQ and JMS. Much appreciated if anyone can point me out where did I go wrong.
Problem was in JNDI properties file. It should be like below,
java.naming.factory.initial = org.apache.qpid.amqp_1_0.jms.jndi.PropertiesFileInitialContextFactory
java.naming.provider.url = src/main/resources/jndi.properties
connectionfactory.myJmsFactory = amqp://admin:admin#localhost/test?
brokerlist = 'tcp://localhost:5672'
destination.topicExchange = amq.topic

Struts2 : dynamic link redirects?

I'm a newbie in Struts,
I use a java class that generates a algortihme an HTML file that I store locally.
Is it possible to create a link in my action that redirects to the temporary file in case of success of the action?
This is my action.java class:
String databases;
String sequence;
String algoUsed;
String maxTarget;
String wordSize;
String name;
String sequenceFasta;
boolean lowComplexity;
private String url;
public String getUrl()
{
return url;
}
public String getAlgoUsed() {
return algoUsed;
}
public void setAlgoUsed(String algoUsed) {
this.algoUsed = algoUsed;
}
public String getDatabases() {
return databases;
}
public void setDatabases(String databases) {
this.databases = databases;
}
public String getWordSize() {
return wordSize;
}
public void setWordSize(String wordSize) {
this.wordSize = wordSize;
}
public boolean isLowComplexity() {
return lowComplexity;
}
public void setLowComplexity(boolean lowComplexity) {
this.lowComplexity = lowComplexity;
}
public String getMaxTarget() {
return maxTarget;
}
public void setMaxTarget(String maxTarget) {
this.maxTarget = maxTarget;
}
public String getSequence() {
return sequence;
}
public void setSequence(String sequence) {
this.sequence = sequence;
}
File blast = new File("C:\\dmif-blast\\web\\blast.xml");
File directory = new File("C:\\dmif-blast\\web\\blast\\");
public String commandBlastN() throws Exception{
try {
blast.delete();
File blasthtml = File.createTempFile("blast_", ".html",directory);
ProcessBuilder pb = new ProcessBuilder(
this.blastAllPath,
"-task", "blastn",
"-db", blastDB,
"-query", fasta.getAbsolutePath(),
"-outfmt", "5",
"-word_size", wordSize,
"-num_alignments", maxTarget,
"-num_descriptions", maxTarget,
"-out", blast.getAbsolutePath());
Process proc = pb.start();
System.out.println(pb.command());
if (proc.waitFor() != 0) {
throw new RuntimeException("error occured");
}
} catch (Exception err) {
throw new RuntimeException(err);
}
InputStream in = new FileInputStream(blast);
FileOutputStream out = new FileOutputStream(blasthtml);
out.write(BlastXML2HTML.toHTML(in).getBytes());
out.close();
System.out.println("success......");
url = blasthtml.getCanonicalPath();
return SUCCESS;
}
}
and my stuts.xml
<action name="blastn" class="com.ncbi.blast.beanAction.ncbiBlastNAction" method="commandBlastN">
<interceptor-ref name="token"/>
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="execAndWait"/>
<result name="wait">wait.jsp</result>
<result name="error">blastn.jsp</result>
<result name="invalid.token">blastn.jsp</result>
<result name="success" >${url}</result>
</action>
I have a error
"The requested resource (/dmif-blast/C:/dmif-blast/web/blast/blast_7632426713872140252.html) is not available."
thanks for the help
EDIT :
thanks for the solution Tommi, but it doesn't work, now I have a new error:
Stacktraces java.lang.RuntimeException: java.io.IOException: The system cannot find the path specified com.ncbi.blast.beanAction.ncbiBlastNAction.commandBlastN(ncbiBlastNAction.java:168) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) java.lang.reflect.Method.invoke(Method.java:597) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280) org.apache.struts2.interceptor.BackgroundProcess$1.run(BackgroundProcess.java:57) java.lang.Thread.run(Thread.java:619)
java.io.IOException: The system cannot find the path specified java.io.WinNTFileSystem.createFileExclusively(Native Method) java.io.File.checkAndCreate(File.java:1704) java.io.File.createTempFile(File.java:1792) com.ncbi.blast.beanAction.ncbiBlastNAction.commandBlastN(ncbiBlastNAction.java:95) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) java.lang.reflect.Method.invoke(Method.java:597) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280) org.apache.struts2.interceptor.BackgroundProcess$1.run(BackgroundProcess.java:57) java.lang.Thread.run(Thread.java:619)
Try defining your result like this:
<result name="redirect" type="redirect">${url}</result>
And then in your action, have something like this:
private String url;
public String getUrl() {
return url;
}
public String commandBlastN() {
// create your HTML file
url = "/web/blast/blast_xxxx.html";
return "redirect";
}