简体   繁体   English

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

[英]UN MARSHALING XML to JAVA object for Restful Service using JAXRS

I am trying to achieve BOOLEAN return (true/false) based on XML file upload by user. 我正在尝试根据用户上传的XML文件实现BOOLEAN返回(真/假)。 For instance, I have a element direction which indicates type of data it contains. 例如,我有一个元素方向指示它包含的数据类型。 So i am interested in un marshaling the data and return boolean. 因此,我有兴趣取消封送数据并返回布尔值。

Step 1: Interested in POST method and would be testing using POSTMAN chrome app. 第1步:对POST方法感兴趣,将使用POSTMAN chrome应用程序进行测试。

Step 2: Contents object to hold everything for un marshaling and marshaling 步骤2:Contents对象容纳要进行封送和封送处理的所有内容

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;
    }

}

Step 3: Have Validation Class for receiving the Request and un marshal the XML to return boolean. 步骤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" );

    }
}

I am new to RESTful Service and i read few documents and based on instructions i am trying to achieve the given task. 我是RESTful Service的新手,我阅读了很少的文档,并且根据说明,我试图完成给定的任务。 So any help, corrections, guidance, code is much appreciated. 因此,非常感谢您提供任何帮助,更正,指导和代码。

It can be much simpler. 它可以简单得多。 You don't need to do XML to Java object conversion by hand. 您无需手动进行XML到Java对象的转换。 JAX-RS providers are doing that automatically. 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();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM