logo
down
shadow

Consume multiple resources in a RESTful Web Service


Consume multiple resources in a RESTful Web Service

By : Felix Thomsen
Date : November 21 2020, 01:01 AM
I wish this helpful for you One solution is to just read from an InputStream. You could wrap the InputStream in a ZipInputStream. With ZipInputStream you can get a ZipEntry with ZipInputStream.getNextEntry(), then you can get the file name with ZipEntry.getName(). Then just check if the name endsWith(".xml").
With this though, you would need to consume application/octet-stream. Here's a simple example
code :
@Path("/zip")
public class ZipResource {

    @POST
    @Consumes(MediaType.APPLICATION_OCTET_STREAM)
    public Response postZipFile(InputStream is) throws Exception {
        StringBuilder builder;
        try (ZipInputStream zip = new ZipInputStream(is)) {
            builder = new StringBuilder("==== Data ====\n");
            ZipEntry entry;
            while ((entry = zip.getNextEntry()) != null) {
                String filename = entry.getName();
                if (filename.endsWith(".xml")) {
                    builder.append("name: ").append(entry.getName()).append("\n");
                    String xml = filePartToString(zip, (int) entry.getSize());
                    builder.append("data: ").append(xml).append("\n");
                }
                zip.closeEntry();
            }
        }
        return Response.ok(builder.toString()).build();
    }

    private String filePartToString(InputStream is, int size) throws Exception {
        String xml;
        byte[] buff = new byte[size];
        is.read(buff, 0, size);
        return new String(buff);
    }
}
@Test
public void testResteasy() throws Exception {
    WebTarget target = client.target(
            TestPortProvider.generateURL(BASE_URI)).path("zip");
    File file = new File("C:/test/test.zip");
    Response response = target.request().post(
            Entity.entity(file, MediaType.APPLICATION_OCTET_STREAM));
    System.out.println(response.getStatus());
    System.out.println(response.readEntity(String.class));
    response.close();
}
test1.xml
---------
<test1>hello world</test1>

test2.xml
---------
<test2>hello squirrel</test2>

test3.json
----------
{
    "test3":"Hello Girls"
}
==== Data ====
name: test1.xml
data: <test1>hello world</test1>
name: test2.xml
data: <test2>hello squirrel</test2>
@Provider
@Consumes("application/zip")
public class ZipMessageBodyReader implements MessageBodyReader<ZipInputStream> {

    @Override
    public boolean isReadable(Class<?> type, Type genericType, 
            Annotation[] annotations, MediaType mediaType) {
        return type == ZipInputStream.class;
    }

