Java: do while string issue - do-while

I have an issue when I run this program, If I use int it works, but for string it does not.
import java.util.Scanner;
public class userinput_swutch_do_while {
public static void main(String[] args) {
String password= null;
Scanner value = new Scanner(System.in);
do {
System.out.println("Enter the password for ATM: ");
password = value.nextLine();
System.out.println("You put : "+password);
} while (password !="55");
System.out.println("You got it!");
}
}

In JAVA, String equality is tested correctly using equals()or equalsIgnoreCase();
That being said, you can try this :
import java.util.Scanner;
public class userinput_swutch_do_while {
public static void main(String[] args) {
String password= null;
Scanner value = new Scanner(System.in);
do {
System.out.println("Enter the password for ATM: ");
password = value.nextLine();
System.out.println("You put : "+password);
} while(!(password.equals("55")));// string equality
System.out.println("You got it!");
}
}

Related

unable to get file name in struts2 file upload

I am new to Struts2. I am unable to get file name and path. Kindly help any one.
import java.io.File;
import java.util.ResourceBundle;
import org.apache.commons.io.FileUtils;
import nre.dao.DBconnection;
import com.mysql.jdbc.Connection;
import com.opensymphony.xwork2.ActionSupport;
public class AddProperty extends ActionSupport
{
private String propertyid;
private String propertyname;
private String country;
private String state;
private String city;
private String description;
private File uploadphoto;
private String photofiletype;
private String photoname;
public String getPropertyid()
{
return propertyid;
}
public void setPropertyid(String propertyid)
{
this.propertyid = propertyid;
}
public String getPropertyname()
{
return propertyname;
}
public void setPropertyname(String propertyname)
{
this.propertyname = propertyname;
}
public String getCountry()
{
return country;
}
public void setCountry(String country)
{
this.country = country;
}
public String getState()
{
return state;
}
public void setState(String state)
{
this.state = state;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
public File getUploadphoto()
{
return uploadphoto;
}
public void setUploadphoto(File uploadphoto)
{
this.uploadphoto = uploadphoto;
}
public String getPhotofiletype() {
return photofiletype;
}
public void setPhotofiletype(String photofiletype) {
this.photofiletype = photofiletype;
}
public String getPhotoname() {
return photoname;
}
public void setPhotoname(String photoname) {
this.photoname = photoname;
}
public String execute(){
DBconnection connection=new DBconnection();
connection.getConnection();
try{
String filepath=connection.filepath;
System.out.println("filepath : : "+filepath);
System.out.println("photoname : : "+photoname);
if(filepath!=null && photoname!=null){
File filetocreate=new File(filepath,photoname);
FileUtils.copyFile(uploadphoto, filetocreate);
}
}catch(Exception e){
e.printStackTrace();
addActionError(e.getMessage());
return INPUT;
}
String query ="insert into addproperty(propertyid,propertyname,propertycity,propertystate,propertycountry,addedby,addeddate,removeddate) values ('"+propertyid+"','"+propertyname+"','"+city+"','"+state+"','"+country+"','Parthi',now(),NULL)";
connection.executeUpdate(query);
System.out.println("Completed Inserting");
return SUCCESS;
//System.out.println("Class completed");
}
}
Action class should have the following three properties.
• [inputName]File
• [inputName]FileName
• [inputName]ContentType
[inputName] is the name of the file tag(s) on the JSP. For example, if the file tag's name is uploadphoto, the properties will be as follows:
• File uploadphotoFile
• String uploadphotoFileName
• String uploadphotoContentType
String filePath = servletRequest.getRealPath("/");
File fileToCreate = new File(filePath, this.uploadphotoFileName);
FileUtils.copyFile(this.uploadphotoFile, fileToCreate);

How Can i show urls clicked by user in Primefaces+JSF2

I am using JSF2 with Prime faces. I will want to show all the previous links or Urls clicked by user in every page.How can i do this?
Here's a good link for you: How can I get the request URL from a Java Filter?
What I would do is use something like that example and do a set of three URLs.
//Using linked example
public class MyFilter implements Filter {
public void init(FilterConfig config) throws ServletException { }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
chain.doFilter(request, response);
String url = ((HttpServletRequest) request).getPathTranslated();
UrlBean urlBean = (UrlBean) FacesContext.getCurrentInstance()getApplication().getValueBinding("#{urlBean}");
urlBean.storeUrl(url);
}
public void destroy() { }
}
This is totally untested, but the idea should work. You would just need to implement some logic (probably a stack) for your component so it stores what you need. (Obviously you might end up at the same URL multiple times). I should note the UrlBean is just an abstract idea, you would have to implement it
Hi I have created this Singleton class to put the Url Browsed by a User.
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class UrlHistory {
#SuppressWarnings("rawtypes")
private static Map<String, List> store = new HashMap<String, List>();
private static UrlHistoryBean instance = null;
public static UrlHistoryBean getInstance() {
if (instance == null) {
instance = new UrlHistoryBean();
}
return instance;
}
LinkedList<UrlData> urlList = new LinkedList<UrlHistoryBean.UrlData>();
public void addUrl(String sessionId, String urlString, int urlId) {
UrlData data = new UrlData();
data.setUrlName(urlString);
data.setUrlId(companyId);
if (urlList.isEmpty()) {
urlList.add(data);
} else {
boolean isEqual = false;
for (UrlData urlDataObj : urlList) {
if (urlDataObj.equals(data))
isEqual = true;
}
if(!isEqual)
urlList.addFirst(data);
}
store.put(sessionId, urlList);
}
#SuppressWarnings("rawtypes")
public static Map<String, List> getStore() {
return store;
}
#SuppressWarnings("rawtypes")
public static void setStore(Map<String, List> store) {
UrlHistoryBean.store = store;
}
public class UrlData {
String urlName;
int urlId;
public String getUrlName() {
return UrlName;
}
public void setUrlName(String UrlName) {
this.UrlName = UrlName;
}
public int getUrlId() {
return urlId;
}
public void setUrlId(int urlId) {
this.urlId = urlId;
}
public boolean equals(UrlData rData) {
boolean bEqual = false;
if (this.getUrlId() > 0 && rData.getUrlId() > 0 && this.getUrlId() == rData.getUrlId()) {
bEqual = true;
}
return bEqual;
}
}
}

