2012-05-10 4 views
0

사용자가 XML 파일을 업로드하여 BOOLEAN 반환 (true/false)을 얻으려고합니다. 예를 들어, 포함 된 데이터 유형을 나타내는 요소 방향이 있습니다. 그래서 나는 데이터 마샬링을 해제하고 부울을 반환하는 데 관심이 있습니다.JAXRS를 사용하여 안정적인 서비스를위한 JAVA 객체에 XML을 유엔에서 보복

1 단계 : POST 방법에 관심이 있으며 POSTMAN 크롬 앱을 사용하여 테스트합니다.

2 단계 : 목차 않은 마샬링에 대한 모든 및

패키지 validator.service 마샬링를 개최 객체;

import javax.xml.bind.annotation.XmlElement; 
import javax.xml.bind.annotation.XmlRootElement; 

// Created the Contents object to hold everything for un marshaling and marshaling 

@XmlRootElement(name = "contents") 
public class Contents 
{ 
    @XmlElement 
    String portalarea; 

    @XmlElement 
    String portalsubarea; 

    @XmlElement 
    String direction; 

    public String getportalarea() 
    { 
     return portalarea; 
    } 

    public String getportalsubarea() 
    { 
     return portalsubarea; 
    } 

    public String getdirection() 
    { 
     return direction; 
    } 

} 

3 단계 : 유무 검증 클래스 부울을 반환 할 XML을 요청을 받아 유엔 정렬 화합니다.

package validatorService; 

import java.io.InputStream; 

import javax.xml.bind.JAXBContext; 
import javax.xml.bind.JAXBElement; 
import javax.xml.bind.Unmarshaller; 
import javax.xml.stream.XMLInputFactory; 
import javax.xml.stream.XMLStreamReader; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 

@Path ("/valid") 
public class ValidatorService 
{ 
    boolean n_value = false; 
    boolean r_value = false; 

    @POST 
    @Produces(MediaType.TEXT_PLAIN) 
    @Consumes("application/xml") 
    public String validate(String xmlContent) 
    { 
     HttpClient httpclient = new DefaultHttpClient(); 

     try 
     { 
      if (xmlContent != null) 
      { 
       if (xmlContent.startsWith("https")) 
       { 
        HttpGet xmlGet = new HttpGet(xmlContent); 

        HttpResponse response = httpclient.execute(xmlGet); 
        int responseStatus = response.getStatusLine().getStatusCode(); 
        // String responseMessage = response.getStatusLine().getReasonPhrase(); 

        if (responseStatus == 200) 
        { 
         HttpEntity responseEntity = response.getEntity(); 
         InputStream inStream = responseEntity.getContent(); 

         Contents direction = unmarshalingContent(inStream, xmlContent); 

         if (direction.equals("N")) 
         { 
          n_value = true; 


         } 
         else if (direction.equals("R")) 
         { 
          r_value = true; 


        } 
        else 
        { 
         System.out.println("Response Error : " + responseStatus); // Should be 
                        // handled 
                        // properly 
        } 

       } 
       else 
       { 
        System.out.println(" 'https' Format Error"); // Should be handled properly 
       } 

       return "success"; 
      } 

     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
      System.out.println(" Error caught at catch " + e); // Should be handled properly for 
                   // all exception 
     } 
     finally 
     { 
      httpclient.getConnectionManager().shutdown(); 
     } 

     return null; 
    } 

    public Contents unmarshalingContent(InputStream inputStream, String resourceClass) throws Exception 
    { 
     System.out.println(" welcome "); 

     if (resourceClass == "xmlContent") 
     { 
      JAXBContext jc = JAXBContext.newInstance("com.acme.bar"); 
      Unmarshaller u = jc.createUnmarshaller(); 

      XMLInputFactory inputFactory = XMLInputFactory.newInstance(); 
      XMLStreamReader xReader = inputFactory.createXMLStreamReader(inputStream); 

      JAXBElement<Contents> jaxBElement = (JAXBElement<Contents>) u.unmarshal(xReader, Contents.class); 

      Contents portalArea = (Contents) jaxBElement.getValue(); 
      Contents portalSubarea = (Contents) jaxBElement.getValue(); 
      Contents direction = (Contents) jaxBElement.getValue(); 

      return direction; 
     } 
     throw new Exception("Invalid resource request"); 

    } 
} 

저는 RESTful 서비스에 익숙하며 몇 가지 문서를 읽고 지침에 따라 주어진 작업을 수행하려고합니다. 그래서 어떤 도움, 수정,지도, 코드를 많이 주시면 감사하겠습니다.

답변

4

훨씬 간단 할 수 있습니다. XML에서 Java 로의 오브젝트 변환은 직접 수행 할 필요가 없습니다. JAX-RS 제공자는 자동으로이를 수행합니다.

@POST 
@Produces(MediaType.TEXT_PLAIN) 
@Consumes("application/xml") 
public Response validate(Contents con){ //con will be initialized by JAX-RS 
    //validate your XML converted to object con 
    boolean validation_ok = ... 
    if(validation_ok){ 
    return Response.ok("true").build(); 
    }else{ 
    return Response.ok("false").build(); 
    } 
} 
관련 문제