com.dv.sharer.restclients.ImageRestClient.java Source code

Java tutorial

Introduction

Here is the source code for com.dv.sharer.restclients.ImageRestClient.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dv.sharer.restclients;

import com.dv.common.webservices.rest.core.client.BaseRestClientModel;
import com.dv.common.webservices.rest.core.client.IUploadDownload;
import com.dv.common.webservices.rest.core.client.SimpleRestClient;
import com.dv.common.webservices.rest.core.response.Response;
import com.dv.sharer.model.entity.Image;
import com.dv.sharer.model.entity.UserAccount;
import java.text.MessageFormat;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import org.apache.commons.codec.binary.Base64;

/**
 *
 * @author PP76575
 */
public class ImageRestClient extends SimpleRestClient<Image> implements IUploadDownload {

    public ImageRestClient(String baseUrl) {
        super(baseUrl, Image.class);
    }

    public ImageRestClient(String baseUrl, boolean logMessages) {
        super(baseUrl, Image.class, logMessages);
    }

    public byte[] downloadFile(String id) throws ClientErrorException {
        WebTarget resource = getWebTarget();
        resource = resource.path(MessageFormat.format("download/{0}", new Object[] { id }));
        String response = resource.request(MediaType.TEXT_PLAIN).get(String.class);
        return Base64.decodeBase64(response);
    }

    public byte[] downloadFile(Integer id) throws Exception {
        return downloadFile(id.toString());
    }

    public Response uploadFile(Integer id, byte[] data) throws Exception {
        data = Base64.encodeBase64(data);
        String dataStr = new String(data);
        Invocation.Builder builder = getWebTarget().path(MessageFormat.format("upload/{0}", new Object[] { id }))
                .request();
        String response = builder.post(Entity.entity(dataStr, MediaType.TEXT_PLAIN), String.class);
        Response resp = Response.fromJson(response, Response.class);
        return resp;

    }

    @Override
    public String getPath() {
        return "image";
    }

}