Returning value from a web browser

I had created 4 classes for the restlet. However, When I hit on the browser, http://localhost:8182/firstSteps/hello, it returns me UserName = userName, Password = password. Which class should I change in order to get the intended url such as http://localhost:8080/restletTest?p1=abc&p2=def??
package firstStep;
import org.restlet.Component;
import org.restlet.data.Protocol;
public class Mainone {
public static void main(String[] args) throws Exception {
// Create a new Component.
Component component = new Component();
// Add a new HTTP server listening on port 8182.
component.getServers().add(Protocol.HTTP, 8182);
// Attach the sample application.
component.getDefaultHost().attach("/firstSteps", new FirstStepsApplication());
// Start the component.
component.start();
}}
package firstStep;
import org.restlet.Application;
import org.restlet.Restlet;
import org.restlet.routing.Router;
public class FirstStepsApplication extends Application{
public Restlet createInboundRoot(){
Router router = new Router(getContext());
router.attach("/hello",FirstServerResource.class);
return router;
}}
package firstStep;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
public class FirstServerResource extends ServerResource {
Contact contact = new Contact("userName","Password");
//Contact contactTwo = contact.retrieve();
// #Get
// public Contact retrieve() {
// return contact;
// }
#Get
public String toString() {
return contact.toString();
}
}
package firstStep;
public class Contact {
private String userName;
private String password;
//Constructor
public Contact(String userName,String password){
this.userName = userName;
this.password = password;
}
public Contact retrieve(){
System.out.println("Contact retrieve():"+this.userName+"|"+this.password);
return this;
}
public String toString(){
return "Username:\t"+this.userName+"\nPassword:\t"+this.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;
}}
When you hit http://localhost:8182/firstSteps/hello
the #Get toString()-method of contact is called and the output
UserName: userName
Password: Password
is correct.
So The value is returned from the server correctly.
What else do you want to do?

