I'm trying to create a simple DB connection using JPA.
It works fine but when I try to Throw an Exception to the client I get the error:
[ERROR] [browsereditor] - Line 210: No source code is available for type javax.persistence.EntityExistsException; did you forget to inherit a required module?
[ERROR] [browsereditor] - Line 212: No source code is available for type javax.persistence.EntityNotFoundException; did you forget to inherit a required module?
I get no error in development mode and it compiles fine, but when the app module is loaded there is where I get the error.
I have the required imports in server/Composer and client/Presenter classes
import javax.persistence.EntityExistsException;
import javax.persistence.EntityNotFoundException;
I also added the following jars to the classpath and build path:
javax.persistence.jar
jpa-annotations-source.jar (http://code.google.com/p/google-web-toolkit/issues/detail?id=1830#c14)
I also tried adding to gwt.xml
<source path='client'/>
<source path='shared'/>
<source path='server'/>
Any ideas on how to tell eclipse where to find the source code??
Thanks
Here is the code:
//Create composer from Composer.class in server
public static Composer createComposer(String name)
throws EntityExistsException {
Composer comp = new Composer();
comp.setName(name);
comp.setId(1);
EntityManager entityManager = entityManager();
entityManager.getTransaction().begin();
entityManager.persist(comp);
entityManager.getTransaction().commit();
entityManager.close();
return comp;
}
///fire Request from createComposer(above) in Presenter.class
req.fire(new Receiver<ComposerProxy>() {
public void onSuccess(ComposerProxy arg0) {
ComposerProxy comp;
comp = arg0;
}
public void onFailure(Throwable caught)
throws Throwable {
// Convenient way to find out which exception
// was thrown.
try {
throw caught;
} catch (EntityExistsException e) {
} catch (EntityNotFoundException e) {
}
}});
}});
[ERROR] [browsereditor] - Line 210: No source code is available for type javax.persistence.EntityExistsException; did you forget to inherit a required module?
[ERROR] [browsereditor] - Line 212: No source code is available for type javax.persistence.EntityNotFoundException; did you forget to inherit a required module?
You can't use types such as EntityExistsException or EntityNotFoundException in client-side GWT code at all.
These are plain Java classes and GWT don't know how to translate them to JavaScript.
You can only use very limited part of external libraries in your client-side code. These libraries (like Visualisation for example) are designed and prepared specifically for client-side and require inheriting their GWT module in your application's module.
I think that what you really want to do is something like that:
public void onFailure(ServerFailure failure) throws Throwable {
if(failure.getExceptionType().equals("javax.persistence.EntityExistsException")){
...
}else if(failure.getExceptionType().equals("javax.persistence.EntityNotFoundException")){
...
}
}
Because you can read type of server-side exception as String, see Javadoc for Receiver and ServerFailure.
Thanks Piotr for your help.
Here is the code for what I finally did:
Code in the client
req.fire(new Receiver<ComposerProxy>() {
public void onSuccess(ComposerProxy arg0) {
ComposerProxy comp;
comp = arg0;
}
public void onFailure(ServerFailure failure) {
serverError.getServerError(failure,
"onAddButtonClicked");
}
});
I created a class to handle the errors
public class ServerError {
public ServerError() {
}
public void getServerError(ServerFailure failure, String message) {
// Duplicate Key Error
if (failure.getMessage().contains(
"IntegrityConstraintViolationException")) {
Window.alert("Duplicate Key " + message);
return;
}
// Connection Error
if (failure.getMessage().contains("NonTransientConnectionException")) {
Window.alert("Connection error ");
return;
}
// TimeOut Error
if (failure.getMessage().contains("TimeoutException")) {
Window.alert("Timeout Error" + message);
return;
}
// Other Error
else {
Window.alert("Duplicate Key " + message);
return;
}
}
}
Service in the server
public static Composer createComposer(String name) throws Throwable {
EntityManager entityManager = entityManager();
Composer comp = new Composer();
try {
comp.setName(name);
comp.setId(1);
entityManager.getTransaction().begin();
entityManager.persist(comp);
entityManager.getTransaction().commit();
} catch (Exception e) {
log.error("Error in Composer::createComposer( " + name + ") //"
+ e.toString());
throw e;
} finally {
entityManager.close();
}
return comp;
}
One problem I found is that the variable 'ServerFailure failure'only contains info in the failure.message; all the other variables are null.
Related
I cannot perform search query.
https://developer.mapquest.com/documentation/searchahead-sdk/android/v1.3/
Tells me that this is correct but it wont work. It throws me an error
private void searchQuery(String queryString){
SearchAheadService mSearchAheadServiceV3;
mSearchAheadServiceV3 = new SearchAheadService(mContext, "uZW4cZzRkNqXaK9oHOrgJVEb6rk3oVM0");
List searchCollections = Arrays.asList(SearchCollection.AIRPORT, SearchCollection.ADMINAREA,
SearchCollection.ADDRESS);
try {
SearchAheadQuery query = new SearchAheadQuery.Builder(queryString, searchCollections).location(new LatLng((float)MapsActivity.mLastLocation.getLatitude(), (float)MapsActivity.mLastLocation.getLongitude())).build();
mSearchAheadServiceV3.predictResultsFromQuery(query,
new SearchAheadService.SearchAheadResponseCallback() {
#Override
public void onSuccess(#NonNull SearchAheadResponse searchAheadResponse) {
Log.i(TAG, "Search Ahead V3 Success - Response: " + searchAheadResponse);
}
#Override
public void onError(Exception e) {
Log.e(TAG, "Search Ahead V3 Failure", e);
}
});
} catch (IllegalQueryParameterException e) {
L.e("Error performing search", e);
}
}
But i got this error:
java.lang.LinkageError: Method org.apache.http.HttpResponse com.mapquest.android.commoncore.network.volley.NetworkHelper$InitialRequestQueueSupplier$1.performRequest(com.android.volley.Request, java.util.Map) overrides final method in class Lcom/android/volley/toolbox/BaseHttpStack; (declaration of 'com.mapquest.android.commoncore.network.volley.NetworkHelper$InitialRequestQueueSupplier$1' appears in /data/app/com.example.locolusmap-S4zcpMbjISCjpC9YmZe9SQ==/base.apk:classes3.dex)
This is an issue that the development team is aware of and we hope to have a fix for this soon. It will be part of the next version of the SDK. I don't have an ETA.
I'm currently trying to migrate an EAR Project
-The old Project-
EJB 2.0
Jboss 5.0.1
-New Project-
EJB 3.0
Wildfly 13.0.0Final
Its session beans which I have managed to create and I can call upon it. the logic in it self seems to work. The issues I'm having is one of the follow ups seems to forget what it was doing.
the current issue I'm seeing is the following:
In the Web application in an class we are creating an object of Another class which we then trigger its parent method. this parent method then calls upon a class with it self as an argument which then checks which type it is and then stars a session bean depending on what type. which then calls on the arguments function performExecute() in this function we call upon a Query and actually get the correct results, we then add the resultsets values to a private dto member. and then performExecute is done. and we are back at the web applications class and we then try to access the same dto member with a get function. this returns a nullpointer. I'm wondering if I've forgotten something in my session beans?
Old sessionbean:
public class TxNotSupportedCommandServerBean implements SessionBean {
SessionContext sessionContext;
public void ejbCreate() throws CreateException {}
public void ejbRemove() {
sessionContext = null;
}
public void ejbActivate() {}
public void ejbPassivate() {}
public void setSessionContext(SessionContext sessionContext) {
this.sessionContext = sessionContext;
}
public void executeCommand(TargetableCommand cmd) throws CommandException {
try {
cmd.performExecute();
}
catch (CommandException ex) {
throw ex;
}
}
}
The new one:
#Stateless
#Remote
#TransactionManagement(value=TransactionManagementType.CONTAINER)
#TransactionAttribute(value=REQUIRED)
public class TxNotSupportedCmdServerBean implements TxNotSupportedCmdServerRemote{
/**
* Default constructor.
*/
public TxNotSupportedCmdServerBean() {
// TODO Auto-generated constructor stub
}
public void executeCommand(TargetableCommand cmd) throws CommandException {
try {
cmd.performExecute();
}
catch (CommandException ex) {
throw ex;
}
}
}
Both these are in the EJB.Jar
the interface is implemented in the EJBClient.jar
The old Interface:
public interface TxNotSupportedCommandServerLocal extends EJBLocalObject {
public void executeCommand(TargetableCommand cmd) throws CommandException;
}
The new Interface:
public interface TxNotSupportedCmdServerRemote {
public void executeCommand(TargetableCommand cmd) throws CommandException;
}
Now here come s the next set of files that is also in the EJBClient.jar
TargetableCommand:
public abstract class TargetableCommand implements Command {
private boolean constraintViolated;
protected RequestContext requestContext;
protected String dataSourceName;
public TargetableCommand(RequestContext requestContext, String dataSourceName) {
this.requestContext = requestContext;
this.dataSourceName = dataSourceName;
}
public TargetableCommand(RequestContext requestContext) {
this.requestContext = requestContext;
}
public TargetableCommand(String dataSourceName) {
this.dataSourceName = dataSourceName;
}
public TargetableCommand() {
}
public void setConstraintViolated(boolean constraintViolated) {
this.constraintViolated = constraintViolated;
}
public boolean isConstraintViolated() {
return constraintViolated;
}
public abstract void performExecute() throws CommandException;
public void execute() throws CommandException {
CommandTarget.executeCommand(this);
}
}
Command:
public interface Command extends Serializable {
public void execute() throws CommandException;
}
The commented code is the old session beans.
CommandTarget:
public class CommandTarget {
public CommandTarget() {
}
/**
* Exekverar ett kommando i rätt miljö, t.ex. med eller utan transaktionshantering
* #param cmd TargetableCommand Kommandot som ska utföras
* #throws CommandException
*/
public static void executeCommand(TargetableCommand cmd) throws CommandException {
Context context = null;
try {
ServiceLocator sl = ServiceLocator.getInstance();
// if (cmd instanceof TxRequired) {
// TxRequiredCommandServerLocalHome cmdSrvHome = (TxRequiredCommandServerLocalHome) sl.getEJBLocalHome("TxRequiredCommandServer");
// TxRequiredCommandServerLocal cmdSrv = cmdSrvHome.create();
// cmdSrv.executeCommand(cmd);
// }
// else if(cmd instanceof TxNotSupported) {
// TxNotSupportedCommandServerLocalHome cmdSrvHome = (TxNotSupportedCommandServerLocalHome) sl.getEJBLocalHome("TxNotSupportedCommandServer");
// TxNotSupportedCommandServerLocal cmdSrv = cmdSrvHome.create();
// cmdSrv.executeCommand(cmd);
// }
// else {
// throw new CommandException("Cannot instanciate command server");
// }
//
System.out.println("CT: Inside commandTarget. about to diffrientate what instance");
context = JNDILookupClass.getInitialContext();
if (cmd instanceof TxRequired) {
System.out.println("CT: TxRequired");
TxRequiredCmdServerRemote cmdSrv = (TxRequiredCmdServerRemote)context.lookup(JNDILookupClass.getLookupName("TxRequiredCmdServerRemoteBean", TxRequiredCmdServerRemote.class.getName()));
cmdSrv.executeCommand(cmd);
}
else if(cmd instanceof TxNotSupported) {
System.out.println("CT: TxNotSupported");
System.out.println("CT: cmd: " + cmd.getClass());
TxNotSupportedCmdServerRemote cmdSrv = (TxNotSupportedCmdServerRemote)context.lookup(JNDILookupClass.getLookupName("TxNotSupportedCmdServerBean", TxNotSupportedCmdServerRemote.class.getName()));
cmdSrv.executeCommand(cmd);
}
else {
throw new CommandException("Cannot instanciate command server");
}
}
catch (CommandException ex) {
throw ex;
}
// catch (CreateException ex) {
// throw new CommandException(ex);
// }
//new catch
catch(NamingException ex) {
throw new CommandException(ex);
}
catch (ServiceLocatorException ex) {
throw new CommandException(ex);
}
}
}
Phew ...
Ok now that's the important parts from EJBClient. now onwards to the Web.war
I'm only pasting the part that actually runs and were it returns a nullpoint
public class ActionIdentitetKonsultCommand implements Command {
private static Logger logger = Logger.getLogger(ActionIdentitetKonsultCommand.class);
public ActionIdentitetKonsultCommand() {
}
public String execute(RequestContext requestContext) throws CommandException {
GetPersonByPersnrEJBCommand personCmd;
logger.info("execute()");
try {
UserBean user = (UserBean) requestContext.getSession().getAttribute("user");
String kstnr = requestContext.getParameter("kstnr");
//Tilldela konsultuppgifter
personCmd = new GetPersonByPersnrEJBCommand();
personCmd.setPersnr(user.getPersnr());
System.out.println("AI: Before execute DTO " + personCmd.dto);
personCmd.execute();
System.out.println("AI: After execute DTO " + personCmd.dto);
logger.info("person hamtad med personnummer (EJB):");
logger.info(personCmd.getPerson().toString());
So the personCmd.getPerson().tostring() is what causes the nullpointer. GetPersonByPersnrEJBCommand():
public class GetPersonByPersnrEJBCommand extends TargetableCommand implements TxNotSupported {
public PersonDTO dto;
private long persnr;
public GetPersonByPersnrEJBCommand() {
}
public void setPersnr(long persnr) {
this.persnr = persnr;
}
public PersonDTO getPerson() {
return this.dto;
}
public void performExecute() throws CommandException {
try {
QueryPersonByPersnrCommand cmd = new QueryPersonByPersnrCommand();
cmd.setPersnr(persnr);
cmd.execute();
if(cmd.next()){
this.dto = new PersonDTO();
System.out.println("GP: inside PerformExecute DTO: " + dto);
dto.setPersnr(cmd.getPersnr());
dto.setEfternamn(cmd.getEfternamn());
dto.setFornamn(cmd.getFornamn());
dto.setEpostAdress(cmd.getEpostAdress());
dto.setKonsult((cmd.getKonsult() == 1));
dto.setAnsvarig((cmd.getAnsvarig() == 1));
System.out.println("GP: Inside Perform Execute DTO: " + dto);
}
}
catch (DataAccessCommandException ex) {
System.out.println("GetPersonByPersnrEJBCommand.performExecute misslyckades " + ex.getMessage());
throw new CommandException(ex);
}
}
}
So that's it; I don't understand why it forgets it. when we do sysouts inside the last class we see that both the dto and the cmd has data in them, but once the function ends and we are back in the class that called on this the data is empty.
I'm suspecting its something to do with my session beans, I'm missing an property or something. because this code works with the old beans in the old JBOSS server. Hopefully someone can help me and others can learn from this as well as me.
I managed to solve this issue. Since the scope of the project is to get this to work. Its not a beautiful solution and with more time rewriting this would have been better. so onwards to the solution:
We need to change in both the bean, targetableCommand, CommandTarget and in the GetPersonByPersnrEJBCommand
TargetableCommand - add method:
public TargetableCommand execute(TargetableCommand cmd) throws CommandException
{
return CommandTarget.executeCommand(cmd);
}
CommandTarget - We change the method executeCommand to return a TargetableCommand, and make sure that after the bean is done we return that cmd.
public static TargetableCommand executeCommand(TargetableCommand cmd) throws CommandException {
Context context = null;
try {
context = JNDILookupClass.getInitialContext();
if (cmd instanceof TxRequired) {
TxRequiredCmdServerRemote cmdSrv = (TxRequiredCmdServerRemote)context.lookup(JNDILookupClass.getLookupName("TxRequiredCmdServerRemoteBean", TxRequiredCmdServerRemote.class.getName()));
cmd = cmdSrv.executeCommand(cmd);
}
else if(cmd instanceof TxNotSupported) {
TxNotSupportedCmdServerRemote cmdSrv = (TxNotSupportedCmdServerRemote)context.lookup(JNDILookupClass.getLookupName("TxNotSupportedCmdServerBean", TxNotSupportedCmdServerRemote.class.getName()));
cmd = cmdSrv.executeCommand(cmd);
}
else {
throw new CommandException("Cannot instanciate command server");
}
}
catch (CommandException ex) {
throw ex;
}
catch(NamingException ex) {
throw new CommandException(ex);
}
}
return cmd;
}
The bean - cange the method Execute command to return Targetablecommand
public TargetableCommand executeCommand(TargetableCommand cmd) throws CommandException {
try {
cmd = cmd.performExecute();
}
catch (CommandException ex) {
throw ex;
}
return cmd;
}
Then lastly to get it all to work I had to create a new method in the classes that needed to do the perform execute so in the GetPersonByPersnrEJBCommand class i created the method wf13Layer(); wich is a just an extra step:
public void wf13Layer() throws CommandException
{
GetPersonByPersnrEJBCommand tmp;
try{
tmp = (GetPersonByPersnrEJBCommand) execute(this);
dto = tmp.getPerson();
} catch (Exception ex) {
throw new CommandException(ex);
}
}
This is what i did to make it work. as i said its not a beautiful solution but it works. IT seems to be a combination that once we cross between the projects the scope vanishes. and to obtain it futher we need to layer it like this. I really hope this helps someone at some point since theres till alot of old code running around out there.
Kind regards
VeryTired
How to bind to jndi custom object programmatically on jboss 7.1?
Context.bind throws exception indicating that jndi context is read-only.
Is it possible at all?
Yes, it is possible at all. The following code works in JBoss AS 7.1.1.Final:
#Stateless
public class JndiEjb {
private static final Logger LOGGER = LoggerFactory.getLogger(JndiEjb.class);
public void registerInJndi() {
try {
Context context = new InitialContext();
context.bind("java:global/JndiEjb", this);
} catch (NamingException e) {
LOGGER.error(String.format("Failed to register bean in jndi: %s", e.getMessage()));
}
}
public void retrieveFromJndi() {
try {
Context context = new InitialContext();
Object lookup = context.lookup("java:global/JndiEjb");
if(lookup != null && lookup instanceof JndiEjb) {
LOGGER.debug("Retrieval successful.");
JndiEjb jndiEjb = (JndiEjb)lookup;
jndiEjb.helloWorld();
}
} catch (NamingException e) {
LOGGER.error(String.format("Failed to register bean in jndi: %s", e.getMessage()));
}
}
public void helloWorld() {
LOGGER.info("Hello world!");
}
}
If you call first registerInJndi() and afterwards retrieveFromJndi() the object will be looked up and the method helloWorld()is called.
You will find more information here.
I have the following code in UserController in my Session Scoped Bean
public void addItemToBundle(ItemEntity item){
//System.out.println(item.getTitle());
try {
em.getTransaction().begin();
UserEntity user = em.find(UserEntity.class, this.username);
BundleEntity bundle = new BundleEntity();
BundleEntityPK compositePk = new BundleEntityPK();
compositePk.setCheckedOutDate(new Date());
compositePk.setItemId(item.getItemId());
compositePk.setUsername(user.getUsername());
bundle.setId(compositePk);
Set<BundleEntity> bundles = new HashSet<BundleEntity>();
bundles.add(bundle);
user.setBundleEntities(bundles);
em.persist(user);
em.flush();
em.getTransaction().commit();
} finally {
}
}
public String addToBundle(){
try {
addItemToBundle(item);
} catch (NullPointerException e) {
e.getMessage();
}
return null;
}
This code uses private ItemEntity item; which gets passed in by the following JSF markup:
<p:commandLink action="#{itemController.item}">
<f:setPropertyActionListener target="#{itemController.selectedItem}" value="#{movie}" />
</p:commandLink>
(I'm using PrimeFaces in this example) The problem is that the addItemToBundle is not calling any SQL code in the console (I have FINE enabled) and the bundle never gets created or added to the user. I also tried em.persist(user) and em.flush() and setting cascadeType in my UserEntity with no luck.
#OneToMany(mappedBy="userEntity",cascade=CascadeType.PERSIST)
private Set<BundleEntity> bundleEntities;
Thanks!
You know that this:
try {
addItemToBundle(item);
} catch (NullPointerException e) {
e.getMessage();
}
is very bad practice, right? Maybe, that's the problem here, you run into a NPE and never notice it.
You should at least log the exception to know what's going on there (just for demo purposes, I've used stdout, please replace with your favorite logging framework):
try {
addItemToBundle(item);
} catch (NullPointerException e) {
System.err.println(e.getMessage()); //use logger here
}
I try to use get result from a api called j-calais, and then out put the result on a web page, i write all the code in client, but it cant compile right, dont know why??? please help. the source code like below:
there is no obvious error arise, but it cant be compile successfully..... thanks a lot:
public void onModuleLoad() {
// Create table for stock data.
stocksFlexTable.setText(0, 0, "Type");
stocksFlexTable.setText(0, 1, "Name");
// Assemble Add Stock panel.
addPanel.add(newSymbolTextBox);
addPanel.add(addStockButton);
// Assemble Main panel.
mainPanel.add(stocksFlexTable);
mainPanel.add(addPanel);
mainPanel.add(lastUpdatedLabel);
// Associate the Main panel with the HTML host page.
RootPanel.get("stockList").add(mainPanel);
// Move cursor focus to the input box.
newSymbolTextBox.setFocus(true);
// Listen for mouse events on the Add button.
addStockButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
try {
addStock();
} catch (Exception e) {
e.printStackTrace();
}
}
});
// Listen for keyboard events in the input box.
newSymbolTextBox.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event) {
if (event.getCharCode() == KeyCodes.KEY_ENTER) {
try {
addStock();
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
private void addStock() throws Exception {
final String url_s = newSymbolTextBox.getText().toUpperCase().trim();
newSymbolTextBox.setFocus(true);
newSymbolTextBox.setText("");
int row = stocksFlexTable.getRowCount();
CalaisClient client = new CalaisRestClient("ysw5rx69jkvdnzqf6sgjduqj");
System.out.print("read success...\n");
URL url = new URL(url_s);
CalaisResponse response = client.analyze(url);
for (CalaisObject entity : response.getEntities()) {
System.out.println(entity.getField("_type") + ":"
+ entity.getField("name"));
stocks.add(entity.getField("_type"));
stocksFlexTable.setText(row, 0, entity.getField("_type"));
stocksFlexTable.setText(row, 1, entity.getField("name"));
}
for (CalaisObject topic : response.getTopics()) {
System.out.println(topic.getField("categoryName"));
}
}
}
GWT only handles unchecked exceptions so you can throw Runtime Exceptions
or write your own Exception that extends from Runtime Exception then it will not cause any compile time problem
void f() throws NullPointerException // will not cause any problem because it is Runtime exception so unchecked
void f() throws IllegalAccessException // it is checked exception so there will be problem at compile time