Getting NullPointerException while fetching property from repository in ATG - atg

I'm trying to fetch properties like first name and last name from profile repository, displaying it in jsp using droplet. Below is my sample code:
SampleDroplet.java
public class SampleDroplet extends DynamoServlet {
private Repository mProfileRepository;
#Override
public void service(DynamoHttpServletRequest pReq, DynamoHttpServletResponse pRes)
throws ServletException, IOException {
String lFirstName = null;
String lLastName = null;
String lProfileId = pReq.getParameter("profileId");
try {
RepositoryItem lItem = getProfileRepository().getItem(lProfileId, "user");
lFirstName = (String) lItem.getPropertyValue("firstName");
lLastName = (String) lItem.getPropertyValue("lastName");
} catch (RepositoryException e) {
e.printStackTrace();
}
pReq.setParameter("firstName", lFirstName);
pReq.setParameter("lastName", lLastName);
pReq.serviceParameter("output", pReq, pRes);
}
SampleDroplet.properties
$class=com.tap.droplet.SampleDroplet
scope=global
profileRepository=/atg/userProfiling/ProfileAdaptarRepository
SampleDroplet.jsp
<dsp:page>
<dsp:importbean bean="/atg/userprofiling/Profile" var="profile" />
<dsp:importbean bean="/com/tap/droplet/SampleDroplet" />
<dsp:getvalueof var="profileId" bean="Profile.id"/>
<dsp:droplet name="SampleDroplet">
<dsp:param name="profileId" value="${profileId}" />
<dsp:oparam name="output">
Profile's First Name : <dsp:valueof param="firstName"/>
Last Name : <dsp:valueof param="lastName"/>
</dsp:oparam>
</dsp:droplet>
</dsp:page>
I've tried displaying profileId in jsp it is working. But when i passed it to droplet it is showing NullPointerException
java.lang.NullPointerException
at com.tap.droplet.SampleDroplet.service(SampleDroplet.java:26)
at atg.servlet.DynamoServlet.service(DynamoServlet.java:152)
at atg.taglib.dspjsp.DropletTag.invokeServlet(DropletTag.java:420)
at atg.taglib.dspjsp.DropletTag.doAfterBody(DropletTag.java:705)
at jsp_servlet._test._droplet.__sampledroplet._jsp__tag18(__sampledroplet.java:874)
Truncated. see log file for complete stacktrace
If anyone knows what is the issue please help me.
Thanks in advance

it looks like problem is here:
profileRepository=/atg/userProfiling/ProfileAdaptarRepository
Nucleus can't find this component:
"userprofiling" should be in lower case.
ProfileAdaptarRepository -> ProfileAdapterRepository

Related

API Automation : Assertion is not working for google place api

//Below mentioned code not working for assertion in google api
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class Base {
public static void main(String[] args) {
//URL --> End Point --> BaseURL/Resources/Format?Parameters
// BaseURL or Host
RestAssured.baseURI = "https://maps.googleapis.com";
given().
param("location","33.8670522,151.1957362").
param("radius","500").
param("key","AIzaSyDahQkqdxmUihrC0_3Gi7hRBZQWDrV1xI0").
when().
get("/maps/api/place/nearbysearch/json").
then().assertThat().statusCode(200).and().contentType(ContentType.JSON).and().
body("results[0].geometry.location.lat", equalTo("-33.8710748"));
}
}
Below error I am getting :
java.lang.AssertionError: 1 expectation failed.
JSON path results[0].geometry.location.lat doesn't match.
Expected: -33.8710748
Actual: null
Also find the original response:
https://jsoneditoronline.org/?id=7f9b24fa65f044fa9c4f48500a6c9bbe
It looks, Given Piece of Code is correct only (I hope all the applicable headers are mentioned)and valid response might not be retrieved from the API with Status Code as 200. Please extract the response and store in one variable for the debugging purpose.
Please check the below for the debugging.
public static void main(String[] args) {
//URL --> End Point --> BaseURL/Resources/Format?Parameters
// BaseURL or Host
RestAssured.baseURI = "https://maps.googleapis.com";
String result=given().
param("location","33.8670522,151.1957362").
param("radius","500").
param("key","AIzaSyDahQkqdxmUihrC0_3Gi7hRBZQWDrV1xI0").
when().
get("/maps/api/place/nearbysearch/json").
then().assertThat().statusCode(200).extract().asString();;
System.out.println(" API Response :"+ result);
}

Domino REST Service - Can't get parameter from GET Call

I can't seem to get json handed into a GET call in the serviceBean.
<xe:restService id="restService1" pathInfo="getaccount">
<xe:this.service>
<xe:customRestService requestContentType="application/json" serviceBean="web.service.GetAccount" contentType="application/json"/>
</xe:this.service>
</xe:restService>
For the pathInfo I've tried pathInfo="getaccount", pathInfo="getaccount/{id}", pathInfo="getaccount{id}"
The serviceBean:
public class GetAccount extends CustomServiceBean {
#Override
public void renderService(CustomService service, RestServiceEngine engine) throws ServiceException {
XspOpenLogUtil.logEvent(null, "getAccount()", Level.INFO, null);
Map parameters = engine.getHttpRequest().getParameterMap();
XspOpenLogUtil.logEvent(null, "getAccount() - getHttpRequest().getParameterMap(): " + parameters.toString(), Level.INFO, null);
String json_string = IOUtils.toString(engine.getHttpRequest().getInputStream(), "UTF-8");
XspOpenLogUtil.logEvent(null, "getAccount() - jsonReaderString: " + json_string, Level.INFO, null); }
I can get the json_string if I change to a POST, but I should be able to perform a GET and send some json in i.e. { "id": "1234" }
Using SoapUI with the resource as api.xsp/getaccount{id} and a parameter Name=id and Value=1234
Thanks,
Scott.
I figured it out. You can use the engine.getHttpRequest().getRequestURI(), which will give you the URI handed in e.g. api.nsf/api.xsp/getaccount/Bob.Smith%40mail.com. Run a URLDecode to cleanup the encoding.
Hope this helps others trying to sort this out.
Scott.

How would I receive all fields from a dynamic form with Struts?

I found myself with the following problem:
I have a page generated with logic:iterate that shows the current supervisor and assistant of a service.
That page also acts as a form where people can add their possible substitutes, but you never know how many of those are there.
Due to the environment I am currently working with it had to be without JSTL so a lot of options were gone; couldn't get DynaActionForm working for this either.
Since I couldn't find anything but I already got the answer I decided to create this to answer anyone who might have the same issue.
Code:
public ActionForward post(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String[] tot;
try {
Enumeration<?> fieldsForm = request.getParameterNames();
while(fieldsForm.hasMoreElements()) {
String current = (String) fieldsForm.nextElement();
tot = request.getParameterValues(current);
System.out.println("Field name is: " + current);
for (i=0; i<tot.length; i++) {
// do whatever you need to do; contents are in tot[i]
System.out.println("Value " + i + " is: " + tot[i]);
}
}
catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
}
}

How to update the tables in dataclass IBM?

I am trying to update a dataclass table with extra values after inserting some fields in the columns,again if i want insert the details in the same column,its not working,it gets in the second row,could anyone please help me,i want this answer as soon as possible
This is how I updated the row in bluemix by getting a particular column value position. Here is the code.
This is the code for getting the entire values from the bluemix table:
IBMQuery<Company> query = IBMQuery.queryForClass(Company.CLASS_NAME);
query.find().continueWith(new Continuation<List<Company>, Void>() {
public Void then(Task<List<Company>> task) throws Exception {
final List<Company> objects = task.getResult();
// Log if the find was cancelled.
if (task.isCancelled()) {
Log.e(CLASS_NAME, "Exception : Task " + task.toString()
+ " was cancelled.");
}
// Log error message, if the find task fails.
else if (task.isFaulted()) {
Log.e(CLASS_NAME, "Exception : "
+ task.getError().getMessage());
}
// If the result succeeds, load the list.
else {
companyList.clear();
for (IBMDataObject storeObject : objects) {
companyList.add((Company) storeObject);
}
if (task.isCompleted()) {
handler.sendEmptyMessage(2);
}
}
Where Company is the name of the Table and companyList is the company class array list.
After this code is executed the companylist will get all the rows and columns values stored in bluemix from which we can get the required row by using the query
query.whereKeyEqualsTo(User.RegisterName, userName);
query.whereKeyEqualsTo(User.Password, password);
Where User is the table name
RegisterName and Password are static variable defined in the User Class
userName and password is the user defined given inputs.
By getting the position of the required row retrieved in companyList, I do the update in the following way:
Company companyObject=Company.getPosition(position);
companyObject.setName("Something");
companyObject.save() query......
Now the problem is I'm able to do the update properly, but I'm not able to retrieve the table values from bluemix using the code which I mentioned in the top.
// Find a set of objects by class
IBMQuery<Item> queryByClass = IBMQuery.queryForClass(Item.class);
// Find a specific object
IBMQuery<Item> queryForObject = myItem.getQuery();
query.find().continueWith(new Continuation<List<Item>, Void>() {
#Override
public Void then(Task<List<Item>> task) throws Exception {
if (task.isFaulted()) {
// Handle errors
} else {
// do more work
List<Item> objects = task.getResult();
}
return null;
}
});
This code came from http://mbaas-gettingstarted.ng.bluemix.net/android

Twitter 4j with Netbeans

First time poster, but I'm really stuck.
I'm working on a little project and I'm trying to send out a tweet using a netbeans project. I'm using twitter4j and it seems like things have recently changed to where you have to use their OAuth function. I've created an application on twitter and tried some code but I keep getting this error:Exception in thread "main" connect timed outRelevant discussions can be on the Internet at:
http://www.google.co.jp/search?q=b2b52c28 or
http://www.google.co.jp/search?q=1b442895
TwitterException{exceptionCode=[b2b52c28-1b442895 b2b52c28-1b44286b], statusCode=-1, retryAfter=-1, rateLimitStatus=null, featureSpecificRateLimitStatus=null, version=2.2.5}
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:200)
at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:102)
at twitter4j.TwitterImpl.post(TwitterImpl.java:1929)
at twitter4j.TwitterImpl.updateStatus(TwitterImpl.java:433)
at login.Login.start(Login.java:36)
at login.Login.main(Login.java:63)
Caused by: java.net.SocketTimeoutException: connect timed out
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:75)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:388)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:483)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:213)
at sun.net.www.http.HttpClient.New(HttpClient.java:300)
at sun.net.www.http.HttpClient.New(HttpClient.java:316)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:992)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:928)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:846)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1087)
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:158)
... 6 more
Java Result: 1
I'm not entirely sure what I'm doing wrong. Below is the code I've tried.
package login;
import java.io.IOException;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
public class Login {
private final static String CONSUMER_KEY = "******";
private final static String CONSUMER_KEY_SECRET =
"******";
public void start() throws TwitterException, IOException {
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
// here's the difference
String accessToken = getSavedAccessToken();
String accessTokenSecret = getSavedAccessTokenSecret();
AccessToken oathAccessToken = new AccessToken(accessToken,
accessTokenSecret);
twitter.setOAuthAccessToken(oathAccessToken);
// end of difference
twitter.updateStatus("Hi, im updating status again from Namex Tweet for Demo");
System.out.println("\nMy Timeline:");
// I'm reading your timeline
ResponseList list = twitter.getHomeTimeline();
/* for (Status each : list) {
System.out.println("Sent by: #" + each.getUser().getScreenName()
+ " - " + each.getUser().getName() + "\n" + each.getText()
+ "\n");
}*/
}
private String getSavedAccessTokenSecret() {
// consider this is method to get your previously saved Access Token
// Secret
return "oC8tImRFL6i8TuRkTEaIcWsF8oY4SL5iTGNkG9O0Q";
}
private String getSavedAccessToken() {
// consider this is method to get your previously saved Access Token
return "102333999-M4W1Jtp8y8QY8RH7OxGWbM5Len5xOeeTUuG7QfcY";
}
public static void main(String[] args) throws Exception {
new Login().start();
}
}
Could I suggest an alternative route..
I have recently been messing around with twitter4j and I approached this slightly differently - I found a nice and easy way to authenticate the client using a ConfigurationBuilder object and passing this to the factory that is getting the instance of the Twitter object you need.
package main;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import twitter4j.conf.ConfigurationBuilder;
public class Base {
protected Twitter twitter;
//protected TwitterStream twitterStream;
private ConfigurationBuilder configBuilder;
public Base(){
configBuilder = new ConfigurationBuilder();
configBuilder.setDebugEnabled(true);
configBuilder.setOAuthConsumerKey("[consumer key here]");
configBuilder.setOAuthConsumerSecret("[consumer secret key here]");
configBuilder.setOAuthAccessToken("[OAuthAccessToken here]");
configBuilder.setOAuthAccessTokenSecret("[secret OAuthAccessToken here]");
//use the ConfigBuilder.build() method and pass the result to the TwitterFactory
TwitterFactory tf = new TwitterFactory(configBuilder.build());
//you can now get authenticated instance of Twitter object.
twitter = tf.getInstance();
}
}
You could then extend this class with sub classes that implement the functionality you require or just create the ConfigurationBuilder/TwitterFactory/Twitter objects elsewhere in your code.
Below I have implemented a class that creates status' and can return the Status object that holds additional information such as createdAt() and the ID etc etc.
package main;
import twitter4j.Status;
import twitter4j.TwitterException;
public class StatusUpdater extends Base{
public StatusUpdater(){}
public Status updateStatus(String statusToUpdate) throws TwitterException{
Status status = twitter.updateStatus(statusToUpdate);
System.out.println("statusToUpdate: " + status + ".");
return status;
}
}
Then you can use the following statement to create the status. This can be done from mbean/ejb/servlet etc.
try {
StatusUpdater statusUpdater = new StatusUpdater();
String statusTextToSet = "test status";
Status updatedStatus = statusUpdater.updateStatus(statusTextToSet);
System.out.println("Created at: " + updatedStatus.getCreatedAt());
} catch (TwitterException tex) {
System.out.println(tex.getErrorMessage());
}
More info on the configuration process here
Your code looks ok. Have you confirmed your definitely using the correct consumer key and secret for your app? Try twitter.verifyCredentials() to see if you get the same error, or a more specific error.
If you're correcting to the net via a proxy, you will need to include your proxy settings to allow the connection to succeed, details can be found here http://twitter4j.org/en/configuration.html#HTTP%20proxy%20server
As an aside, you may want to remove you access token and secret from your post, if they're still valid then someone could login to your account with them.