Total Pageviews

Wednesday 4 April 2012

best way to keep data in the form when failing to submit in JSP

Problem:
When submiting the page, sometime it fails because of the validation. At this time, the data in the page  are lost, and we have to type everything again.
Solution:
Declare the varaible at the beginning, and assign the value from the request. But if it's first fime calling the page, assign it as empty string.

        <%
        String xmlStr=request.getParameter("xmlStr");if(xmlStr==null)xmlStr="";
        %>
         <form method=GET >
                <tr>
                    <td><textarea name="xmlStr" rows="12" cols="100"><%=xmlStr%></textarea></td>                   
                </tr>              
               <tr><td><input type=submit name=submit value='Post'/></td></tr>
            </table>           
        </form>
        <%
         if(request.getParameter("submit") != null){
          
                  if(xmlStr == null || xmlStr.equals("")) {
                  out.println("<p>xmlStr empty!</p>");  
                 return;
           }         
           // do whatever
         }
         %>
 

how to handle binary data such as image in soap based web service

Web Service Part:
supposed that  you have a picture named Desert.jpg in package resources

@WebService(serviceName = "PictureService")
@Stateless()
public class PictureService {   
      
     @WebMethod(operationName = "getImage")
    public byte[] getImage( ) throws IOException {
   URL resource = this.getClass().getResource("/resources/Desert.jpg");
   InputStream in = resource.openStream();
     ByteArrayOutputStream bos = new ByteArrayOutputStream();
     byte[] buf = new byte[1024];
    for(int read; (read = in.read(buf)) != -1;) {
        bos.write(buf, 0, read);
     }
        return bos.toByteArray()s;
    }
   
}

Client part as Servlet:

public class test extends HttpServlet {
   
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
      
        try {
            PictureService_Service service = new PictureService_Service();
            PictureService port=service.getPictureServicePort(); 
           
            response.setContentType("image/jpeg");  
            OutputStream out = response.getOutputStream();  
           
            byte[] content = port.getImage();
             
            out.write(content);  
           
            out.close();
        } catch (IOException_Exception ex) {
            Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
        }
            }
   
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
   
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
   
    @Override
    public String getServletInfo() {
        return "Short description";
    }
}

Sunday 1 April 2012

Unmarshalling from XML file and marshalling to XML file

            ObjectFactory of = new ObjectFactory();
            FlightInfo sh = of.createFlightInfo();
            //Unmarshalling
            JAXBContext ctx = JAXBContext.newInstance(sh.getClass().getPackage().getName());
            Unmarshaller unm = ctx.createUnmarshaller();
            sh= (FlightInfo)unm.unmarshal(new File("flight.xml"));

           //do something with object sh

            //Marshalling
            try {               
                javax.xml.bind.Marshaller marshaller = ctx.createMarshaller();
                marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8");
                marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
                marshaller.marshal(sh, new FileOutputStream(new File("flight.xml")));
            } catch (javax.xml.bind.JAXBException ex) {
            // Handle exception
            java.util.logging.Logger.getLogger("global").log(java.util.logging.Level.SEVERE, null, ex);
            }    

How to convert String to XMLGregorianCalendar

String mydatetime="2011-09-29T08:55:00";
XMLGregorianCalendar xgc=DatatypeFactory.newInstance().newXMLGregorianCalendar(mydatetime);

Monday 26 March 2012

How to cast a list in inheritance

For Example:
public class Person {};
public class Student extends Person{};
List<Person> persons=new ArrayList();
List<Student> students=new ArrayList();

persons=students;

how can you assign students to persons? the last line will throw an error.

Wednesday 21 March 2012

Example of Inheritance in EJB

table structure

create table "APP".PERSON
(
 ID INTEGER not null primary key,
 NAME VARCHAR(256),
 ADDRESS VARCHAR(256),
 PHONE VARCHAR(256),
 EMAIL VARCHAR(256),
 TYPE VARCHAR(256)
)



person.java

import javax.persistence.*;



@Entity
@Table(name = "PERSON")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "TYPE", discriminatorType = DiscriminatorType.STRING,length=1)
public class Person implements java.io.Serializable {

@Id
@Column(name = "ID")
private int id;
@Column(name = "NAME")
private String name;
@Column(name = "ADDRESS")
private String address;
@Column(name = "PHONE")
private String phone;
@Column(name = "EMAIL")
private String email;
@Column(name = "TYPE")
private String type;

public Person() {
}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getAddress() { return address; }
public void setAddress(String address) { this.address = address; }
public String getPhone() { return phone; }
public void setPhone(String phone) { this.phone = phone; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
}

student.java

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue(value="S")
public class Student extends Person {
    public Student() {
    }
}

employee.java

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;@Entity
@DiscriminatorValue(value="E")
public class Employee extends Person{
    public Employee() {
    }

Tuesday 20 March 2012

How to get max value for identity column in EJB-QL

For example,
I have a table Bookorder  with an Identity column Id.

I can execute the following:
Query query1 = em.createQuery("SELECT MAX(b.id) FROM Bookorder b");       
int bo_max=(Integer)query1.getSingleResult();

Please notice that it's Integer and not int when casting the result of query.

Sunday 18 March 2012

Get Auto Increment Id after persist

If you have entity marked with annotations @Id and @GeneratedValue(strategy = GenerationType.AUTO), you want get the Id after persist(), then use em.flush().

public int addEmployer(String name) {
        Employer e1 = new Employer();       
        e1.setName(name);
        em.persist(e1);
        em.flush();       
        return e1.getId();
    }

How to persist entity with auto increment Id

when create new entity class from database, if the primary key (for example "Id") with auto increment get annotation @NotNull. At this time, if you use entity manager try to persist an entity, neither set the Id value nor automaticly generate the Id.

Foe Example:

Employer e1 = new Employer();       
e1.setName(name);
em.persist(e1);

The above will get error

In the Employer entity class

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@NotNull.-----------------------------------------------------Delete it!!
@Basic(optional = false)
@Column(name = "ID")
private Integer id;

You will  fix the problem.

Saturday 17 March 2012

Id Auto Increment in Java DB

Using Database Table grab structure  can get the following:

create table "APP".EMPLOYER
(
 ID INTEGER default AUTOINCREMENT: start 1 increment 1 not null primary key,
 NAME VARCHAR(256)
);

but  this can never be run in the SQL command window
To fix the problem, change the above to the following:

CREATE TABLE "APP"."EMPLOYER"
("ID" INT not null primary key         GENERATED ALWAYS AS IDENTITY         (START WITH 1, INCREMENT BY 1),  
"NAME" VARCHAR(256));