Convert an Object into a String
Good day to everyone. I am trying to do a little coding in which a user will input his desired username. I want to check the database if the desired username of the current user is existing, so there'll be no duplication. I'm using JPA for the model and JSF for the controller and view.
Here's my Model.
@Entity
public class WebUser implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String lastName;
private String firstName;
private String middleName;
private String username;
private String password;
public Long getId() {
return id;
public void setId(Long id) {
this.id = id;
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof WebUser)) {
return false;
WebUser other = (WebUser) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
return true;
@Override
public String toString() {
return "web.model.WebUser[id=" + id + "]";
public String getLastName() {
return lastName;
public void setLastName(String lastName) {
this.lastName = lastName;
public String getFirstName() {
return firstName;
public void setFirstName(String firstName) {
this.firstName = firstName;
public String getMiddleName() {
return middleName;
public void setMiddleName(String middleName) {
this.middleName = middleName;
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;
}The controller and jsp are auto-generated from Netbeans. My question is, how will I convert the 'WebUser' object into a String so I can compare the value from input text to the value in the database?
Here is my validation method inside WebUserController.java
public void validateUsername(FacesContext facesContext, UIComponent component, Object value) throws ValidatorException {
String newUsername = (String) value;
System.out.println("new user name: " +newUsername);
System.out.println("component: " +component);
int webUserSize;
StringBuffer sb = new StringBuffer();
//webUsers.toString();
if ((webUsers == null) || (webUsers != null)) {
System.out.println("web users null");
List<WebUser> allWebUsers = getWebUsers();
webUserSize = allWebUsers.size();
System.out.println("all web users: " +allWebUsers);
System.out.println("size " +webUserSize);
for(int i=1; i<=webUserSize; ++i) {
sb.append(allWebUsers);
System.out.println("username: " +sb.append(allWebUsers));
}Honestly I'm new to java and having a hard time with this one. Hope someone can help me. Thanks a lot.
I know my code is a mess. :(
Thanks for the help guys! I used the "unique constraint" annotation of JPA and my problem is solved.
Here's the code:
@Entity
@Table(
name="WebUser",
uniqueConstraints={@UniqueConstraint(columnNames={"username"})}
public class WebUser implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String lastName;
private String firstName;
private String middleName;
private String username;
private String password;
public Long getId() {
return id;
public void setId(Long id) {
this.id = id;
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof WebUser)) {
return false;
WebUser other = (WebUser) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
return true;
@Override
public String toString() {
//return "web.model.WebUser[id=" + id + "]";
return "web.model.User[username=" + username +"]";
public String getLastName() {
return lastName;
public void setLastName(String lastName) {
this.lastName = lastName;
public String getFirstName() {
return firstName;
public void setFirstName(String firstName) {
this.firstName = firstName;
public String getMiddleName() {
return middleName;
public void setMiddleName(String middleName) {
this.middleName = middleName;
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;
}Thanks again guys!
Similar Messages
-
How do i convert an object into a string?
has said above, im trying to convert a object to a string.
here is what i ahve so far:
Object nodeInfo = node.getUserObject()RTFM
Object o =...
String str = o.toString(); -
Need to convert a long into a string, please
hi there
i need to convert a long into a string. can i just cast it like this:
(String)longNumber = some function that returns a long;Why not just use Long.toString()? If you start with a long value, you can create a Long object and get it's value as a String.
-
How can I convert table object into table record format?
I need to write a store procedure to convert table object into table record. The stored procedure will have a table object IN and then pass the data into another stored procedure with a table record IN. Data passed in may contain more than one record in the table object. Is there any example I can take a look? Thanks.
I'm afraid it's a bit labourious but here's an example.
I think it's a good idea to work with SQL objects rather than PL/SQL nested tables.
SQL> CREATE OR REPLACE TYPE emp_t AS OBJECT
2 (eno NUMBER(4)
3 , ename VARCHAR2(10)
4 , job VARCHAR2(9)
5 , mgr NUMBER(4)
6 , hiredate DATE
7 , sal NUMBER(7,2)
8 , comm NUMBER(7,2)
9 , deptno NUMBER(2));
10 /
Type created.
SQL> CREATE OR REPLACE TYPE staff_nt AS TABLE OF emp_t
2 /
Type created.
SQL> Now we've got some Types let's use them. I've only implemented this as one public procedure but you can see the principles in action.
SQL> CREATE OR REPLACE PACKAGE emp_utils AS
2 TYPE EmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE;
3 PROCEDURE pop_emp (p_emps in staff_nt);
4 END emp_utils;
5 /
Package created.
SQL> CREATE OR REPLACE PACKAGE BODY emp_utils AS
2 FUNCTION emp_obj_to_rows (p_emps IN staff_nt) RETURN EmpCurTyp IS
3 rc EmpCurTyp;
4 BEGIN
5 OPEN rc FOR SELECT * FROM TABLE( CAST ( p_emps AS staff_nt ));
6 RETURN rc;
7 END emp_obj_to_rows;
8 PROCEDURE pop_emp (p_emps in staff_nt) is
9 e_rec emp%ROWTYPE;
10 l_emps EmpCurTyp;
11 BEGIN
12 l_emps := emp_obj_to_rows(p_emps);
13 FETCH l_emps INTO e_rec;
14 LOOP
15 EXIT WHEN l_emps%NOTFOUND;
16 INSERT INTO emp VALUES e_rec;
17 FETCH l_emps INTO e_rec;
18 END LOOP;
19 CLOSE l_emps;
20 END pop_emp;
21 END;
22 /
Package body created.
SQL>Looks good. Let's see it in action...
SQL> DECLARE
2 newbies staff_nt := staff_nt();
3 BEGIN
4 newbies.extend(2);
5 newbies(1) := emp_t(7777, 'APC', 'CODER', 7902, sysdate, 1700, null, 40);
6 newbies(2) := emp_t(7778, 'J RANDOM', 'HACKER', 7902, sysdate, 1800, null, 40);
7 emp_utils.pop_emp(newbies);
8 END;
9 /
PL/SQL procedure successfully completed.
SQL> SELECT * FROM emp WHERE deptno = 40
2 /
EMPNO ENAME JOB MGR HIREDATE SAL COMM
DEPTNO
7777 APC CODER 7902 17-NOV-05 1700
40
7778 J RANDOM HACKER 7902 17-NOV-05 1800
40
SQL> Cheers, APC -
Converting Array Objects into ArrayCollections
Hi,
I am facing problem with converting Array Objects into ArrayCollections. How can i convert Array Objects into ArrayCollections. If any one knows how can we do that Pl reply.
Thanks in advance to all
Regards
subbareddy.pHi Bhasker,
thanks for u r reply. Here i attached screen shot of my server "data.result".
My proxy varaible contains
My object varaible "obj" contains
After parsing the result my arraycollection contains, (i mean after converting Object to Array to ArrayCollection) the below information. For information Pl find the attached arraycollection.png image. In the attached image my arraycollection name is "users".
Here i pasted the code that i used to convert "ObjectProxy" to "ArrayCollection"
var proxy:ObjectProxy = ObjectProxy(data.result);
var obj:Object = proxy.object_proxy::object;
var arrycoll:Array = ArrayUtil.toArray(obj);
model.users = new ArrayCollection(arrycoll);
Regards
sss -
Converting EJB Object into XML
All:
Suppose I have an EJB that is named MyDog, it has attributes as follows:
name
breed
weight
age
Is there a way to convert this Object into an XML document? Something like:
<?xml version=\"1.0\" ?>
<MyDog>
<name>Bubba</name>
<breed>Australian Shepherd</breed>
<weight>65 lbs</weight>
<age>6 years old</age>
</MyDog>
I can't find any information on doing this - any ideas, links, etc? There has to be a way to do this, but I can't find it. I'm welcome to any ideas out there!check JAXB - might be usefull for you: http://java.sun.com/xml/jaxb/index.html
-
How to convert Java Objects into xml?
Hello Java Gurus
how to convert Java Objects into xml? i heard xstream can be use for that but i am looking something which is good in performance.
really need your help guys.
thanks in advance.There are apparently a variety of Java/XML bindings. Try Google.
And don't be so demanding. -
How to convert an Object into integer?
Ho can v convert an object of type Object into integer data type?
Object obj = null;
integer int = _____________;
plz do fill it up and help ASAP......Fortunately, Gosling was able to predict that his
language would produce exceptions, so he gave usthe
catch block, so we can magically make them goaway:
> catch (Exception exc) {}You are
probably not without knowing that empty catch blocks
are considered to be bad practice.
You should better do the following
:catch(Exception exc) {
throw new RuntimeException();
ode]You turned your sarcasm detector off or something?? :-) -
Converting Document object into XML file
I was wondering how to convert a document object to XML file? I have read the documentation about document and Node but nothing explains the procedure of the conversion. Ive been told that it can be done, but not sure how. I have converted an XML file into Document by parsing DocumentBuilder. Just not sure how to do the reverse. Any help appreciated.
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
trans.transform(new DOMSource(yourDOMsRootNode), new StreamResult(new FileOutputStream(yourFileName)));or something a lot like that. -
How to convert the Object into tonumber
Hi all,
How to convert a date in Object type into a number type.
eg:
Object EVENT_NUMBER = ADFContext.getCurrent().getSessionScope().get("SV_EVENT_NUMBER");
Number LV_N_EVENT_NUMBER = EVENT_NUMBER.*toNumber();*
I need to assign the value in number type to variable LV_N_EVENT_NUMBER.
Thanks in advance
C.KarukkuvelHi,
I am assuming you are using oracle.jbo.domain.Number.
Is this what you need?
Number num;
try {
num = new Number(object);
} catch (SQLException e) {
}Gabriel. -
How do I convert an Object into an Array?
If I have an instance of type object that I know is really a DataGrid row that was cast into an object when passed to a function, how can I cast that Object to an array, such that each index of this array would correspond to the information in a given column of the row?
@Sathyamoorthi
Can you please explain what this function does? Essentially, what should be contained in the String?
I printed out the string and it seems like I am getting a random row in the Object, as opposed to first or last. Why is that?
UPDATE: I printed out the value of dataGrid0.columns[5].dataField but it just turned out to be the id of the column. -
How can i convert JMS TextMessage into a String
Please tell me,How can i convert A JMS TextMessage into a String
http://java.sun.com/javaee/5/docs/api/javax/jms/TextMessage.html#getText()
-
Converting objects into Strings
How would someone convert an object of say (String, int, double, String) into a readable string. I tried the toString() method but all I get is something like this
Student@1f12c4e..I'm not sure I understand "how" to override. The whole point of this project is to use quicksort on a list of students, unfortunately all I get is the address whenever I use the .toStrings() method.
Here's what I have, any help would be greatly appreciated-so very close
import cs1.Keyboard;
import java.io.*;
import java.util.*;
public class StudentTraverse
public static void main(String[] args)
String newName;
int newSocial;
double newGPAs;
String newMajors;
System.out.println("How many Students would you like to add");
Student newStudent;
StudentList12 WORK = new StudentList12();
int total = Keyboard.readInt();
for(int number = total; number > 0; number--)
System.out.println("Name?");
newName = Keyboard.readString();
System.out.println("Social?");
newSocial = Keyboard.readInt();
System.out.println("GPA?");
newGPAs = Keyboard.readDouble();
System.out.println("Major?");
newMajors = Keyboard.readString();
newStudent = new Student(newName, newSocial, newGPAs, newMajors);
System.out.println("Inserting: "+newStudent.toString());
WORK.add(newStudent);
for(total = 0; total < WORK.size(); total++)
System.out.println("top" total": "+WORK.top(total).toString());
try
BufferedReader in = new BufferedReader(new FileReader("LIST.out"));
while (in.ready())
// Print file line to scree
System.out.println (in.readLine());
in.close();
catch (Exception e)
System.err.println("File input error");
public class StudentNode
public Student student;
public StudentNode next;
public StudentNode()
next = null;
student = null;
public StudentNode(Student d, StudentNode n)
student = d;
next = n;
public void setNext(StudentNode n)
next = n;
public void setData(Student d)
data = d;
public StudentNode getNext()
return next;
public Student getData()
return data;
public String toString()
return ""+data;
public StudentNode(Student newStudent)
METHOD NAME: StudentNode
AUTHOR:
DATE OF CREATION: Nov 20, 2004
DATE OF UPDATES: Nov 28, 2004
PURPOSE: Acts as a node for the Student list
ALGORITHM:Acts as node for the list
INSTANCE VARIABLES: none
student = newStudent;
next = null;
public class Student
private String name;
private int social;
private double GPA;
private String Major;
public Student(String newName, int newSocial, double newGPAs, String newMajors)
METHOD NAME: Student
AUTHOR:
DATE OF CREATION: Nov 20, 2004
DATE OF UPDATES: Nov 28, 2004
PURPOSE: The actual Student class, determines what is allowed in the array
ALGORITHM:Declare what variables will be needed for the program
INSTANCE VARIABLES: String name, int social, double GPA, String Major
name = newName;
social = newSocial;
GPA = newGPAs;
Major = newMajors;
import java.io.*;
import cs1.Keyboard;
import java.io.BufferedWriter;
import java.util.*;
public class StudentList12
private StudentNode list;
static int i = 0;
public StudentList12()
METHOD NAME: StudentList12
AUTHOR:
DATE OF CREATION: Nov 20, 2004
DATE OF UPDATES: Nov 28, 2004
PURPOSE: Declares the Node
ALGORITHM:Declare the Node
INSTANCE VARIABLES: none
list = null;
public boolean isEmpty()
return list == null;
public int size()
return i;
public void add(Student newStudent)
METHOD NAME: add
AUTHOR:
DATE OF CREATION: Nov 20, 2004
DATE OF UPDATES: Nov 28, 2004
PURPOSE: Let's users add objects to the array of objects
ALGORITHM:Traverses the current list and adds object to the end
INSTANCE VARIABLES: none
list = new StudentNode(newStudent, list);
i++;
current = current.next;
current.next = node;
public Student remove()
if(isEmpty())
return null;
StudentNode tmp = list;
list = tmp.getNext();
i--;
return tmp.getData();
public void insertEnd(Student newStudent)
if(isEmpty())
add(newStudent);
else
StudentNode t = list;
while(t.getNext() != null)
t=t.getNext();
StudentNode tmp = new StudentNode(newStudent, t.getNext());
t.setNext(tmp);
i++;
public Student removeEnd()
if(isEmpty())
return null;
if(list.getNext() == null)
return remove();
StudentNode t = list;
while(t.getNext().getNext() != null)
t = t.getNext();
Student newStudent = t.getNext().getData();
t.setNext(t.getNext().getNext());
i--;
return newStudent;
public Student top(int n)
StudentNode t = list;
for(int i = 0; i <n && t != null; i++)
t = t.getNext();
return t.getData();
public void writeToFile(int n)
int z = n;
try
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("LIST.out")));
for(int counter = z; counter >= 0; counter--)
System.out.println(counter);
out.close();
catch(Exception e)
System.err.println("Couldn't Write File");
try
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("LIST.out")));
out.write(list.toString());
out.close();
catch(Exception e)
System.err.println("Couldn't Write File");
} -
Convert Objects into an XML Document? Possible?
Hello,
Is there a way to convert different objects into an XML File/Document
If I create 10 objects and then I want to create an XML Document
of these objects,is it possible to do this?
AjayHello,
Is there a way to convert different objects into an
XML File/Document
If I create 10 objects and then I want to create an
XML Document
of these objects,is it possible to do this?
Ajayjust override the .toString() method... -
Convert SSIS DateTime to a String
Being a newbie to SSIS I'm not sure of the most efficient method of converting a DateTime object to a String.
I'm from a C# background where this would be easy using DateTime.ToString("YYYYMMdd"). I want to use the date in a file name so don't require most of the parts.
I'm sure I could do this using a script task to produce a file name for each row of data in my table and add that filename to the dataset but it seem like overkill to do something that should be simple. Also as I'm supposed to be getting to grips with SSIS I shouldn't keep running back to what I know.
My current approach is to derive a column and build up an expression to convert the date into a string. The only problem being that it doesn't work.
The expression I'm working with is:
(DT_WSTR, 50)([OrgName] ) + "_" + (DT_WSTR, 50)( [PayrollName] ) + (DT_WSTR, 4)(YEAR( [ProcessedDate] )) + (DT_WSTR, 2)(MONTH( [ProcessedDate] )) + (DT_WSTR, 2)(DAY( [ProcessedDate] )) ".txt"
Can anyone see where I'm going wrong?
All comments greatly received.
Cheers
BenDoesn't work ? What is the error you are getting ?
Use dt_str instead. Here is an example I am using successfully...
Code Snippet
"FileName_" + (DT_STR,4,1252) DatePart("yyyy",getdate()) +
Right("0" + (DT_STR,4,1252) DatePart("m",getdate()),2) +
Right("0" + (DT_STR,4,1252) DatePart("d",getdate()),2) + Right("0" + (DT_STR,4,1252) DatePart("hh",getdate()),2) +Right("0" + (DT_STR,4,1252) DatePart("n",getdate()),2) +".txt"
Maybe you are looking for
-
Restricting values of a dropdown based on user roles
Hi, Is it possible to restrict the values of a custom metadata dropdown based on the user roles (assuming only 1 role is assigned to each user)? Say, based on the role assigned to a user, he/she should see only 3-4 values out of 10 values in a dropdo
-
Itune card not properly activated
Hi, please help me, i bought itunes gift card and try to redeem it, the code was ok but i cant redeem it and shows a message "The gift certificate or prepaid code you entered has not been properly activated. please contact itunes store customer supor
-
Select on VBAP giving a dump in preproduction system
Hello Experts, We are trying to fetch records from VBAP based on the primary key of VBELN. Even with the primary key, it gives dump in pre production system. select vbeln posnr matnr arktx pstyv abgru zmeng meins netwr waerk kwmeng kbmeng v
-
Hi All, Presently, I am working in OA Framework and I am new to this Framework.Firstly I am going to complete the documentation which they provided in Jdeveloper IDE. I completed HelloWorld example with successfully,but in Search Exercise, I am unabl
-
Importing to different location
Hello, I just got an external hardrive and I am trying to figure out how to import my cd's to it rather than to my computer. I know how to get my ipod to read from it, so I fine there, I just can't figure out how to import directly to it. Is this pos