MediaType для ProtoBuf - PullRequest
       43

MediaType для ProtoBuf

8 голосов
/ 19 марта 2020

Мне нужно отправить данные protobuf в мою конечную точку от клиента, которого я создал. Ниже приведен код для конечной точки клиента и JAXRS.

--client
Client genClient = ClientBuilder.newClient();
WebTarget target2 = genClient.target("http://localhost:8080/ClientJAXRS/rest/Hello").path("/proto");
 String inputproto = String.format("\n" +  "syntax = \"proto3\";\n" + 
                "message Struct1 {\n" + 
                " string   s1Att1 = 1;\n" + 
                " int32    s1Att2 = 2;\n" + 
                " int32    s1Att3 = 3;\n" + 
                " Struct2  s1Att4 = 4;\n" + 
                " message Struct2 {\n" + 
                " repeated string s2Att1 = 1;\n" + 
                "  }\n" + 
                 + " ");
Response res =  target2.request("application/x-protobuf").put(Entity.text(inputproto));

--endpoint
@PUT
@Path("/proto")
@Consumes("application/x-protobuf")
//@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getInfo(String text){



  return    Response.ok(text.getBytes(),MediaType.APPLICATION_OCTET_STREAM).status(200).build();
}

вывод, который я получаю для этого, является неподдерживаемым MediaType.

context=ClientResponse{method=PUT, uri=http://localhost:8080/ClientJAXRS/rest/Hello/proto, status=415, reason=Unsupported Media Type}}

Помогите мне с MIME TYPE для proto или proto Формат, который отправить.

Редактировать 2:

Я создал отдельный файл для protobuf в data.proto

syntax = "proto3";
 option java_outer_classname = "DataProtos";
 option java_package = "com.client.JAXClient";
 message Album {
     optional string title = 1;
     repeated string artist = 2;
     repeated int32 release_year = 3;
     required string song_title = 4;
 }

Сгенерировал код для него в java, используя proto c - Я кодировал и получил сгенерированный класс Album.

Реализовал для него MessagebodyWriter и MessageBodyReader, как указано ниже

@Provider
@Produces("application/x-protobuf")
@Consumes("application/x-protobuf")
public class ProtoMessageBodyWriter implements MessageBodyWriter<Album>,MessageBodyReader<Album> {

    @Override
    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        // TODO Auto-generated method stub
        return type == Album.class ;
    }

    @Override
    public void writeTo(Album t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
            MultivaluedMap<String, Object> httpHeaders, OutputStream out)
            throws IOException, WebApplicationException {
            Writer writer = new PrintWriter(out);
            t.writeTo(out);

    }

    @Override
    public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        // TODO Auto-generated method stub
        return type == Album.class ;
    }

    @Override
    public Album readFrom(Class<Album> type, Type genericType, Annotation[] annotations, MediaType mediaType,
            MultivaluedMap<String, String> httpHeaders, InputStream in)
            throws IOException, WebApplicationException {
            return Album.parseFrom(in);
    }

}

Добавлены 2 конечные точки для protobuf, как показано ниже

@GET
@Path("/proto-data")
@Consumes("application/x-protobuf")
 public Response getInfo(Album inpAlbum){
                   StringBuilder sbuilder = new  StringBuilder("Input album");
                   sbuilder.append("ID: ").append(inpAlbum.getReleaseYear()).append("\n");
                   sbuilder.append("Name: ").append(inpAlbum.getArtist()).append("\n");
                    return Response.created(null).entity(sbuilder.toString()).build();

}

I я пытаюсь получить доступ к этим конечным точкам от Клиента, используя

Response response =null;
Client client =null;
client = ClientBuilder.newClient();
WebTarget target2 = client.target("http://localhost:8081/ClientJAXRS/rest/Hello").path("/proto-data");
response= target2.request().get();
System.out.println(response);

Но ответ

ClientJAXRS/rest/Hello/proto-data, status=500, reason=Internal Server Error}}
text/html;charset=utf-
...