I am developing an application in which the first window is
after clicking on log-in the log-in window appears and after correct credentials is is directed to choose time stamp and data set id window.
This is how I am accessing the value of API key (Login.java)
String value1=text1.getText();
String value2=text2.getText();
URL url = new URL("http://website-link/method/user.json?userName="+value1+"&password="+value2);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
String inputLine;
StringBuilder sb = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
String Result;
Result=sb.toString();
String jsonSource = Result;
JSONArray array;
try {
array = new JSONArray(jsonSource);
for (int i = 0; i < array.length(); i++) {
JSONObject firstObject = (JSONObject) array.get(i);
System.out.println("APIkey is " + firstObject.getString("apiKey"));
APIkey=firstObject.getString("apiKey");
}
I want that after successful log-in the user can anytime choose data set and time stamps.
That is Login.java is passing a value to Algorithm.java (for choosing the data set and timestamp window)
if (httpCon.getResponseCode()==200) {
Algorithm frame=new Algorithm(APIkey);
frame.setSize(450,200);
frame.setVisible(true);
dispose();
JLabel label = new JLabel("Welcome:"+value1);
}
now this API key is used in Algorithm.java to set the connection and select some specific nodes based on entered time stamps and data set id.
Now I want that after log-in I can anytime click on the second button shown in this window and choose the time stamp and data set id. But in that case I don't have the value of API key as I am using this in Main.java (responsible for the above window). And in Main.java the value of API key is null. I don't want the user to enter the log in username and password again and again.
if (e.getSource() == myFirstButton) {
Login frame1=new Login();
frame1.setSize(450,200);
frame1.setVisible(true);
}
if (e.getSource() == mySecondButton) {
Algorithm frame=new Algorithm(APIkey);
frame.setSize(450,200);
frame.setVisible(true);
}
Now how can I have the value of API key stored in all files once the user entered the correct access credentials in Login window and can use it anywhere.
Each of the file: Log-in.java , Algorithm.java,Main.java is extending jframe.
and Main.java is having the main() function
I am working in Netbeans 7.1.2. I am coding this in Swing Java. I am new to Java.
The fastest way to do this would be to have a global variable APIKey in Main.java and set it's value after the user logs-in. And if you do this, I would also add a Logout button to unset this variable.
Related
I am new to Java
I created a conversion software for metric units and now I want to create new window for logging the output of converted units from one Window text areas into one text area in another window Picture of the application
Both Windows are one application
What code would I need to put in there to display this in another window text area
JButton btnConvert = new JButton("Convert");
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double numCM,sumCM;
double numKM,sumKM;
double numMIL,sumMIL;
try {
//startCM//
numCM = Double.parseDouble(textFieldenter.getText());
sumCM = numCM*100;
textFieldcm.setText(Double.toString(sumCM));
//endCM//
//startKILOMETERS//
numKM = Double.parseDouble(textFieldenter.getText());
sumKM = numKM*0.001;
textFieldkm.setText(Double.toString(sumKM));
//endKILOMETERS//
//startMILES//
numMIL = Double.parseDouble(textFieldenter.getText());
sumMIL = numMIL*0.000621;
textFieldmil.setText(Double.toString(sumMIL));
//endMILES//
}
catch (Exception e1) {
JOptionPane.showInternalMessageDialog(btnConvert, "Value etered is incorrect");
}
}
});
You can use the method JTextField.getText() over your JTextFields and store its value into a String variable, then pass it to the JTextArea using the method append(String str) and put a line break at the end with /n
Read the API for these classes to learn more about its methods and how to use them Java API
It would be something like this
String record = "";
record = textFieldcm.getText()+" "+textFieldkm.getText()+" "+textFieldmil.getText();
JTextArea.append(record+"\n");
i need to access a website multiple times a day and want to skip the Log-In page. This is why i want to use Cookies in Java Selenium Chromedriver, for skipping that Log-In after accessing it the first time on a day.
Selenium is saving the Cookies correctly, but does not use them and i dont get access on the following page. Can you help me?
This is my Code:
public static void main(String[] args) throws InterruptedException {
Set<Cookie> cookie = null;
Iterator<Cookie> itr = null;
while (true) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Maxi\\Desktop\\ChromeDriver.exe");
driver = new ChromeDriver();
driver.get("https://www.xxxxxx.xxx");
while (itr != null && itr.hasNext()) {
driver.manage().addCookie(itr.next());
}
driver.navigate().refresh();
WebDriverWait wait0 = new WebDriverWait(driver, 20);
if (itr == null) {
String UserID = "LoginFieldXpath";
wait0.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(UserID)));
driver.findElement(By.xpath(UserID)).sendKeys("Username");
String PW = "PasswordField Xpath";
driver.findElement(By.xpath(PW)).sendKeys("Password");
String LogIn = "LoginButtonXpath";
driver.findElement(By.xpath(LogIn)).click();
cookie = driver.manage().getCookies();
itr = cookie.iterator();
}
}
}
You can create user profile in Chrome like this
options:
addArguments("user-data-dir="+"path_to_empty_folder");
Then make sign up, so cookie will be stored in this profile. And than just copy this user data dir to another folder
FileUtils.copyDirectory(new File("path-to-dir-with-cookie"), new File("new-dir"));
options.addArguments("user-data-dir="+"new-dir");
Selenium starts a new temporary browser instance each time, so it doesn't come with any cookies stored, cache or anything like that.
I would suggest moving your open chrome driver to be outside of the while loop so you'll be able to reuse it each time you want to check a page. Maybe either move the login outside of the loop as well or check if you need to log in. Then just grab whatever page you're trying to check inside the loop each time you need to.
public static void main(String[] args) throws InterruptedException {
Set<Cookie> cookie = null;
Iterator<Cookie> itr = null;
// move this outside the loop
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Maxi\\Desktop\\ChromeDriver.exe");
driver = new ChromeDriver();
while (true) {
driver.get("https://www.xxxxxx.xxx");
// not sure why you're adding a cookie?
// it should automatically accept page cookies that are set
while (itr != null && itr.hasNext()) {
driver.manage().addCookie(itr.next());
}
driver.navigate().refresh();
WebDriverWait wait0 = new WebDriverWait(driver, 20);
// check to make sure that you need to log in
if (itr == null) {
String UserID = "LoginFieldXpath";
wait0.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(UserID)));
driver.findElement(By.xpath(UserID)).sendKeys("Username");
String PW = "PasswordField Xpath";
driver.findElement(By.xpath(PW)).sendKeys("Password");
String LogIn = "LoginButtonXpath";
driver.findElement(By.xpath(LogIn)).click();
cookie = driver.manage().getCookies();
itr = cookie.iterator();
}
}
}
I have an web application that uses JSF for form submission. I have a user select an image from a list followed by filling out and submitting a form. I then use the selected image and form input to annotate the image with the information. I then process a pdf file using the annotated images and email it to the user. After processing, I give the user the option to navigate back to the image selection page, or use the same images and go back to the form. Here is the jsf/html for the form that allows the user to navigate to their new page:
<h:form id="form" method="post">
<div>
<h:commandButton value="images" action="#{artwork.backToArt}"/>
</div>
<div>
<h:commandButton value="Form" action="#{artwork.backToForm}"/>
</div>
<div>
<h:commandButton value="Upload" action="#{artwork.backToUpload}"/>
</div>
</h:form>
It seems that IE caches the annotated images and keeps those images on display regardless of my method calls.
Here are my methods:
public String backToArt()
{
log.info("========= Setting back to art page ==========");
this.backToForm();
this.selectedValue = "";
this.resizedArt = "";
this.backArt = "";
return "loginSuccess.xhtml";
}
public String backToUpload()
{ log.info("========= Setting back to upload ==========");
this.backToForm();
this.selectedValue = "";
this.resizedArt = "";
this.backArt = "";
return "CSVSubmit.xhtml";
}
public String backToForm()
{
log.info("============ Reseting all variables ==========");
String temp = null;
if (this.selectedValue != null)
{
temp = this.selectedValue;
temp=temp.substring(temp.lastIndexOf(Dir.getDir("\\")) + 1, temp.length() - 4);
this.selectedValue = temp;
}
log.info("Setting input variables");
//set all previous values to blank
//this.jobNum = "";
this.quantity = null;
this.headLine = null;
this.codeNum = null;
this.pass = null;
this.expir = null;
this.website = null;
log.info("Setting front art to old image");
//setting previous images to non-text
if (temp.length() > 0)
{
temp = this.resizedArt;
temp = "converted" + temp.substring(temp.lastIndexOf(Dir.getDir("\\")),temp.length() - 8)
+ ".jpg";
this.resizedArt=temp;
log.info("Setting back art to old image");
temp = this.backArt;
temp = "converted" + temp.substring(temp.lastIndexOf(Dir.getDir("\\")),temp.length() - 8)
+ ".jpg";
this.backArt = temp;
log.info("Deleting old text images");
//start to delete text images
File folderOne = new File(Env.textDestOne);
this.deleteFiles(folderOne);
File folderTwo = new File(Env.textDestTwo);
this.deleteFiles(folderTwo);
}
log.info("============ Reset Complete ==========");
return "FormSubmission.xhtml";
}
These methods reset the input variables and the images selected as well as deletes my annotated images depending on which button is pressed on that page. Looking at my logging, the methods are called and are processed, but no updating occurs for the images. When I process my pdf, the correct images and input are outputed, but what is viewed still shows old values. This means that my values are being stored properly and my methods are being called correctly. When I go to cancel and reprocess using Google Chrome, the images are updated properly.
Using all of this information, I have concluded that IE must be caching my images and not updating them with the correct values. I'm not sure how to override this, but I need to somehow clear the cache so that the images are updated to the correct values.
Edit: I noticed that when I refresh the page hitting F5, the pictures would update. Not sure what this means.
i am working on a project where i have to display a set of records then the user can select 1 or more of these records to move them to another set.
i think the most appropiate componenet to use is Checkboxes. my probelm is that i cant add the check boxes to the frame automatically while reading the file. i added a panel, and added the check box but it still doesnt appear after using paint, or updateUI.
this is my code:
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file.getAbsolutePath()), "UTF-8"));
String line = reader.readLine();
String text = "";
while (line != null) {
text += line;
line = reader.readLine();
}
ArrayList<String> records = new ArrayList<String>(Arrays.asList(text.split("")));
for(String rec: records){
resPanal.add(new JCheckBox(rec));
}
resPanal.updateUI();
the number of records is not constant, so i need a way to add the components = to the number of records found.
i am open to other suggestions that can help other than check boxes
for anyone interested:
i tried what #TerryStorm suggested in a small program with only a button, and each time the button is clicked a box is added
private void addCBActionPerformed(java.awt.event.ActionEvent evt) {
JCheckBox box=new JCheckBox("add");
box.setVisible(true);
jPanel1.add(box);
jPanel1.updateUI();
}
I have a PNR Inquiry app on Google Play. It was working very fine. But recently Indian Railwys added captcha to their PNR Inquiry section and because of this I am not able to pass proper data to the server to get proper response. How to add this captcha in my app in form of an imageview and ask the users to enter captcha details also so that I can send proper data and get proper response.
Indian Railways PNR Inquiry Link
If you check the html code, its actualy pretty bad captcha.
Background of captcha is: http://www.indianrail.gov.in/1.jpg
Those numbers are actualy in input tag:
<input name="lccp_cap_val" value="14167" id="txtCaptcha" type="hidden">
What they are doing is, via javascript, use numbers from that hidden input tag
and put them on that span with "captcha" background.
So basicaly your flow is:
read their html
get "captcha" (lol, funny captcha though) value from input field
when user puts data in your PNR field and presses Get Status
post form field, put PNR in proper value, put captcha in proper value
parse response
Oh yeah, one more thing. You can put any value in hidden input and "captcha"
input, as long as they are the same. They aren't checking it via session or
anything.
EDIT (code sample for submiting form):
To simplify posting form i recommend HttpClient components from Apache:
http://hc.apache.org/downloads.cgi
Lets say you downloaded HttpClient 4.3.1. Include client, core and mime
libraries in your project (copy to libs folder, right click on project,
properties, Java Build Path, Libraries, Add Jars -> add those 3.).
Code example would be:
private static final String FORM_TARGET = "http://www.indianrail.gov.in/cgi_bin/inet_pnstat_cgi.cgi";
private static final String INPUT_PNR = "lccp_pnrno1";
private static final String INPUT_CAPTCHA = "lccp_capinp_val";
private static final String INPUT_CAPTCHA_HIDDEN = "lccp_cap_val";
private void getHtml(String userPnr) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(INPUT_PNR, userPnr); // users PNR code
builder.addTextBody(INPUT_CAPTCHA, "123456");
builder.addTextBody("submit", "Get Status");
builder.addTextBody(INPUT_CAPTCHA_HIDDEN, "123456"); // values don't
// matter as
// long as they
// are the same
HttpEntity entity = builder.build();
HttpPost httpPost = new HttpPost(FORM_TARGET);
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = null;
String htmlString = "";
try {
response = client.execute(httpPost);
htmlString = convertStreamToString(response.getEntity().getContent());
// now you can parse this string to get data you require.
} catch (Exception letsIgnoreItForNow) {
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException ignoredOnceMore) {
} finally {
try {
is.close();
} catch (IOException manyIgnoredExceptions) {
}
}
return sb.toString();
}
Also, be warned i didn't wrap this in async call, so you will have to do that.
Image from the network can be displayed in android via efficient image loading api's like Picasso/volley or simply image view via async task.
considering all above things as basic build a logic such that you should need a image URL for that captcha if user resets or refresh the captcha it should reload new image via network call requesting the new request implementation, you have to get REST api access to the Indian railway and check in that any image uri available in that (it may be in base64 format )
if REST API is not available you may think of building your own server with this code
RESTful API to check the PNR Status
pnrapi
Update: you don't need to do this complex hacks , just implement Drago's answer !