    @Override
    public ZipInputStream readFrom(Class<ZipInputStream> type, 
            Type genericType, Annotation[] annotations, MediaType mediaType, 
            MultivaluedMap<String, String> httpHeaders, 
            InputStream entityStream) throws IOException, WebApplicationException {

        return new ZipInputStream(entityStream);
    }    
}
@POST
@Consumes("application/zip")
public Response postZipFile(ZipInputStream zip) throws Exception {
@Path("/zip")
public class ZipResource {

    @POST
    @Consumes({"application/zip", "application/xml"})
    public Response postZipFile(InputStream is, @Context HttpHeaders headers) throws Exception {
        String contentType = headers.getHeaderString(HttpHeaders.CONTENT_TYPE);
        String returnString = null;

        if (null != contentType) switch (contentType) {
            case "application/xml":
                returnString = readXmlFile(is);
                break;
            case "application/zip":
                returnString = readZipFile(is);
                break;
        }

        return Response.ok(returnString).build();
    }

    private String filePartToString(InputStream is, int size) throws Exception {
        String xml;
        byte[] buff = new byte[size];
        is.read(buff, 0, size);
        return new String(buff);
    }

    private String readXmlFile(InputStream is) {
        StringWriter writer = new StringWriter();
        try {
            IOUtils.copy(is, writer, "utf-8");
        } catch (IOException ex) {
            Logger.getLogger(ZipResource.class.getName()).log(Level.SEVERE, null, ex);
        }
        return writer.toString();
    }

    private String readZipFile(InputStream is) {
        StringBuilder builder = new StringBuilder("==== Data ====\n");
        try (ZipInputStream zip = new ZipInputStream(is)) {
            ZipEntry entry;
            while ((entry = zip.getNextEntry()) != null) {
                String filename = entry.getName();
                if (filename.endsWith(".xml")) {
                    builder.append("name: ").append(entry.getName()).append("\n");
                    String xml = filePartToString(zip, (int) entry.getSize());
                    builder.append("data: ").append(xml).append("\n");
                }
                zip.closeEntry();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return builder.toString();
    }
}
@Provider
@Consumes("application/zip")
public class ZipMessageBodyReader implements MessageBodyReader<InputStream> {
    @Override
    public boolean isReadable(Class<?> type, Type genericType, 
            Annotation[] annotations, MediaType mediaType) {
        return type == InputStream.class;
    }

    @Override
    public InputStream readFrom(Class<InputStream> type, 
            Type genericType, Annotation[] annotations, MediaType mediaType, 
            MultivaluedMap<String, String> httpHeaders, 
            InputStream entityStream) throws IOException, WebApplicationException {

        return entityStream;
    }  
}
@Test
public void testResteasy() throws Exception {
    WebTarget target = client.target(
            TestPortProvider.generateURL(BASE_URI)).path("zip");


    File file = new File("C:/test/test.zip");
    Response response = target.request().post(
            Entity.entity(file, "application/zip"));

    System.out.println(response.getStatus());
    System.out.println(response.readEntity(String.class));
    response.close();

    file = new File("C:/test/test1.xml");
    response = target.request().post(
            Entity.entity(file, "application/xml"));

    System.out.println(response.getStatus());
    System.out.println(response.readEntity(String.class));
    response.close();

}
200
==== Data ====
name: test1.xml
data: <test1>hello world</test1>
name: test2.xml
data: <test2>hello squirrel</test2>

200
<test1>hello world</test1>
@Provider
@Produces("application/xml")
public class ZipClientMessageBodyWriter implements MessageBodyWriter<File> {

    @Override
    public boolean isWriteable(Class<?> type, Type genericType, 
            Annotation[] annotations, MediaType mediaType) {
        return type == File.class;
    }

    @Override
    public long getSize(File t, Class<?> type, Type genericType, 
            Annotation[] annotations, MediaType mediaType) {
        return -1;
    }

    @Override
    public void writeTo(File t, Class<?> type, Type genericType, 
            Annotation[] annotations, MediaType mediaType, 
            MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) 
            throws IOException, WebApplicationException {

        IOUtils.write(IOUtils.toByteArray(new FileInputStream(t)), entityStream);
    }  
}

....

client.register(ZipClientMessageBodyWriter.class);


Share : facebook icon twitter icon
Deleting multiple resources during a single request in a RESTful service

Deleting multiple resources during a single request in a RESTful service


By : Sabri
Date : March 29 2020, 07:55 AM
Any of those help It feels a little odd because the RESTful URI doesn't name a "resource", but rather a collection of resources.
While it feels a little odd, I think there are no better ways to specify that kind of "collection".
code :
/path/to/resource/in:filter;filter;filter/
How do you consume a RESTful WCF service from an ASP project using a service reference?

How do you consume a RESTful WCF service from an ASP project using a service reference?


By : user3294307
Date : March 29 2020, 07:55 AM
Any of those help Take a look at ADO.Net data services, which specifically supports rest API's, and will return data in formats other than XML e.g. JSON
http://msdn.microsoft.com/en-us/data/bb931106
Implementing RESTful service and consume xml at the service and map it to a bean class

Implementing RESTful service and consume xml at the service and map it to a bean class


By : Gabriela
Date : March 29 2020, 07:55 AM
Hope this helps The same site that you tried the json example also provides a RESTEasy + JAXB example. Hope this helps.
how to consume a Restful Web Service (Restful API) in Java

how to consume a Restful Web Service (Restful API) in Java


By : skaggs
Date : March 29 2020, 07:55 AM
it fixes the issue There are many ways to consume RESTful APIs.
Typically, you need to know what version of the API you are going to use. When the API changes (i.e. a different version is exposed) you need to decide if the new functionality is worth migrating your application(s) to the latest and greatest or not...
How to create/consume WCF oData Service (RESTful Service) using U2 toolkit for .NET?

How to create/consume WCF oData Service (RESTful Service) using U2 toolkit for .NET?


By : Shivam Gupta
Date : March 29 2020, 07:55 AM
To fix this issue I want to create WCF oData Service (RESTful Service) using U2 Toolkit for .NET and U2 Database. Then I want to consume oData Service in any .NET Client Application. , Please see my answer below:
Overview
Related Posts Related Posts :
  • How to write generic Java API without method Overloading
  • Java Serialization / Deserialization of an ArrayList works only on first program execution
  • Conway's Game of Life's rules dont apply properly
  • call a java method when Click on a html button without using javascript
  • Why does SSLSocketFactory.createSocket returns a Socket instead of SSLSocket?
  • How to schedule a task in Tomcat
  • compare two pdf files (approach) using java
  • What is the use of allowCoreThreadTimeout( ) in ThreadPoolExecutor?
  • Describe the Strategy Design Pattern in Java?
  • MongoDB too many open connections
  • Issue with generate JAXB classes with value constructors
  • Moving from one frame to another in java swing
  • Get a thread by Id
  • how to open front camera and back camera at same time?
  • Messed up with Java Declaration
  • Extracting chart in EXcel as image using java
  • How to get latitude and longitude in Android phone?
  • Do GC pauses and kill -STOP produce the same behavior?
  • Android HTML.ImageGetter Images resized
  • The way to instantiate map<String, List<String>> in Java
  • Java Making objects move while buttons held
  • Androidx Navigation View - `setNavigationItemSelectedListener` Doesn't Work
  • after compiling code JFrame does not appear
  • Netbeans project, JFrames ran from the main JFrame close all JFrames in project
  • Square Retrofit Client: How to enable/disable followRedirects? How to intercept redirect URL?
  • Java Circular Reference - Can’t Compile
  • Mouse click on specific time JAVA
  • android 4 onCreateDialog return type incompatible when overriding
  • Java Implementation of Oracle's DBMS_UTILITY.GET_HASH_VALUE Function
  • javac cannot be run, and furthermore does not seem installed
  • Function to obtain a thread given its ID
  • Java File path to Executable has spaces
  • Minimum Oracle Java VM heap memory setting?
  • Elegant way to create one of a large number of classes
  • Java fx binding styles
  • Summing weights based on string in large file
  • Android ListView setOnItemClickListener not working
  • How is the Java Bootstrap Classloader loaded?
  • Check object is blank
  • Add image between text in JEditorPane
  • Java POI Excel creating new column and new rows
  • NullPointerException when managing bean with Spring+JSF(Primefaces)
  • Content autocomplete in spring tool suite 4
  • Super Noob Help ~ MouseEvent/Frame
  • Making one project with dependencies stand-alone in Eclipse (Java)
  • Jsoup- getting certain attributes from website
  • MongoDB, how to make a link between collections with JAVA code
  • Overriding an abstract method means class abstract class or not in java?
  • Bukkit teleport - nullPointerException
  • How to check if a Float variable is negative in java
  • Servlet: Cannot forward after response has been committed
  • sql query to select a specific cell in excel
  • How to make new picture when mouse dragged in java
  • Use Constants interface in GWT Project
  • Setting size of a JPanel in GroupLayout
  • Construct a map from two equal size arrays
  • Implementing Read-Write Locks with Double-Checked Locking
  • Disable NO_BUTTON from JOptionPane Java if a condition is true
  • UDP multiple socket
  • Android Threading: This Handler class should be static or leaks might occur
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org