I have an old java code and I'm quite new to java spring, I need to read json files and merge data from entity to Oracle database.
I test my code without the entityManager.merge() and it works well.
But now, I tried with merge and got an EJBException
javax.ejb.EJBException: EJB Exception: : javax.persistence.TransactionRequiredException: The method public abstract java.lang.Object javax.persistence.EntityManager.merge(java.lang.Object) must be called in the context of a transaction.
at weblogic.persistence.BasePersistenceContextProxyImpl.validateInvocation(BasePersistenceContextProxyImpl.java:148)
at weblogic.persistence.BasePersistenceContextProxyImpl.invoke(BasePersistenceContextProxyImpl.java:103)
at weblogic.persistence.TransactionalEntityManagerProxyImpl.invoke(TransactionalEntityManagerProxyImpl.java:138)
at weblogic.persistence.BasePersistenceContextProxyImpl.invoke(BasePersistenceContextProxyImpl.java:91)
at com.sun.proxy.$Proxy592.merge(Unknown Source)
at be.smals.ideploy.manager.ReleaseManager.updateReleases(ReleaseManager.java:69)
at be.smals.ideploy.manager.ReleaseManager.getActiveReleaseList(ReleaseManager.java:144)
This is my code :
#Stateless
#Local
#TransactionAttribute(TransactionAttributeType.SUPPORTS)
public class ReleaseManager {
private static final Logger LOGGER = LoggerFactory.getLogger(ReleaseManager.class);
private static final String STATUS_CLOSED = "inactive";
private static final String STATUS_OPEN = "active";
private Integer cpt_active = 0;
private Integer cpt_inactive = 0;
#PersistenceContext(unitName = "deployment")
private EntityManager em;
public void updateReleases() {
try {
for (GetReleaseList releaseList : getRelease(STATUS_OPEN)) {
Service service_active = new Service();
Release release_active = new Release();
List<ResponseJson> response = getResponse(STATUS_OPEN);
service_active.setId(response.get(cpt_active).getResult().getService_id());
release_active.setService(service_active);
String releaseId = releaseList.getNumber();
String releaseId_format = releaseId.replace("CHG","");
release_active.setId(releaseId_format);
release_active.setName(releaseList.getShortDescription());
release_active.setActive(Boolean.TRUE);
LOGGER.info("RELEASE NUMBER FORMATED : " + releaseId_format);
em.merge(release_active);
cpt_active += 1;
}
for (GetReleaseList releaseList : getRelease(STATUS_CLOSED)) {
Service service_inactive = new Service();
Release release_inactive = new Release();
List<ResponseJson> response = getResponse(STATUS_CLOSED);
service_inactive.setId(response.get(cpt_inactive).getResult().getService_id());
release_inactive.setService(service_inactive);
String releaseId = releaseList.getNumber();
String releaseId_format = releaseId.replace("CHG","");
release_inactive.setId(releaseId_format);
release_inactive.setName(releaseList.getShortDescription());
release_inactive.setActive(Boolean.FALSE);
LOGGER.info("RELEASE NUMBER FORMATED : " + releaseId_format);
em.merge(release_inactive);
cpt_inactive += 1;
}
}catch (TransactionException ex) {
throw new TechnicalException(ex);
}
Query q = em.createQuery("update Deployment d set d.release = null where d.status.id = :status and d.release.id in ( select r.id from Release r where r.active = :active) ");
LOGGER.info("Create Query : " + q);
q.setParameter("status", State.CREATING);
q.setParameter("active", Boolean.FALSE);
int updated = q.executeUpdate();
LOGGER.info("Updated release.id of " + updated + " deployments");
}
// getRelease element for Release entity except service ID
private List<GetReleaseList> getRelease(String STATUS) {
Gson gson = new Gson();
BufferedReader buffer_reader = null;
LOGGER.info(STATUS);
try {
buffer_reader = new BufferedReader(new FileReader("/tmp/snow/Release_manager_"+STATUS+".json"));
File File_snow = new File("/tmp/snow/Release_manager_"+STATUS+".json");
boolean exists = File_snow.exists();
LOGGER.info(String.valueOf(exists));
}catch (FileNotFoundException ex){
ex.printStackTrace();
}
RESTResponseJson response = gson.fromJson(buffer_reader, RESTResponseJson.class);
return response.getResult();
}
// getServiceID element for Release entity attribute Long service_id
private static List<ResponseJson> getResponse(String STATUS){
Gson gson_service = new Gson();
BufferedReader buffer_reader_service = null;
try {
buffer_reader_service = new BufferedReader(new FileReader("/tmp/snow/Service_id_"+STATUS+".json"));
}catch (FileNotFoundException ex){
ex.printStackTrace();
}
Response response_service = gson_service.fromJson(buffer_reader_service, Response.class);
return response_service.getResponse();
}
public List<Service> getServiceList(){
TypedQuery<Service> q = em.createQuery("SELECT s from Service", Service.class);
List<Service> services = q.getResultList();
return services;
}
public List<ReleaseTO> getInActiveReleaseList() {
TypedQuery<ReleaseTO> query = em.createQuery("select new be.smals.ideploy.to.ReleaseTO(r.id, r.name) from Release r where r.active=:active ORDER BY UPPER(r.name)", ReleaseTO.class);
query.setParameter("active", Boolean.FALSE);
List<ReleaseTO> result = query.getResultList();
return result;
}
public List<ReleaseTO> getActiveReleaseList() {
updateReleases();
TypedQuery<ReleaseTO> query = em.createQuery("select new be.smals.ideploy.to.ReleaseTO(r.id, r.name) from Release r where r.active=:active ORDER BY UPPER(r.name)", ReleaseTO.class);
query.setParameter("active", Boolean.TRUE);
List<ReleaseTO> result = query.getResultList();
return result;
}
public List<ReleaseTO> getReleaseList() {
TypedQuery<ReleaseTO> query = em.createQuery("select new be.smals.ideploy.to.ReleaseTO(r.id, r.name) from Release r ORDER BY UPPER(r.name)", ReleaseTO.class);
List<ReleaseTO> result = query.getResultList();
return result;
}
}
As suggest the error, is the #TransactionAttribute that don't correspond to my context, if somebody can explain the differencies for TransactionAttributeType.
I also read that it could come from #Stateless statement.
From https://docs.oracle.com/javaee/6/api/javax/ejb/TransactionAttributeType.html
SUPPORTS: If the client calls with a transaction context, the container performs the same steps as described in the REQUIRED case.
REQUIRED: If a client invokes the enterprise bean's method while the client is associated with a transaction context, the container invokes the enterprise bean's method in the client's transaction context.
I think you want "REQUIRED"
Related
I am sending from the frontend a value to search on two properties of my entity Producto. That properties are Codigo and Descripcion.
The issue is that when the line TypedQuery<Long> typedQuery = em.createQuery(queryCount); hits, this exception is thrown:
queryString= org.hibernate.hql.internal.ast.QuerySyntaxException: Invalid path:
'generatedAlias1._codigo' [select count(generatedAlias0) from
com.its.entidades.db.Producto as generatedAlias0 where (
generatedAlias1._codigo like :param0 ) and (
generatedAlias1._descripcion like :param1 )]
detailMessage= Invalid path: 'generatedAlias1._codigo'
The weird thing is that if I comment the quoted line, and in consequence the two lines below, everything runs as expected.
But I need to get the total of the registers filtered, so I need to count them.
ProductoService.java
#Override
public ServiceResponse<List<Producto>> ObtenerListaPaginada(ParametrosListadoModelo parametros) {
ServiceResponse<List<Producto>> ret = new ServiceResponse<>();
ret.setListadoModelo(parametros);
try {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Producto> query = cb.createQuery(Producto.class);
CriteriaQuery<Long> queryCount = cb.createQuery(Long.class);
queryCount.select(cb.count(queryCount.from(Producto.class)));
Root<Producto> entity = query.from(Producto.class);
TypedQuery<Producto> tq = null;
if (parametros.getBusqueda() != null && !parametros.getBusqueda().isEmpty()) {
String queryFilter = "%" + parametros.getBusqueda() + "%";
List<Predicate> predicates = new ArrayList<>();
predicates.add(cb.like(entity.<String>get("_codigo"), queryFilter));
predicates.add(cb.like(entity.<String>get("_descripcion"), queryFilter));
query.where(predicates.toArray(new Predicate[]{}));
queryCount.where(predicates.toArray(new Predicate[]{}));
}
// Count for total
TypedQuery<Long> typedQuery = em.createQuery(queryCount);
Long count = typedQuery.getSingleResult();
ret.getListadoModelo().setTotalRegistros(count);
// Order by
if (parametros.getCampoOrdenamiento().equals("codigo"))
parametros.setCampoOrdenamiento("_codigo");
if (parametros.getCampoOrdenamiento().equals("descripcion"))
parametros.setCampoOrdenamiento("_descripcion");
query.orderBy(parametros.getDireccionOrdenamiento().equals("ASC") ? cb.asc(entity.get(parametros.getCampoOrdenamiento())) : cb.desc(entity.get(parametros.getCampoOrdenamiento())));
// Paginator
tq = em.createQuery(query);
tq.setFirstResult((int) ((parametros.getNumeroPagina() - 1) * parametros.getCantidadElementos()));
tq.setMaxResults((int) (parametros.getCantidadElementos()));
ret.setData(tq.getResultList());
} catch (Exception ex) {
ret.getErrores().add(new ServicioError(ex));
}
return ret;
}
Producto.java
#Entity(name = "Producto")
public class Producto {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "ProductoID")
private int _productoID;
#Column(name = "cCodigo")
private String _codigo;
#Column(name="cDescripcion")
private String _descripcion;
#JsonProperty("codigo")
public String getCodigo() {
return _codigo;
}
#JsonProperty("codigo")
public void setCodigo(String _codigo) {
this._codigo = _codigo;
}
#JsonProperty("descripcion")
public String getDescripcion() {
return _descripcion;
}
#JsonProperty("descripcion")
public void setDescripcion(String _descripcion) {
this._descripcion = _descripcion;
}
}
Why is this happening?
Finally solved refactoring:
try{
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Producto> query = cb.createQuery(Producto.class);
CriteriaQuery<Long> queryCount = cb.createQuery(Long.class);
Root<Producto> entityRoot = queryCount.from(query.getResultType());
queryCount.select(cb.count(entityRoot));
Root<Producto> entity = query.from(Producto.class);
TypedQuery<Producto> tq;
//And the rest of the code is the same as the original one.
//...
}
I have a Patients entity class which auto generates an id:
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "personId", nullable = false, unique = true)
private Long personId;
public void copy (Patients patient) {
if (patient.getNationality() != null)
this.setNationality(patient.getNationality());
if (patient.getGivenName() != null)
this.setGivenName(patient.getGivenName());
if (patient.getMiddleName() != null)
this.setMiddleName(patient.getMiddleName());
if (patient.getPrefix() != null)
this.setPrefix(patient.getPrefix());
}
/**
* #return PERSONID
*/
public int getPersonId() {
return personId;
}
My addPerson in PersonDaoImpl :
public Patients addPerson(Patients person) {
Patients p = new Patients(person);
try {
em = factory.createEntityManager();
em.getTransaction().begin();
SimpleDateFormat sdfr = new SimpleDateFormat("yyyy-MM-
dd'T'HH:mm:ss.SSS+05:30");
Date date = new Date();
String dateCreated = sdfr.format(date);
p.setDateCreated(dateCreated);
em.persist(p);
em.getTransaction().commit();
} catch (Exception e) {
em.getTransaction().rollback();
log.error("Exception caught :: " + e);
p = null;
}
em.close();
return p;
}
My update api in person service class:
#PUT
#Path("/person-manager-resource/updatePersonById")
#Produces("application/json")
#Consumes("application/json")
public Response update(Patients person) {
log.info("Inside UpdatePerson");
log.info(person.getPersonId());
dao = new PersonDaoImpl();
ObjectMapper mapper = new ObjectMapper();
person1 = dao.updatePerson(person);
String result = "";
try {
result = mapper.writeValueAsString(person1);
log.info("Person updated :: " + result);
} catch (JsonProcessingException e) {
log.info("Exception Caught :: " + e);
}
if (person1 != null) {
return Response.
status(Response.Status.OK.getStatusCode()).
entity(result).
build();
} else {
return Response.
status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).
entity(result).
build();
}
}
UpdatePerson:
public Patients updatePerson(Patients updatedPatient) {
Patients dbPatient = new Patients();
TypedQuery<Patients> query = null;
ObjectMapper mapper = new ObjectMapper();
try {
em = factory.createEntityManager();
String identifier = updatedPatient.getPersonIdentifiers().getIdentifier();
String queryStr = "SELECT c FROM Patients c where c.personIdentifiers.identifier = '" + identifier + "'";
query = em.createQuery(queryStr, Patients.class);
dbPatient = query.getSingleResult();
dbPatient.copy(updatedPatient);
em.getTransaction().begin();
em.merge(dbPatient);
em.getTransaction().commit();
} catch (Exception e) {
log.error("Exception caught :: " + e);
em.getTransaction().rollback();
dbPatient = null;
}
em.close();
return dbPatient;
}
I pass a json object through my REST api to create a patient entry:
{
"personId": 5,
"prefix": null,
"givenName": "Pooja roy",
"middleName": null
}
Now this is going fine. I take the same object, which now contains the auto-generated personId, in an api which is supposed to update the object. I pass the json in the Patients entity object. When I print this whole object, the personId is null.
Since it is null and primary key, I can't do a merge. I have to manually update the database object, which is a very lengthy process.
Any ideas why it is coming as null and how I can retrieve it?
I am using postgres.
I think the whole problem is caused by the implementation of the updatePerson method. You should implement the method as follows and it should work as expected, assuming the updatedPatient instance is a persistent entity (meaning it has an ID field set):
public Patients updatePerson(Patients updatedPatient) {
Patients mergedPatient = new Patients();
try {
em = factory.createEntityManager();
em.getTransaction().begin();
mergedPatient = em.merge(updatedPatient);
em.getTransaction().commit();
} catch (Exception e) {
log.error("Exception caught :: " + e);
em.getTransaction().rollback();
}
em.close();
return mergedPatient;
}
Now mergedPatient should contain the synchronized state.
Update:
alternative solution
For whatever reason you cannot use a setter for the ID field. Then the following might solve your problem:
public Patients updatePerson(Patients updatedPatient) {
Patients dbPatient = new Patients();
try {
em = factory.createEntityManager();
String identifier = updatedPatient.getPersonIdentifiers().getIdentifier();
em.getTransaction().begin();
dbPatient = em.find(Patients.class, Long.parseLong(identifier));
dbPatient.copy(updatedPatient);
em.getTransaction().commit();
} catch (Exception e) {
// ..:
dbPatient = null;
}
em.close();
return dbPatient;
}
As the em.find() method is executed inside of a transaction, the object returned is managed, which means any changes to that returned instance will be synchronized with the database when the transaction commits.
PersonId is an auto generated id. So, jpa doesn't allow for me to set a setter for personId. We only have getPersonId() method in the entity class.
So, in updatePerson(Patients person), when I am passing the person object, every setter is called and the object is thus created. Since, personId doesn't have a setter method, it is returned as null in that object.
I have an error while I am getting data from database.It looks like everything is fine but i get this error?Why?
Full Error
(org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: 0 near line 1, column 47 [from com.project.Data limit 0,10] (Encoded))
DataAction.java
/**
* To list Data
*
* #return String
*/
public String listThrowException() {
try{
//Getting Total records count from database...
pagination.setPreperties(facade.getDataCount());
//Getting data list from database
listData = facade.listData(pagination);
//Setting number of records in the particular page
pagination.setPage_records(listData.size());
logger.info(Logger.EVENT_SUCCESS,
"successfully viewed data list!");
}catch (Exception e) {
logger.error(
Logger.EVENT_FAILURE,
"could not view data list, error: *"
+ e.getMessage() + "*");
}
return "success";
}
DataService.java
#Override
public List<Data> listData(Pagination pagination){
List<Data> list=new ArrayList<Data>();
Query query;
try {
String excQuery = "from Data limit ";
excQuery = pagination.getSQLQuery(excQuery);
query = em.createQuery(excQuery);
list = query.getResultList();
} catch (Exception e) {
logger.error(Logger.EVENT_FAILURE, e.getMessage());
return null;
}
return list;
}
Pagination.java
public class Pagination {
private long page_size = 0;
private int page_number = 0;
private long total_records = 0;
private int page_records = 0;
private long start = 0;
private long end = 0;
private int total_pages = 0;
public void setPreperties(long l){
total_records = l;
total_pages = (int) Math.ceil(((double)l / (double)page_size));
start = ((page_size * page_number) - page_size);
end = page_size*page_number;
if(page_size==0){
start = 0;
end = l;
total_pages = 1;
}
}
public Pagination(int page_size, int page_number) {
this.page_number = page_number;
this.page_size = page_size;
}
public String getSQLQuery(String query) {
query += getStart() + "," + getEnd();
return query;
}
///get and set methods
}
My problem is that "limit" in Hql it is not supported.I use setFirstResults() setMaxResults() and it works.My question is a good example for implementing paginaton in your page. I refer this tutorial http://prathap-puppala.blogspot.com/2011/06/struts-2-pagination-example.html I change only DateService.java** Good Luck!
DateService.java
#Override
public List<Data> listData(Pagination pagination){
List<Data> list=new ArrayList<Data>();
Query query;
try {
String excQuery = "from Data ";
query = em.createQuery(excQuery).
setFirstResult(pagination.getStart()).setMaxResults(pagination.getEnd());
query = em.createQuery(excQuery);
list = query.getResultList();
} catch (Exception e) {
logger.error(Logger.EVENT_FAILURE, e.getMessage());
return null;
}
return list;
}
I want to test MessageProcessor1.listAllKeyword method, which in turn
calls HbaseUtil1.getAllKeyword method. Initialy, I had to deal with a problem associated with the static initializer and the constructor. The problem was to initialize a HBASE DB connection. I used powerMock to suppress static and constructor calls and it worked fine.
Even though I mocked HbaseUtil1.getAllKeyword method, actual method is being called and executes all HBase code leading to an exception, in which HBASE server is not up.
EasyMock.expect(hbaseUtil.getAllKeyword("msg", "u1")).andReturn(expectedList);
Please give me any idea on how to avoid an actual method call. I tried many ways but none of them worked.
public class MessageProcessor1
{
private static Logger logger = Logger.getLogger("MQ-Processor");
private final static String CLASS_NAME = "MessageProcessor";
private static boolean keywordsTableExists = false;
public static PropertiesLoader props;
HbaseUtil1 hbaseUtil;
/**
* For checking if table exists in HBase. If doesn't exists, will create a
* new table. This runs only once when class is loaded.
*/
static {
props = new PropertiesLoader();
String[] userTablefamilys = {
props.getProperty(Constants.COLUMN_FAMILY_NAME_COMMON_KEYWORDS),
props.getProperty(Constants.COLUMN_FAMILY_NAME_USER_KEYWORDS) };
keywordsTableExists = new HbaseUtil()
.creatTable(props.getProperty(Constants.HBASE_TABLE_NAME),
userTablefamilys);
}
/**
* This will load new configuration every time this class instantiated.
*/
{
props = new PropertiesLoader();
}
public String listAllKeyword(String userId) throws IOException {
HbaseUtil1 util = new HbaseUtil1();
Map<String, List<String>> projKeyMap = new HashMap<String, List<String>>();
//logger.info(CLASS_NAME+": inside listAllKeyword method");
//logger.debug("passed id : "+userId);
List<String> qualifiers = util.getAllKeyword("msg", userId);
List<String> keywords = null;
for (String qualifier : qualifiers) {
String[] token = qualifier.split(":");
if (projKeyMap.containsKey(token[0])) {
projKeyMap.get(token[0]).add(token[1]);
} else {
keywords = new ArrayList<String>();
keywords.add(token[1]);
projKeyMap.put(token[0], keywords);
}
}
List<Project> projects = buildProject(projKeyMap);
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
.create();
System.out.println("Json projects:::" + gson.toJson(projects));
//logger.debug("list all keyword based on project::::"+ gson.toJson(projects));
//return gson.toJson(projects);
return "raj";
}
private List<Project> buildProject(Map<String, List<String>> projKeyMap) {
List<Project> projects = new ArrayList<Project>();
Project proj = null;
Set<String> keySet = projKeyMap.keySet();
for (String hKey : keySet) {
proj = new Project(hKey, projKeyMap.get(hKey));
projects.add(proj);
}
return projects;
}
//#Autowired
//#Qualifier("hbaseUtil1")
public void setHbaseUtil(HbaseUtil1 hbaseUtil) {
this.hbaseUtil = hbaseUtil;
}
}
public class HbaseUtil1 {
private static Logger logger = Logger.getLogger("MQ-Processor");
private final static String CLASS_NAME = "HbaseUtil";
private static Configuration conf = null;
public HbaseUtil1() {
PropertiesLoader props = new PropertiesLoader();
conf = HBaseConfiguration.create();
conf.set(HConstants.ZOOKEEPER_QUORUM, props
.getProperty(Constants.HBASE_CONFIGURATION_ZOOKEEPER_QUORUM));
conf.set(
HConstants.ZOOKEEPER_CLIENT_PORT,
props.getProperty(Constants.HBASE_CONFIGURATION_ZOOKEEPER_CLIENT_PORT));
conf.set("hbase.zookeeper.quorum", props
.getProperty(Constants.HBASE_CONFIGURATION_ZOOKEEPER_QUORUM));
conf.set(
"hbase.zookeeper.property.clientPort",
props.getProperty(Constants.HBASE_CONFIGURATION_ZOOKEEPER_CLIENT_PORT));
}
public List<String> getAllKeyword(String tableName, String rowKey)
throws IOException {
List<String> qualifiers = new ArrayList<String>();
HTable table = new HTable(conf, tableName);
Get get = new Get(rowKey.getBytes());
Result rs = table.get(get);
for (KeyValue kv : rs.raw()) {
System.out.println("KV: " + kv + ", keyword: "
+ Bytes.toString(kv.getRow()) + ", quaifier: "
+ Bytes.toString(kv.getQualifier()) + ", family: "
+ Bytes.toString(kv.getFamily()) + ", value: "
+ Bytes.toString(kv.getValue()));
qualifiers.add(new String(kv.getQualifier()));
}
table.close();
return qualifiers;
}
/**
* Create a table
*
* #param tableName
* name of table to be created.
* #param familys
* Array of the name of column families to be created with table
* #throws IOException
*/
public boolean creatTable(String tableName, String[] familys) {
HBaseAdmin admin = null;
boolean tableCreated = false;
try {
admin = new HBaseAdmin(conf);
if (!admin.tableExists(tableName)) {
HTableDescriptor tableDesc = new HTableDescriptor(tableName);
for (int i = 0; i < familys.length; i++) {
tableDesc.addFamily(new HColumnDescriptor(familys[i]));
}
admin.createTable(tableDesc);
System.out.println("create table " + tableName + " ok.");
}
tableCreated = true;
admin.close();
} catch (MasterNotRunningException e1) {
e1.printStackTrace();
} catch (ZooKeeperConnectionException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return tableCreated;
}
}
Below is my Test class.
#RunWith(PowerMockRunner.class)
#PrepareForTest(MessageProcessor1.class)
#SuppressStaticInitializationFor("com.serendio.msg.mqProcessor.MessageProcessor1")
public class MessageProcessorTest1 {
private MessageProcessor1 messageProcessor;
private HbaseUtil1 hbaseUtil;
#Before
public void setUp() {
messageProcessor = new MessageProcessor1();
hbaseUtil = EasyMock.createMock(HbaseUtil1.class);
}
#Test
public void testListAllKeyword(){
List<String> expectedList = new ArrayList<String>();
expectedList.add("raj:abc");
suppress(constructor(HbaseUtil1.class));
//suppress(method(HbaseUtil1.class, "getAllKeyword"));
try {
EasyMock.expect(hbaseUtil.getAllKeyword("msg", "u1")).andReturn(expectedList);
EasyMock.replay();
assertEquals("raj", messageProcessor.listAllKeyword("u1"));
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
}
The HbaseUtil1 is instantiated within the listAllKeyword method
public String listAllKeyword(String userId) throws IOException {
HbaseUtil1 util = new HbaseUtil1();
...
So the mock one you create in your test isn't being used at all.
If possible, make the HbaseUtil1 object passable, or settable on the MessageProcessor1 class and then set it in the test class.
Also, and note I'm not 100% familiar with PowerMock, you could include HbaseUtil1 in the prepare for test annotation. I think that will make PowerMock instantiate mocks instead of real objects and then use the expectations you provide in you test.
This is the web services that i want to connect and send value from android virtual machine.
#WebService(serviceName = "EmoDeneme")
#Stateless()
public class EmoDeneme {
/**
* This is a sample web service operation
*/
#WebMethod(operationName = "hello")
public String hello(#WebParam(name = "name") String name) {
String BargeName = "";
int BargeNo = 0;
String Starting = "";
String StartingDate = "";
try {
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("Barge");
DBCollection collection = db.getCollection("Emo");
DBObject match = new BasicDBObject("$match", new BasicDBObject("html.table.tbody.Barge.Name", name));
DBObject unwind = new BasicDBObject("$unwind", "$html.table.tbody.Barge");
AggregationOutput output = collection.aggregate(unwind, match);
for (DBObject result : output.results()) {
DBObject htmlObj = (DBObject) result.get("html");
DBObject tableObj = (DBObject) htmlObj.get("table");
DBObject tbodyObj = (DBObject) tableObj.get("tbody");
DBObject bargeObj = (DBObject) tbodyObj.get("Barge");
BargeName = (String) bargeObj.get("Name");
BargeNo = (Integer) bargeObj.get("Bargeno");
Starting = (String) bargeObj.get("Starting");
StartingDate = Starting.substring(0, 10);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
return "Terminal: " + " BargeName :" + BargeName + " BargeNo: " + BargeNo + " ETA
: " + StartingDate;
}
}
This is the Android Code to connect to web service
public class MainActivity extends Activity {
private static final String SOAP_ACTION = "";
private static final String METHOD_NAME = "hello";
private static final String NAMESPACE = "http://mongodb.me.org/";
private static final String URL = "http://10.0.2.2:8080/EmoDeneme/EmoDeneme?WSDL";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread networkThread = new Thread() {
#Override
public void run() {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
String firstName = "Aan";
//Pass value for fname variable of the web service
PropertyInfo fnameProp =new PropertyInfo();
fnameProp.setName("name");//Define the variable name in the web service `method`
fnameProp.setValue(firstname);//Define value for fname variable
fnameProp.setType(String.class);//Define the type of the variable
request.addProperty(fnameProp);//Pass properties to the variable
SoapSerializationEnvelope envelope = new `SoapSerializationEnvelope(SoapEnvelope.VER11);`
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE ht = new HttpTransportSE(URL);
ht.call(SOAP_ACTION, envelope);
final SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
final String str = response.toString();
runOnUiThread (new Runnable(){
public void run() {
TextView result;
result = (TextView)findViewById(R.id.textView1);//I have created a text view `& It's id is textView1`
result.setText(str);
}
});
}
catch (Exception e) {
e.printStackTrace();
}
}
};
networkThread.start();
}
}
It does not work, can someone help me please what i do wrong.
Thank you.
SOAP calls can get messy. There is a better way of calling a web service. Check out the following 2 videos:
http://javabrains.koushik.org/2013/06/writing-web-service-client-stub.html
http://javabrains.koushik.org/2013/06/writing-web-service-client-calling.html
In the first video the author generated java code by using the command line and pointing to a wsdl and in the second video he calls functions from the generated java code.
And if you want to do some really interesting things with web services check out:
http://cxf.apache.org/
Hope this helps.
PS. there is a really cool tool if you are into SOAP: http://www.soapui.org/