I'm now trying to learn Oracle ADF and I'm getting a NullPointerException while running the following code on a Java bean.
Can you help me figure out what I'm doing wrong please? This is being invoked from a button on a JSPX page.
public String cb1_action() {
try{
BindingContext bindingctx = BindingContext.getCurrent();
BindingContainer bindings = bindingctx.getCurrentBindingsEntry();
DCBindingContainer bindingsImpl = (DCBindingContainer)bindings;
DCIteratorBinding iter = bindingsImpl.findIteratorBinding("ViewObj1Iterator");
Row row = iter.getCurrentRow();
row.setAttribute("Id", 123);
row.setAttribute("Nome", "Pedro Teste");
}
catch(Exception e) {
System.out.println("Excepcao em: ");
e.printStackTrace();
}
return null;
}
According to the Stack trace, the error occurs on the first row.setAttribute() line.
Also, I'm using the latest version of JDeveloper with the integrated WebLogic server.
Best regards,
Pedro
Row row = iter.getCurrentRow();
if(row != null){
row.setAttribute("Id", 123);
row.setAttribute("Nome", "Pedro Teste"); //name?
}
The info that you get the error at
row.setAttribute("Id", 123);
let me think that you try to alter the primary key attribute of the row, which is not allowed. Not sure about this as you did not mention the error you get.
Ok, so here's how I figured out how to get around this:
First, I asked jDeveloper to generate a class for the Application Module.
In that class, I added the following methods:
public void testEntityObject()
{
System.out.println("Let's try our Entity Object...");
try
{
EntityDefImpl entity = TesteEOImpl.getDefinitionObject();
TesteEOImpl ti = (TesteEOImpl)entity.createInstance2(getDBTransaction(), null);
ti.setId(new BigDecimal(123));
ti.setNome("Entity Object test...");
getDBTransaction().commit();
System.out.println("Looks good :-)");
}
catch(Exception e)
{
System.out.println("It seems something went wrong :-(");
e.printStackTrace();
}
}
public void testViewObject() {
System.out.println("Let's try our View Object...");
ViewObjectImpl vo = this.getTeste1();
try{
Row row = vo.createRow();
row.setAttribute("Id", 234);
row.setAttribute("Nome", "VO test");
vo.insertRow(row);
getDBTransaction().commit();
System.out.println("Looks good :-)")
}
catch(Exception e) {
System.out.println("It seems something went wrong :-(");
e.printStackTrace();
}
}
These methods are being called by a managed bean that is connected to two buttons on the page. This managed bean has the following methods. I'll post just one of them as only the method names change:
public String cb1_action() {
try{
FacesContext fctx = FacesContext.getCurrentInstance();
BindingContext bindingContext = BindingContext.getCurrent();
DCDataControl dc = bindingContext.findDataControl("AppModuleAMDataControl");
AppModuleAMImpl am = (AppModuleAMImpl)dc.getDataProvider();
am.criarTesteComEntityObject();
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
I know this is not rocket science or anything but it took a while for me to get there...
Basically, your answers helped me a lot to go and investigate what was happening. The cause? Poor design! ADF is supposed to be organized...
Thank you everyone! :D
Related
I am working on a project right now where I use jsoup in a class with the function retrieveMedia in order to return an ArrayList filled with data from the webpage. I run it in a thread since you shouldn't be connecting to URLs from the main thread. I run it and join it. However, it doesn't work (I tested the same code in Eclipse separate from Android Studio and it worked fine). It seems that no matter what I do I can't get jsoup to connect to the webpage. Below is my class MediaRetriever.
public class MediaRetreiever {
public ArrayList<Media> retrieveMedia() {
ArrayList<Media> mediaOutput = new ArrayList<Media>(); //Store each scraped post
Thread downloadThread = new Thread(new Runnable() {
public void run() {
Document doc = null;
try {
doc = Jsoup.connect(<Website Im connecting to>).timeout(20000).get();
} catch (IOException e) {
System.out.println("Failed to connect to webpage.");
mediaOutput.add(new Media("Failed to connect", "oops", "", "oh well"));
return;
}
Elements mediaFeed = doc.getElementById("main").getElementsByClass("node");
for (Element e : mediaFeed) {
String title, author, imageUrl, content;
title=e.getElementsByClass("title").text().trim();
author=e.getElementsByClass("content").tagName("p").select("em").text().trim();
content=e.getElementsByClass("content").text().replace(author,"").trim();
Media media = new Media(title, author, "", content);
mediaOutput.add(media);
}
}
});
downloadThread.start();
try {
downloadThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return mediaOutput;
}
}
Running this class's method from another class and it doesn't ever connect. Any ideas?
Since you say that the problem persists only in Android, it looks like that you should add the user agent string to your request - first get the user agent string of a browser that displays correctly the site, and then add it to the request:
doc = Jsoup.connect(<Website Im connecting to>)
.userAgent("your-user-agent-string")
.timeout(20000).get();
And as a sidenote - if you are catching exception, don't print your own error message - print the original message, it may be very useful.
I'm trying to redirect a new page with this syntax
try {
usuarios usu = new usuarios();
usu.setNombreusuario(request.getParameter("parCodigo"));
System.out.println(usu.getUsuario());
usu.setContrasena(request.getParameter("parContrasenha"));
System.out.println(usu.getContrasena());
usu = usuariosDAO.login(usu);
System.out.println("es valido? " + usu.isValid());
if (usu.isValid()) {
HttpSession session = request.getSession(true);
session.setAttribute("usuario", usu.getUsuario());
response.sendRedirect("/KolaEscocesaCRM/menumobile.jsp");
return;
} else {
response.sendRedirect("/KolaEscocesaCRM/loginmobile.jsp");
}
} catch (Exception ex) {
ex.printStackTrace();
}
My problem is that when I submit I get this:
http://localhost:8084/KolaEscocesaCRM/srvMenu2?parCodigo=admin&parContrasenha=kola
I don't know what to do please any help would be fine
If you get a dear 404
Most of the time, because the entry application is mapped into something like /myapp instead of /(root)
The server says to the browser go to /KolaEscocesaCRM/loginmobile.jsp where it should be /.myapp/KolaEscocesaCRM/loginmobile.jsp
The simplest way is changing the context-path to root (/ or empty string)
Im working with orient db where i have to export specified data tables using java. Here is the code im working with:
ODatabaseDocumentTx db = new ODatabaseDocumentTx("remote:localhost/sampleDB").open("admin", "admin");
try {
OCommandOutputListener listener = new OCommandOutputListener() {
#Override
public void onMessage(String iText) {
// System.out.print(iText);
}
};
Set<String> abcd = new HashSet<String>();
abcd.add("sample_demo1_OnlineShopping");
System.out.println(abcd);
ODatabaseExport export = new ODatabaseExport(db, "DataCont/Data.gz", listener);
export.setIncludeInfo(false);
export.setIncludeClusterDefinitions(false);
export.setIncludeSchema(false);
export.setIncludeIndexDefinitions(false);
export.setIncludeManualIndexes(false);
export.setIncludeClasses(abcd);
// export.exportRecords();
export.exportDatabase();
export.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
db.close();
}
The problem is, its not including any classes. Output file was like this:
{"records":[]}
But when i tries without the "setIncludeClasses" it prints all the classes available in the database. What would the issue for this problem. Thanks in advance.
Change this line to:
abcd.add("sample_demo1_OnlineShopping".toUpperCase());
I haven't found it in the documentation, but includeClasses is expecting classes in UpperCase (same for excludeClasses).
See the source code.
How can i implement theming support in Play Framework 2?
I want to create directory structure like:
views/default <- default template directory
views/site1 <- template for site 1
views/site2 <- template for site 2
If template doesn`t exist (ie. views/site1/home) it should render template from default directory.
I have tried cls = Class.forName("views.html.home); But I get class not found exception.
SOLUTION:
Maybe someone will find this useful:
protected static String renderTemplate(final String template, final String action,final ViewData templateParams) {
Class<?> cls = null;
String ret = "Template not found";
try {
cls = Class.forName(template);
} catch (ClassNotFoundException e) {
ret = e.toString();
}
if (cls == null) {
try {
cls = Class.forName("views.html.default."+action);
} catch (ClassNotFoundException e) {
ret = e.toString();
}
}
if (cls != null) {
Method htmlRender;
try {
htmlRender = cls.getMethod("render", ViewData.class);
ret = htmlRender.invoke("",templateParams).toString();
} catch (NoSuchMethodException e) {
ret = "Method not found"+e.toString();
} catch (IllegalAccessException e) {
ret = "illegal access exception";
} catch (InvocationTargetException e) {
ret = "InvocationTargetException";
}
}
return ret;
}
ViewData vd=new ViewData();
renderTemplate("views.html.custom."+viewname, actionname, vd)
You have to implement it yourself, as a reference, check the Play Authenticate usage sample, it allows to send ie. validation emails basing on Play's template and depending on the client's language, so for an instance, if your main language is Polish it will render the verify_email_pl.scala.html otherwise if your browser uses language not supported by PA, it will silently fallback to: verify_email_en.scala.html.
Check the usage and declaration of the method.
For your case it will be good solution, of course just criteria of the choice will be different.
This process is called "Branding". What you have to do is following.
Create a table in db by name "BRANDING" and add theme names in it against each instance of website.
Now you will make folders hierarchy as you mentioned and in jsp pages where load css files you will do that like this <link rel="stylesheet" type="text/css" href="/views/${themeName}.css">
where themeName would be a server side variable that you will program in your controller to be fetched from db or first time you will fetch it and then cache it.
I am new to the twitter4j api, is there any way of getting no of favorite count for a particular tweet using twitter4j. I am using api version 3.0.3 for Twitter4j.
In documentation the method getFavoriteCount() is present but the same method gives compilation error in code. Should I use different version of jar file?
public static void main(String[] args) {
ConfigurationBuilder cb= new ConfigurationBuilder();
cb.setDebugEnabled(true);
cb.setOAuthConsumerKey("**************************");
cb.setOAuthConsumerSecret("**************************");
cb.setOAuthAccessToken("*******************************");
cb.setOAuthAccessTokenSecret("*****************************");
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
User user = null;
try {
user = twitter.verifyCredentials();
} catch (TwitterException e1) {
e1.printStackTrace();
}
String[] test = new String[]{"teststr"};
ResponseList<User> users;
try {
users = twitter.lookupUsers(test);
for (User user1 : users) {
if (user1.getStatus() != null)
{
Paging paging = new Paging(1, 40);
ResponseList<Status> statusess = twitter.getUserTimeline(user1.getName(),paging);
for (Status status3 : statusess)
{
long retweetCount = status3.getRetweetCount();
long favoriteCount = status3.getFavoriteCount();/** this line gives compilation error saying the method getFavoriteCount() is undefined for the type Status**/
}
}
}
} catch (TwitterException e) {
e.printStackTrace();
}
}
Unfortunately, it seems like the JavaDocs on the Twitter4J site linked next to the 3.0.3 release are not correct. The actual docs are here - you can see that getFavoriteCount() isn't present in these.
It looks like Status#getFavoriteCount() was only introduced in 3.0.4. So yes, you need to upgrade from 3.0.3 in order to use this method.
Although be aware that version 3.0.4 looks like it is under active development presently.
Although you have already found and marked an answer, let me provide an alternate to switching the Twitter4J version.
When using a method similar to what you are using, I had searched a lot and finally found the solution in an entirely unrelated post. Here is how you can get the Favorite count of tweets:
NOTE: This is what I use in an Android app of mine.
First, in your ConfigurationBuilder cb instance, add this one line:
cb.setJSONStoreEnabled(true);
This will return all results in a JSON format. Strangely, getting a JSON result it provides you that value.
Now, to fetch the Tweets:
try {
Paging paging = new Paging(initPagingOffset, 200);
statuses = twitter.getHomeTimeline(paging);
String strTweets = DataObjectFactory.getRawJSON(statuses);
JSONArray JATweets = new JSONArray(strTweets);
for (int i = 0; i < JATweets.length(); i++) {
JSONObject JOTweets = JATweets.getJSONObject(i);
..... // PARSE ANY OTHER DATA YOU MIGHT NEED FOR DISPLAYING THE TWEETS
String FAV_COUNT = JOTweet.getString("favorite_count");
}
} catch (TwitterException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}