es.carebear.rightmanagement.client.admin.GetAllGroups.java Source code

Java tutorial

Introduction

Here is the source code for es.carebear.rightmanagement.client.admin.GetAllGroups.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 es.carebear.rightmanagement.client.admin;

import com.google.gson.Gson;
import es.carebear.rightmanagement.client.exceptions.BadRequestException;
import es.carebear.rightmanagement.client.exceptions.InternalServerErrorException;
import es.carebear.rightmanagement.client.exceptions.UnknownResponseException;
import es.carebear.rightmanagement.client.xml.XMLHelper;
import es.carebear.rightmanagement.core.exceptions.UnauthorizedException;
import es.carebear.rightmanagement.core.group.Group;
import es.carebear.rightmanagement.core.misc.StringListContainer;
import es.carebear.rightmanagement.core.user.User;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpStatus;

/**
 *
 * @author hannes
 */
public class GetAllGroups {
    private String baseUri;
    private HttpClient httpClient;

    public GetAllGroups(String baseUri) {
        this.baseUri = baseUri;
        this.httpClient = new HttpClient();
    }

    public Group[] getAll(String authName) throws IOException, IllegalArgumentException,
            InternalServerErrorException, BadRequestException, UnauthorizedException, UnknownResponseException {
        PostMethod postMethod = new PostMethod(baseUri + "/client/groups/all");
        postMethod.addParameter("authName", authName);
        int responseCode = httpClient.executeMethod(postMethod);

        switch (responseCode) {
        case HttpStatus.SC_ACCEPTED:
            String response = XMLHelper.fromStreamToXML(postMethod.getResponseBodyAsStream());
            StringListContainer lc = XMLHelper.fromXML(response, StringListContainer.class);
            List<Group> ls = new ArrayList<>();
            lc.getContainer().stream().forEach(obj -> {
                Gson gson = new Gson();
                ls.add(gson.fromJson(obj, Group.class));
            });
            return ls.toArray(new Group[ls.size()]);
        case HttpStatus.SC_INTERNAL_SERVER_ERROR:
            throw new InternalServerErrorException();
        case HttpStatus.SC_UNAUTHORIZED:
            throw new UnauthorizedException();
        case HttpStatus.SC_BAD_REQUEST:
            throw new BadRequestException();
        default:
            throw new UnknownResponseException((new Integer(responseCode)).toString());

        }

    }
}