I'm trying to make an application for my school website (reggienet.illinoisstate.edu), but I'm having trouble getting entering the login and having it stored in the cookies that I am logged in. I've scoured the web and tried everything I could find, but nothing is working I'm totally lost.
Here is the code that I have right now
public void login()
{
HtmlPage currentPage = null;
Scanner keyboard = new Scanner(System.in);
WebClient webClient = new WebClient();
try
{
webClient = reggieLogin(webClient, keyboard);
}
catch (Exception e)
{
e.printStackTrace();
}
try
{
currentPage = webClient.getPage(""https://reggienet.illinoisstate.edu/portal"");
}
catch (FailingHttpStatusCodeException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
String pageSource = currentPage.asXml();
System.out.print(pageSource);
}
private WebClient reggieLogin(WebClient webClient, Scanner keyboard) throws Exception
{
webClient.getOptions().setJavaScriptEnabled(false);
HtmlPage currentPage = webClient.getPage("https://account.illinoisstate.edu/centrallogin/"); //Load page at the STRING address.
HtmlInput username = currentPage.getElementByName("username"); //Find element called loginuser for username
System.out.print("ULID: ");
username.setValueAttribute(keyboard.nextLine()); //Set value for username
HtmlInput password = currentPage.getElementByName("password"); //Find element called loginpassword for password
System.out.print("Password: ");
password.setValueAttribute(keyboard.nextLine()); //Set value for password
HtmlButtonInput submitBtn = currentPage.getElementByName("submit"); //Find element called Submit to submit form.
currentPage = submitBtn.click(); //Click on the button.
return webClient;
}
Can anybody offer any help, or can anybody see what's wrong with this code?
Consider using the Selenium library to interact with websites. It has methods for editing browser cookies. Here is a link to its java documentation.
Related
I am trying to fetch the data and store it in database.
Created a Get mapping for invoking the data from url and storing it in database using service class .
#GetMapping("/")
public String root(Model model) throws IOException {
model.addAttribute("test1","Hello user");
service.populate();
return "mainTemplate";
}
my populate method in service class add data to database.
public void populate() throws IOException{
URL url = new URL("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/01-01-2021.csv");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
int res= connection.getResponseCode();
CSVReader reader=null;
if(res==200) {
log.info("Connected to github");
try {
BufferedReader readurl = new BufferedReader(new InputStreamReader(connection.getInputStream()),8192);
reader=new CSVReader(readurl);
String[] line;
int i=0;
while((line=reader.readNext())!=null) {
if(i==0) {
i++;
continue;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
Corona corona = new Corona();
corona.setLastupDate(LocalDateTime.parse(line[4],formatter));
corona.setConfirmed(Long.valueOf(line[7]));
corona.setRecovered(Long.valueOf(line[9]));
corona.setActive(Long.valueOf(line[10]));
corona.setCombinedKey(line[11]);
log.info(corona.toString());
repo.save(corona);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CsvValidationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if(reader!=null) {
try {
reader.close();
} catch (IOException e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
}
else {
log.info("URL is wrong");
}
}
Everything is working fine when i hit the resource url ,but i have to wait for some time to show my webpage , until all data does not get stored in database.
I want to show "Data is being added" in mainTemplate.html as soon as i hit the url. So that my populate method runs in background and i don't have to wait for completion of method to show my mainTemplate .
I tired to add #Async method annotation but that does not seem to be worked .
I am new to Java but eager to learn. I am attempting to use an MVC model with the Users.java class controlling my servlets. I feel like am I close to getting this to work but something must be off. Ideally, after pressing submit the username and password would be checked against the users.properties file if there is a match the user would be redirected to the customer home page. If no match, the user is redirected to the registration page. After entering the registration info, the info would be stored to the users.properties file and the user redirected to the homepage.
Login.jsp
<form action=Login method="post">
User Name: <input type=text name=userName><br>
Password: <input type=password name=password><br>
<input type=submit value=Login onClick="validate(this.form)"> <br>
</form>
With the associated servlet java file
Login.java
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
/* Following two statements are used to obtain the absolute path
of the users.properies file from its relative path. */
ServletContext sc = this.getServletContext();
String propFilePath = sc.getRealPath("/WEB-INF/users.properties");
Users aUser = new Users(userName, password);
if (aUser.validateUser(aUser,propFilePath)) {
response.sendRedirect("CustomerHomePage.jsp");
} else {
response.sendRedirect("Registration.jsp");
}
}
So if the user is redirected, it goes to a page quite similar to the login.jsp. The register.java is also quite similar to the login.java. Main difference is below.
register.java servlet
// Registration via the Users object
Users aUser = new Users(userName, password);
// Register the Users object
aUser.registerUser(aUser, propFilePath);
response.sendRedirect("Login.jsp");
Finally, the controller. Likely this is where I went wrong but I'm so new to this I figured I could have went wrong anywhere.
public class Users {
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Users(String userName, String password) {
super();
this.userName = userName;
this.password = password;
}
public void registerUser(Users aUser, String propFilePath) {
Properties p = new Properties();
FileInputStream fis = null;
try {
fis = new FileInputStream(propFilePath);
p.load(fis);
p.setProperty(aUser.getUserName(), aUser.getPassword());
p.store(new FileOutputStream(propFilePath), null);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(fis!=null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public boolean validateUser(Users aUser, String propFilePath){
boolean success = true;
Properties p = new Properties();
FileInputStream fis = null;
try {
fis = new FileInputStream(propFilePath);
p.load(fis);
// Check whether the username exists or not
if(!p.containsKey(aUser.getUserName())) {
// Link-redirection
success = false;
} else { // Check whether the password matches or not
String pword = p.getProperty(aUser.getUserName());
if(!pword.equals(aUser.getPassword())) {
success = true; // Link-redirection
} else {
success = false; // Link-redirection
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
success = false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
success = false;
} finally {
if(fis!=null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return success;
}
}
Edit: I should also add that I have this code at the bottom of the servlet
I do have this code as well I should have added
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException { doGet(request, response);
}
So the form from the login page will send you to the registration page, when I enter in the registration info it goes back to log in like it should. But, when I enter in the login info again, it won't go to the homepage.
Edit2:
Found my mistake. Had to switch around the boolean logic of my validateUsers method. Rookie mistake. :(
New Code:
else { // Check whether the password matches or not
String pword = p.getProperty(aUser.getUserName());
if(!pword.equals(aUser.getPassword())) {
success = flase; // Link-redirection
} else {
success = true; // Link-redirection
}
}
The problem could be anything but looking at your code, your form you are using post this is correct as you are posting data to server and also you don't want it visible in your url but then you are handling it using doGet in your servlet put your code doPost.
For your case:
doGet should return the requested page
doPost should do the process
and return result or as for your case take user to registration/homepage
Cheers.
I am trying to create Group using Smack Api
I use the following code
It crashes on muc#roomconfig_roomowners tag
If i remove that line, it works fine, Group creates
But no group is assigned to the current user, no one is owner
public void createGroup() {
MultiUserChat chatRoom = MultiUserChatManager.getInstanceFor(mConnection).getMultiUserChat("room719#conference." + MYSITE);
try {
chatRoom.create("room719");
Form form = chatRoom.getConfigurationForm().createAnswerForm();
form.setAnswer("muc#roomconfig_publicroom", true);
form.setAnswer("muc#roomconfig_roomname", "room719");
// List owners = new ArrayList();
// owners.add("currUser#"+MYSITE);
form.setAnswer("muc#roomconfig_roomowners", Arrays.asList("currUser#"+MYSITE));
form.setAnswer("muc#roomconfig_persistentroom", true);
chatRoom.sendConfigurationForm(form);
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
This code is working for me, can you try this?
if( !chatRoom.isJoined() ){
chatRoom.createOrJoin("your nickname");
List<String> owners = new ArrayList<String>();
owners.add("currUser#"+MYSITE);
Form form = chatRoom.getConfigurationForm().createAnswerForm();
form.setAnswer("muc#roomconfig_roomname", "your roomname");
form.setAnswer("muc#roomconfig_roomowners", owners);
form.setAnswer("muc#roomconfig_persistentroom", true);
form.setAnswer("muc#roomconfig_publicroom", true);
chatRoom.sendConfigurationForm(form);
}
I am trying to write code in Processing (basically Java) that will get the information from the table here: http://science.nasa.gov/iSat/iSAT-text-only/
I have not started writing the code specific to the table yet because I can't even get this to run. I get the error "type String is ambiguous." I cannot find any duplicate of String nor can I think of any other reason for this error.
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.*;
import java.net.*;
WebClient client = new WebClient(BrowserVersion.CHROME);
try {
java.lang.String url = "http://science.nasa.gov/iSat/iSAT-text-only/";
Page page = client.getPage(url);
println(page.getWebResponse().getContentAsString());
}
catch(IOException e) {
println("oops!");
}
UPDATE:
I modified the code slightly and got it to get the information I want using the following code in eclipse:
WebClient client = new WebClient();
String url = "http://science.nasa.gov/iSat/iSAT-text-only/";
HtmlPage page = null;
try {
page = (HtmlPage) client.getPage(url);
} catch (FailingHttpStatusCodeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
client.waitForBackgroundJavaScript(10000);
System.out.print(page.asXml());
but it still throws the ambiguous String error in Processing.
Bizarrely, manually importing java.lang.String fixed the error.
I am Trying to Automate a Test sequence of Login - Booking - Cancellation.
Till Booking its Fine , But moment it Reaches Cancellation, It throws a java lang Null-Pointer Exp.
I rechecked and My locators(xpath) is correct(xpath-Checker) and I am Trying to getText() the Ticket Number and proceed to cancellation.
Problem is whenever WebDriver is reaching the Booking confirmation Page , which Loads after a While, it Fails and Returns Null Pointer Exp..
It may be a Loading Issue which is handled or I am messed up with my Java Concept...
Please Help !! anyone...
public class StackOverflow {
public static WebDriver driver;
public static Properties p;
public static FileInputStream f ;
#Test
public void loginTest() {
System.out.println("Enter Login");
Properties p=new Properties();
FileInputStream f = null;
try {
f = new FileInputStream("D:\\BOSSFramework\\Framework\\locators.properties");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
p.load(f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver = new FirefoxDriver();
driver.get("https://in3.seatseller.travel/");
driver.manage().window().maximize();
try{
driver.findElement(By.name(p.getProperty("login.username.textfield"))).sendKeys("UserName");
driver.findElement(By.name(p.getProperty("login.password.textfield"))).sendKeys("Password");
WebElement ele =driver.findElement(By.id(p.getProperty("login.signin.button")));
ele.click();
}
catch (Exception e) {
}
}
#Test (dependsOnMethods={"loginTest"})
public void booking() throws InterruptedException{
System.out.println("Enter Booking");
// Type Bangalore on Source Field..
Properties p=new Properties();
FileInputStream f = null;
try {
f = new FileInputStream("D:\\BOSSFramework\\Framework\\locators.properties");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
p.load(f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
WebDriverWait wait2 = new WebDriverWait(driver, 30);
wait2.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(p.getProperty("oneapp.source.textfield"))));
driver.findElement(By.xpath(p.getProperty("oneapp.source.textfield"))).sendKeys("Bangalore");
driver.findElement(By.xpath(p.getProperty("oneapp.source.textfield"))).sendKeys(Keys.TAB);
Thread.sleep(900L);
// Type Mysore on Destination Field
WebDriverWait wait1 = new WebDriverWait(driver, 30);
wait1.until(ExpectedConditions.presenceOfElementLocated(By.xpath(p.getProperty("oneapp.destination.textfield"))));
driver.findElement(By.xpath(p.getProperty("oneapp.destination.textfield"))).sendKeys("Tirupathi");
driver.findElement(By.xpath(p.getProperty("oneapp.destination.textfield"))).sendKeys(Keys.TAB);
}
#Test (dependsOnMethods={"booking"})
public void cancellation() throws InterruptedException{
System.out.println("Enter Cancellation");
WebDriverWait wait4 = new WebDriverWait(driver, 60);
Thread.sleep(9000);
/*Facing Null Pointer Exp Here */
wait4.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(p.getProperty("oneapp.congratulations.text"))));
wait4.until(ExpectedConditions.presenceOfElementLocated(By.xpath(p.getProperty("oneapp.congratulations.text"))));
Thread.sleep(9000);
/*Facing Null Pointer Exp Here */
WebElement ticket =driver.findElement(By.xpath(p.getProperty("oneapp.ticket.text")));
/*Want to getText() Ticket Number to cancel*/
String ticket1 = ticket.getText();
System.out.println(ticket1);
driver.findElement(By.xpath(p.getProperty("oneapp.leftNavCancel.link "))).click();
WebDriverWait wait1 = new WebDriverWait(driver, 30);
wait1.until(ExpectedConditions.presenceOfElementLocated(By.xpath(p.getProperty("oneapp.phoneNumber.textfield"))));
driver.findElement(By.xpath(p.getProperty("oneapp.phoneNumber.textfield"))).sendKeys(TIN1);
driver.findElement(By.xpath(p.getProperty("oneapp.search.button"))).click();
driver.findElement(By.xpath(p.getProperty("oneapp.cancel.button"))).click();
}
}
Either add Properties p=new Properties(); in your cancellation() method or mention it outside of the test methods(In the begining, you've declared public static Properties p; rather define it there like public static Properties p = new Properties();)
In first two methods you create f = new FileInputStream but in the third method you read properties without it. Did you try to read properties again?