I have successfully retrieved a Contact Entry from Google Contacts, but I couldn't get the Notes field yet. How can I do that?
This is part of what I have done so far...
public static void main(String[] args) throws IOException, ServiceException, SQLException {
System.out.println("Start elaboration");
Credential credential =authorize();
if (!credential.refreshToken()) {
throw new RuntimeException("Failed OAuth to refresh the token");
}
ContactsService myService = new ContactsService(APPLICATION_NAME);
myService.setOAuth2Credentials(credential);
URL feedUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full");
Query Query = new Query(feedUrl);
Query.setMaxResults(32767);
ContactFeed feed=null;
try {
feed = myService.query(Query, ContactFeed.class);
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (ContactEntry contact : feed.getEntries()) {
if (contact.hasName()) {
Name name = contact.getName();
if (name.hasFullName()) {
String fullNameToDisplay = name.getFullName().getValue();
if (name.getFullName().hasYomi()) {
fullNameToDisplay += " (" + name.getFullName().getYomi() + ")";
}
System.out.println("Full Name = " + fullNameToDisplay);
}
}
/*
* insert here the code to retrive Notes Field
*/
}
System.out.println("End elaboration");
}
Related
I'm trying to perform a batch operation in QuickBook but getting null callbackhandler.
private static void AddBulkCustomer(DataService ds) throws FMSException{
BatchOperation bo = new BatchOperation();
Customer c1 = new Customer();
c1.setGivenName("Customer 3");
c1.setDisplayName("Disp Customer 3");
EmailAddress email = new EmailAddress();
email.setAddress("customer1#zzz.com");
c1.setPrimaryEmailAddr(email);
bo.addEntity(c1, OperationEnum.CREATE, "b3");
c1= null;
c1 = new Customer();
c1.setGivenName("Customer 4");
c1.setDisplayName("Disp Customer 4");
email = null;
email = new EmailAddress();
email.setAddress("customer2#z2zz.com");
c1.setPrimaryEmailAddr(email);
bo.addEntity(c1, OperationEnum.CREATE, "b4");
// String strQuery = " select * from customer where givenname ='"+c1.getGivenName()+"'";
// bo.addQuery(strQuery, "b3Query");
ds.executeBatchAsync(bo, new AsyncCallBackBatch());
}
For AsyncCallback operation
public class AsyncCallBackBatch implements CallbackHandler {
#Override
public void execute(CallbackMessage callbackMsg) {
System.out.println("asyncCallbackBatch is executing... ");
try {
System.out.println("QR = "+callbackMsg.getFMSException().toString());
BatchOperation BO = callbackMsg.getBatchOperation();
if (BO != null) {
List<String> bId = BO.getBIds();
for (String strBId : bId) {
if (BO.isFault(strBId)) {
Fault fault = BO.getFault(strBId);
System.out.println("asyncCallBackBatch Error Code : "+ fault.getError().get(0).getCode() + " "+ "Error : "
+ fault.getError().get(0).getDetail()+ ", Message : "+ fault.getError().get(0).getMessage());
} else if (BO.isEntity(strBId)) {
System.out.println("Batch having entity message.. ");
Customer cust = (Customer) BO.getEntity(strBId);
System.out.println("cust id : " + cust.getId()+ " CustName = " + cust.getGivenName());
} else if (BO.isQuery(strBId)) {
System.out.println("Batch having Query ... Parsing... ");
QueryResult qR = BO.getQueryResponse(strBId);
System.out.println("Query : " + qR.getTotalCount());
} else if (BO.isReport(strBId)) {
System.out.println("Batch having Report... ");
Report report = BO.getReport(strBId);
System.out.println(" " + report.getClass().getName());
} else {
System.out.println("Something went wrong... ");
}
}
}else{
System.out.println("Batch Operation terminated, reason: NULL callbackMsg ");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
OAuthAuthorizer oAuth = new OAuthAuthorizer(consumerKey, consumerSecret, accessToken, accessTokenSecret);
//403352746
try {
Context context = new Context(oAuth, ServiceType.QBO, "403352746");
System.out.println("RealmID : "+context.getRealmID());
context.setCustomerRequestTimeout(99999);
System.out.println("TimeOut Set to = "+context.getCustomerRequestTimeout());
System.out.println("BASE_URL_QBO = "+Config.getProperty(Config.BASE_URL_QBO));
Config.setProperty(Config.BASE_URL_QBO, "https://sandbox-quickbooks.api.intuit.com/v3/company");
System.out.println("BASE_URL_QBO = "+Config.getProperty(Config.BASE_URL_QBO));
DataService ds = new DataService(context);
AddBulkCustomer(ds);
System.out.println("Operation Complete..");
} catch (Exception e) {
e.printStackTrace();
}
}
When I debug, in execute method, I'm getting Null BatchOperation in return. I'm not sure performing Batch operation is allowed in sandbox environment.
I found the solution after so much of testing and communication with Quickbooks Devs thought would be helpful for others.
In sandbox environment even if you set the config properties to sandbox URL it still picks as PROD URL in Callbackhandler.
Config.setProperty(Config.BASE_URL_QBO, "https://sandbox-quickbooks.api.intuit.com/v3/company");
In this case they called this as a bug, currently all you can do is to make a trial account in PROD and then test this.
I want to create an android GCM sender which will send the URL to the Android app. I have used this windows application to test my android app and it is working. I checked the code in C# and tried to convert it in Java. But I am not getting anything. Let me know what I am missing.
import java.util.*;
import java.util.logging.Logger;
import java.io.*;
import java.net.*;
import java.net.ProtocolException;
//import org.apache.http.HttpResponse;
import org.apache.http.*;
import org.apache.http.util.EntityUtils;
public class Client {
String device_id;
String api_id;
String Msg;
String ResultJSON;
private String GCM_URI = "https://android.googleapis.com/gcm/send";
HttpURLConnection gcmRequest = null;
HttpResponse gcmResponse = null;
Client()
{
//default constructor...do nothing
}
Client(String dev, String auth)
{
this.device_id = dev;
this.api_id = auth;
}
public String Send(String message) throws IOException
{
// Escape condition
if (device_id == null || api_id == null)
{
return "[ERROR] Device Token or API Key has not been set";
}
InitGCMClient();
PostPayload(message);
/*gcmResponse = (HttpResponse) gcmRequest.getResponseMessage();
catch (WebException we)
{
return "[ERROR] There is a problem within processing GCM message \n" + we.Message;
}*/
try {
System.out.println(gcmRequest);
ResultJSON = gcmRequest.getResponseMessage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ResultJSON;
}
public String ReadResponse(HttpResponse response)
{
//StreamReader responseReader = new StreamReader(response.GetResponseStream());
//return responseReader.ReadToEnd();
try {
String responseString = EntityUtils.toString(response.getEntity());
return responseString;
} catch (ParseException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private void InitGCMClient()
{
URL obj = null;
try {
obj = new URL(GCM_URI);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
gcmRequest = (HttpURLConnection) obj.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
gcmRequest.setRequestProperty("Content-Type", "application/json");
gcmRequest.setRequestProperty("User-Agent", "Android GCM Message Sender Client 1.0");
gcmRequest.setRequestProperty("Authorization", "key=" + api_id);
try {
gcmRequest.setRequestMethod("POST");
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void PostPayload(String message) throws IOException
{
String payloadString = AssembleJSONPayload(device_id, message);
byte[] payloadByte = payloadString.getBytes("UTF-8");
//gcmRequest.ContentLength = payloadByte.length;
String len = new String(payloadByte);
gcmRequest.setRequestProperty("Content-Length", len);
gcmRequest.setDoOutput(true);
gcmRequest.setDoInput(true);
OutputStream payloadStream = gcmRequest.getOutputStream();
payloadStream.write(payloadByte, 0, payloadByte.length);
payloadStream.close();
}
public String AssembleJSONPayload(String gcmDeviceToken, String gcmBody)
{
String payloadFormatJSON =
"{{" +
"\"registration_ids\" : [\"" + gcmDeviceToken + "\"]," +
"\"data\" : {{" +
" " + gcmBody + " " +
"}}" +
"}}";
String payload = String.format(payloadFormatJSON, gcmDeviceToken, gcmBody);
//Debug.WriteLine("payload : " + payload);
System.err.println("payload : " + payload);
return payload;
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String dev = "<device_ID>";
String auth = "<api_ID>";
Client cl = new Client(dev, auth);
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
while(true)
{
System.out.println("\nSend your msg\n");
String msg = sc.nextLine();
cl.Send(msg);
}
}
}
I just started working on Android. So kindly let me know if there are any relevant suggestions as well.
Input:
"key" : "http://upload.wikimedia.org/wikipedia/commons/2/23/Lake_mapourika_NZ.jpeg"
In Console, I am getting:
payload : {{"registration_ids" : ["device_id"],"data" : {{ "key" : "http://upload.wikimedia.org/wikipedia/commons/2/23/Lake_mapourika_NZ.jpeg" }}}}
EDIT
Your payload message inside AssembleJSONPayload is not formatted correctly. Please use following code to build payload:
String payloadFormatJSON =
"{" +
"\"registration_ids\" : [\"" + gcmDeviceToken + "\"]," +
"\"data\" : {" +
" " + gcmBody + " " +
"}" +
"}";
Output should be:
payload : {"registration_ids" : ["gcmDeviceToken value"],"data" : {"gcmBody value"}}
I'm building an application where I need to connect to Active Directory using UnboundID. Using an example, I managed to connect a user with their distinguishedName and password.
However I would like to authenticate them using only the domain and the username, similar to how it's done in Windows. Browsing AD using a tool called JXplorer it seems like the sAMAccountName might be the property I need. However replacing the distinguishedName with the sAMAccountName resulted in an AcceptSecurityContext error. Using the "uid=..." syntax shown in the example also yielded the same error.
Is there a way to logon using only the domain, username/sAMAccountName and password. or do I somehow need to search through AD and find the distinguishedName of the user I wish to authenticate, and then bind the connection using their distinguishedName and password?
As #ioplex said in his comment, AD accepts a bind using the username from the sAMAccountName with the domain name appended to it. Just use it instead of the DN on the bind:
String userId = username + "#" + domain;
SimpleBindRequest adminBindRequest = new SimpleBindRequest(userId, passsword);
The final userId will be something like 'eharris#contoso.local'
You will need to use an account with appropriate permissions to perform a search for samAccountName to locate the user and then bind as the found user using the Distinguished Name.
You need to be sure you only return one entry from the search.
Sample For Demonstration Purposes ONLY!
Parameters would be something like:
"adldap.example.com" "CN=bob,OU=Users,DC=example,DC=com" "connPwd" "OU=Users,DC=example,DC=com" "samAccountName" "findUserValue" "userPassword"
/**
* #author jwilleke <br/>
* Use For Demonstration Purposes ONLY!
* #param args
*/
public static void main(String[] args)
{
String connHost = args[0];
String connID = args[1];
String connPwd = args[2];
String searchBase = args[3];
String findUserByAttribute = args[4];
String findUserValue = args[5];
String userPassword = args[6];
int connPort = 389;
// TODO Auto-generated method stub
String actualLDAPServer = null;
RootDSE rootDSE = null;
// If I were doing this for real, I would use a POOL for Connections
SSLUtil sslUtil = new SSLUtil(new TrustAllTrustManager()); // Use For Demonstration Purposes ONLY!
SSLSocketFactory sslSocketFactory = null;
try
{
sslSocketFactory = sslUtil.createSSLSocketFactory();
}
catch (GeneralSecurityException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
SimpleBindRequest adminBindRequest = new SimpleBindRequest(connID, connPwd);
LDAPConnection adminConnection = new LDAPConnection(sslSocketFactory);
try
{
adminConnection = new LDAPConnection(connHost, connPort);
log.debug("Successful LDAP adminConnection to:" + connHost + ":" + connPort);
adminConnection.bind(adminBindRequest);
log.debug("Successful Bind as:" + connID);
}
catch (LDAPException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
LDAPConnection userConnection = new LDAPConnection(sslSocketFactory);
try
{
userConnection = new LDAPConnection(connHost, connPort);
log.debug("Successful LDAP userConnection to:" + connHost + ":" + connPort);
}
catch (LDAPException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
// Construct Filter to find user
Filter findUserfilter = null;
findUserfilter = Filter.createEqualityFilter(findUserByAttribute, findUserValue);
// Create Search Request
SearchRequest searchRequest = new SearchRequest(searchBase, SearchScope.SUB, findUserfilter);
searchRequest.setSizeLimit(1); // We will error if we get more than one hit
SearchResult searchResult = null;
try
{
searchResult = adminConnection.search(searchRequest);
}
catch (LDAPSearchException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
String userDN = null;
if (searchResult.getEntryCount() > 1)
{
log.error("We got more than one Entry for:" + searchRequest.getFilter());
}
if (searchResult.getEntryCount() == 0)
{
log.error("We got No Entries for:" + searchRequest.getFilter());
}
for (SearchResultEntry entry : searchResult.getSearchEntries())
{
userDN = entry.getDN();
log.debug("Found an Entry: " + userDN);
}
SimpleBindRequest userBindRequest = new SimpleBindRequest(userDN, userPassword);
if (userBindRequest.getBindDN() == null)
{
log.warn("We got a null for the userBindRequest UserDN and therefore the bind is anonymous !");
}
if (userBindRequest.getPassword() == null)
{
log.warn("We got a null for the userBindRequest Password and therefore the bind is anonymous !");
}
try
{
userConnection.bind(userDN, userPassword);
log.debug("Successful userConnection Bind as:" + userDN);
}
catch (LDAPException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
-jim
I am trying to create a app for fitbit using fitbit4j . I found their sample code
at
https://github.com/apakulov/fitbit4j/blob/master/fitbit4j-example-client/src/main/java/com/fitbit/web/FitbitApiAuthExampleServlet.java
When i tried to implement it I am getting many errors.
below is their doGet function()
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
FitbitAPIClientService<FitbitApiClientAgent> apiClientService = new FitbitAPIClientService<FitbitApiClientAgent>(
new FitbitApiClientAgent(apiBaseUrl, fitbitSiteBaseUrl, credentialsCache),
clientConsumerKey,
clientSecret,
credentialsCache,
entityCache,
subscriptionStore
);
if (request.getParameter("completeAuthorization") != null) {
String tempTokenReceived = request.getParameter(OAUTH_TOKEN);
String tempTokenVerifier = request.getParameter(OAUTH_VERIFIER);
APIResourceCredentials resourceCredentials = apiClientService.getResourceCredentialsByTempToken(tempTokenReceived);
if (resourceCredentials == null) {
throw new ServletException("Unrecognized temporary token when attempting to complete authorization: " + tempTokenReceived);
}
// Get token credentials only if necessary:
if (!resourceCredentials.isAuthorized()) {
// The verifier is required in the request to get token credentials:
resourceCredentials.setTempTokenVerifier(tempTokenVerifier);
try {
// Get token credentials for user:
apiClientService.getTokenCredentials(new LocalUserDetail(resourceCredentials.getLocalUserId()));
} catch (FitbitAPIException e) {
throw new ServletException("Unable to finish authorization with Fitbit.", e);
}
}
try {
UserInfo userInfo = apiClientService.getClient().getUserInfo(new LocalUserDetail(resourceCredentials.getLocalUserId()));
request.setAttribute("userInfo", userInfo);
request.getRequestDispatcher("/fitbitApiAuthExample.jsp").forward(request, response);
} catch (FitbitAPIException e) {
throw new ServletException("Exception during getting user info", e);
}
} else {
try {
response.sendRedirect(apiClientService.getResourceOwnerAuthorizationURL(new LocalUserDetail("-"), exampleBaseUrl + "/fitbitApiAuthExample?completeAuthorization="));
} catch (FitbitAPIException e) {
throw new ServletException("Exception during performing authorization", e);
}
}
}
When i run the code it goes into the 'else' part first and i get the URL with
localhost:8080/fitbitApiAuthExample?completeAuthorization=&oauth_token=5bccadXXXXXXXXXXXXXXXXXXXXXXXXXX&oauth_verifier=h35kXXXXXXXXXXXXXXXXX, and i get the fitbit login screen and when i log in
and since the
'completeAuthorization==null',
it is executing the else part again.So i manually added a value so that it will enter the 'if' section .
So the new URL became
localhost:8080/fitbitApiAuthExample?completeAuthorization=Success&oauth_token=5bccadXXXXXXXXXXXXXXXXXXXXXXXXXX&oauth_verifier=h35kXXXXXXXXXXXXXXXXX and entered the 'if' section.
Now am getting the exception
'Unrecognized temporary token when attempting to complete authorization:'I tried many workarounds but still cant understand the error.
Please Help.
Solved the problem. the 'apiClientService' was going null when i reload the servlet. Made it member variable and everything started working.
public class NewServlet extends HttpServlet {
public String apiBaseUrl = "api.fitbit.com";
public String webBaseUrl = "https://www.fitbit.com";
public String consumerKey = "your key";
public String consumerSecret = "your secret";
public String callbackUrl = "*****/run?Controller=Verifier";
public FitbitAPIClientService<FitbitApiClientAgent> apiClientService = null;
public String oauth_token = null;
public String oauth_verifier = null;
public String token = null;
public String tokenSecret = null;
public String userId = null;
public APIResourceCredentials resourceCredentials=null;
public FitbitApiClientAgent agent =null;
public LocalUserDetail user=null;
public Gson gson =null;
public UserInfo userInfo=null;
private static Properties getParameters(String url) {
Properties params = new Properties();
String query_string = url.substring(url.indexOf('?') + 1);
String[] pairs = query_string.split("&");
for (String pair : pairs) {
String[] kv = pair.split("=");
params.setProperty(kv[0], kv[1]);
}
return params;
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ParserConfigurationException, SAXException, Exception {
PrintWriter out = response.getWriter();
response.addHeader("Access-Control-Allow-Origin", "*");
// out.println(" ----- process Request Called-----");
String controllerValue = request.getParameter("Controller");
// out.println(" Controller Request : "+param);
if (controllerValue == null) {
// out.println(" inside if part ");
FitbitAPIEntityCache entityCache = new FitbitApiEntityCacheMapImpl();
FitbitApiCredentialsCache credentialsCache = new FitbitApiCredentialsCacheMapImpl();
FitbitApiSubscriptionStorage subscriptionStore = new FitbitApiSubscriptionStorageInMemoryImpl();
FitbitApiClientAgent apiClientAgent = new FitbitApiClientAgent(apiBaseUrl, webBaseUrl, credentialsCache);
out.println("testing2");
apiClientService
= new FitbitAPIClientService<FitbitApiClientAgent>(
apiClientAgent,
consumerKey,
consumerSecret,
credentialsCache,
entityCache,
subscriptionStore
);
// out.println("<script>localStorage.setItem('api',apiClientService);</script>");
LocalUserDetail userDetail = new LocalUserDetail("-");
try {
// out.println("testing4");
String authorizationURL = apiClientService.getResourceOwnerAuthorizationURL(userDetail, callbackUrl);
out.println("access by web browser: " + authorizationURL);
out.println("Your web browser shows redirected URL.");
out.println("Input the redirected URL and push Enter key.");
response.sendRedirect(authorizationURL);
} catch (FitbitAPIException ex) {
out.println("exception : " + ex);
//Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (controllerValue.equalsIgnoreCase("Verifier")) {
oauth_token = request.getParameter("oauth_token");
oauth_verifier = request.getParameter("oauth_verifier");
resourceCredentials = apiClientService.getResourceCredentialsByTempToken(oauth_token);
if (resourceCredentials == null) {
out.println(" resourceCredentials = null ");
throw new Exception("Unrecognized temporary token when attempting to complete authorization: " + oauth_token);
}
if (!resourceCredentials.isAuthorized()) {
resourceCredentials.setTempTokenVerifier(oauth_verifier);
apiClientService.getTokenCredentials(new LocalUserDetail(resourceCredentials.getLocalUserId()));
}
userId = resourceCredentials.getLocalUserId();
token = resourceCredentials.getAccessToken();
tokenSecret = resourceCredentials.getAccessTokenSecret();
user = new LocalUserDetail(userId);
userInfo = apiClientService.getClient().getUserInfo(new LocalUserDetail(resourceCredentials.getLocalUserId()));
user = new LocalUserDetail(userId);
agent = apiClientService.getClient();
response.sendRedirect("http://localhost:8084/FitbitClientCheck/");
}
I am developping J2EE application with appfuse , i have a webform called easyVolAction that contain a method search() I need to save the result of search method in database but and an excpetion is generated when clicking in the action search :NullPointerException in object trajet .I created TrajetDaoHibernate:
public TrajetDaoHibernate() {
super(TrajetModel.class);
}
/**
* {#inheritDoc}
*/
#SuppressWarnings("unchecked")
public List<TrajetModel> getTrajet() {
Session session = getSessionFactory().getCurrentSession();
Query qry = session.createQuery("from TrajetModel u order by upper(u.id)");
return qry.list();
}
/**
* {#inheritDoc}
*/
public TrajetModel saveTrajet(TrajetModel trajet) {
if (log.isDebugEnabled()) {
log.debug("user's id: " + trajet.getId());
}
Session session = getSessionFactory().getCurrentSession();
session.saveOrUpdate(trajet);
// necessary to throw a DataIntegrityViolation and catch it in UserManager
session.flush();
return trajet;
}
#Override
public TrajetModel save(TrajetModel trajet) {
return this.saveTrajet(trajet);
}
and TrajetDao:
public interface TrajetDao extends GenericDao {
List<TrajetModel> getTrajet();
TrajetModel saveTrajet(TrajetModel trajet);
}
and trajetManager:
#Service("trajetManager")
public class TrajetModelImpl extends GenericManagerImpl<TrajetModel, Long> implements TrajetManager {
private TrajetDao trajetDao;
#Autowired
public void setTrajetModelDao(TrajetDao trajetDao) {
this.dao = trajetDao;
this.trajetDao = trajetDao;
}
/**
* {#inheritDoc}
*/
public TrajetModel getTrajet(String trajetId) {
return trajetDao.get(new Long(trajetId));
}
/**
* {#inheritDoc}
*/
public List<TrajetModel> getTrajet() {
return trajetDao.getAllDistinct();
}
/**
* {#inheritDoc}
*/
public TrajetModel saveTrajet(TrajetModel trajet) throws TrajetExistsException {
try {
return trajetDao.saveTrajet(trajet);
} catch (DataIntegrityViolationException e) {
//e.printStackTrace();
log.warn(e.getMessage());
throw new TrajetExistsException("Trajet '" + trajet.getNom() + "' already exists!");
} catch (JpaSystemException e) { // needed for JPA
//e.printStackTrace();
log.warn(e.getMessage());
throw new TrajetExistsException("Trajet '" + trajet.getNom() + "' already exists!");
}
}
}
finnaly the action where i declare the search method:
public String recherche() throws IOException, TrajetExistsException {
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
// String url1 =
// FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("hidden");
String departAller = request.getParameter("easyVolRobot:villeDepart");
String arriveeAller = request.getParameter("easyVolRobot:villeArrivee");
String jourAller = request.getParameter("easyVolRobot:jourDep");
String moisAller = request.getParameter("easyVolRobot:dateDep");
String jourRetour = request.getParameter("easyVolRobot:jourDep");
String moisRetour = request.getParameter("easyVolRobot:dateArr");
String jourAllerPlus1 = jourAller + 1;
parametre = "departAller=" + departAller + "&arriveeAller="
+ arriveeAller + "&jourAller=" + jourAller + "&moisAller="
+ moisAller + "&jourRetour=" + jourRetour + "&moisRetour="
+ moisRetour;
parametre1 = "departAller=" + departAller + "&arriveeAller="
+ arriveeAller + "&jourAller=" + jourAllerPlus1 + "&moisAller="
+ moisAller + "&jourRetour=" + jourRetour + "&moisRetour="
+ moisRetour;
String response = sendGetRequest(url, parametre);
// insert();
PrintStream out = null;
try {
out = new PrintStream(new FileOutputStream(
"/data/crawl/root/siteSNCF.html"));
out.print(response);
} finally {
if (out != null)
out.close();
}
// tableau de resultats des trajets
List<TrajetModel> listTrajets = new ArrayList<TrajetModel>();
// trajet
//TrajetModel trajet = new TrajetModel();
File input = new File("/data/crawl/root/siteSNCF.html");
Document doc = Jsoup.parse(input, "UTF-8",
"http://www.easyvols.org/france-voyage");
for (Element vol : doc.select("div.vols")) {
//trajet = new TrajetModel();
for (Element allerRetour : vol.select("div.aller-retour")) {
Elements aeroport = allerRetour.select("div.aeroport");
System.out.println(aeroport.text());
Elements depart = allerRetour.select("div.depart");
Elements arrive = allerRetour.select("div.arrivee");
Elements date = allerRetour.select("div.date");
trajet.setNom(aeroport.text());
trajet.setVilleDepart(depart.text());
trajet.setVilleArrive(arrive.text());
trajet.sethArrive(12);
trajet.sethDepart(11);
trajet.sethReqt(14);
}
Elements prix2 = vol.select("div.tarif");
trajet.setPrice(prix2.text());
trajet = trajetManager.saveTrajet(trajet);
System.out.println(trajet);}
return"mainMenu";
}
why you comment this line out?
//TrajetModel trajet = new TrajetModel();
I see no other line where you create the TrajetModel.
If that object is not initiated you get the NPE here:
trajet.setNom(aeroport.text());