使用JAXRS将XML MARSHALING XML转换为JAVA对象以实现Restful Service

时间:2012-05-10 16:45:08

标签: java xml rest jax-rs unmarshalling

我正在尝试基于用户上传的XML文件来实现BOOLEAN返回(true / false)。例如,我有一个元素方向,表示它包含的数据类型。所以我感兴趣的是对数据进行编组并返回布尔值。

第1步:对POST方法感兴趣,并将使用POSTMAN chrome app进行测试。

第2步:内容对象保存所有内容以进行编组和编组

package 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:使用Validation Class接收请求并解组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 Service的新手,我阅读的文档很少,并且基于我试图完成给定任务的说明。所以任何帮助,更正,指导,代码都非常感谢。

1 个答案:

答案 0 :(得分: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();
  }
}