Struts2 Iteration of ArrayList with JavaBean

This Question may be asked in several threads...but could not fine the correct answer
a Java Bean
package com.example;
public class Document {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
An ArrayList creation of JavaBean as displayed below
package com.example;
import java.util.ArrayList;
public class classdocs {
public ArrayList getData() {
ArrayList docsmx = new ArrayList();
Document d1 = new Document();
d1.setName("user.doc");
Document d2 = new Document();
d2.setName("office.doc");
Document d3 = new Document();
d3.setName("transactions.doc");
docsmx.add(d1);
docsmx.add(d2);
docsmx.add(d3);
return docsmx;
}
}
an Action Class
package com.example;
import java.util.ArrayList;
import com.opensymphony.xwork2.ActionSupport;
public class FetchAction extends ActionSupport {
private String username;
private String message;
private ArrayList docsmx = new ArrayList();
public ArrayList getDocuments() {
return docsmx;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String execute() {
classdocs cx = new classdocs();
if( username != null) {
docsmx = cx.getData();
return "success";
} else {
message="Unable to fetch";
return "failure";
}
}
}
Jsp with Struts2 Iterator Tag
Documents uploaded by the user are:</br>
<s:iterator value="docsmx">
<s:property value="name" /></br>
</s:iterator>
Question Why the ArrayList of Bucket containing JavaBean not displayed when Iterated ...
Am I doing some thing wrong ???
with regards
karthik
Depending your version, you should either provide a getter for docsmx (preferred, pre-S2.1.mumble), or make docsmx public (not as preferred, S2.1+).
Or, based on your code, use the correct getter:
<s:iterator value="documents">
<s:property value="name" /></br>
</s:iterator>
A couple of notes: documents should likely be declared a List, not ArrayList, although in this case it almost certainly doesn't matter. It's a good habit to get in to, though, coding to an interface when the implementation doesn't matter.
I'd also consider tightening up the code a little bit:
public String execute() {
if (username == null) {
message = "Unable to fetch";
return "failure";
}
docsmx = cs.getData();
return "success";
}
This allows a more natural reading, makes it more clear what the two states are (success and failure), keeps them very distinct, and slightly shorter.

Access ApplicationResource.properties file from Action Class in Struts 2

can i access ApplicationResource.properties file keys from Action Class in Struts 2
and update the values of the key ?
I don't think you can update the values of those keys directly, that would kind of defeat the purpose of it being (static) resources.
You can however use placeholders.
ApplicationResources.properties
property.key=Hi {0}, there's a problem with {1}
MyAction.java
public ActionForward execute(ActionMapping mapping,
ActionForm form,
javax.servlet.ServletRequest request,
javax.servlet.ServletResponse response)
throws java.lang.Exception {
MessageResources msgResource = getResources(request);
String msg = msgResource.getMessage("property.key", "Sankar", "updating values in the resources.");
}
Yes its possible.
Lets say if you have a property error.login in applicationResources.properties file.
eg : error.login= Invalid Username/Password. Please try again.
then in the Action class you can access it like this : getText("error.login")
Complete example:
applicationResources.properties
error.login= Invalid Username/Password
LoginAction.java
package net.sumitknath.struts2;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private String username;
private String password;
public String execute() {
if (this.username.equals("admin") && this.password.equals("admin123")) {
return "success";
} else {
addActionError(getText("error.login"));
return "error";
}
}
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;
}
}

Resources