All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.gs4tr.gcc.restclient.util.APIUtils Maven / Gradle / Ivy

Go to download

GlobalLink Connect Cloud java is a library to connect your system to GlobalLink Connect Cloud REST API.

There is a newer version: 3.1.3
Show newest version
package org.gs4tr.gcc.restclient.util;

import static org.gs4tr.gcc.restclient.util.HttpUtils.addHeaders;
import static org.gs4tr.gcc.restclient.util.HttpUtils.openConnection;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.gs4tr.gcc.restclient.dto.GCResponse;
import org.gs4tr.gcc.restclient.dto.PageableResponseData;
import org.gs4tr.gcc.restclient.operation.Connectors;
import org.gs4tr.gcc.restclient.operation.GCOperation;
import org.gs4tr.gcc.restclient.operation.SessionStart;
import org.gs4tr.gcc.restclient.request.GCRequest;
import org.w3c.dom.DOMException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class APIUtils {

    public static GCResponse doRequestWithParameters(GCOperation operation) {

	MultipartUtility multipart = null;
	try {
	    multipart = new MultipartUtility(operation.getRequestUrl(), operation.getConfig());
	    GCRequest request = operation.getRequestObject();
	    if (request != null && request.getParameters() != null) {
		Map parameters = request.getParameters();

		Map m2 = new HashMap();
		for (Map.Entry entry : parameters.entrySet()) {
		    String key = entry.getKey();
		    if ("connector_id".equals(key)) {
			continue;
		    }
		    if (key.equals("preview_file") || key.equals("file")) {
			m2.put(key, entry.getValue());
		    } else {
			if (!key.equals("ignore_file_name")) {
			    multipart.addFormField(key, "" + entry.getValue());
			}
		    }

		}

		for (Map.Entry entry : m2.entrySet()) {
		    if (parameters.containsKey("name")) {
			multipart.addFilePart(entry.getKey(), (byte[]) entry.getValue(), "" + parameters.get("name"));
		    } else if (parameters.containsKey("ignore_file_name")) {
			multipart.addFilePart(entry.getKey(), (byte[]) entry.getValue(),
				"" + parameters.get("ignore_file_name"));
		    } else {
			multipart.addFilePart(entry.getKey(), (byte[]) entry.getValue(), "unknown");
		    }
		}
	    }

	    HttpURLConnection connection = multipart.finish();

	    String response = null;
	    if (connection.getResponseCode() > 299) {
		response = StringUtils.toString(connection.getErrorStream());
		if (connection.getResponseCode() > 499) {
		    if (connection.getResponseCode() == 503) {
			throw new IllegalStateException("Service Temporarily Unavailable");
		    } else {
			throw new IllegalStateException("Server returned HTTP code " + connection.getResponseCode());
		    }
		}
	    } else {
		response = StringUtils.toString(connection.getInputStream());
	    }
	    ObjectMapper mapper = new ObjectMapper();
	    GCResponse responseObj = mapper.readValue(response, operation.getResponseClass());

	    if (responseObj.getStatus() == null || !responseObj.getStatus().equals(200)) {
		throw new IllegalStateException(responseObj.getMessage());
	    }

	    return responseObj;
	} catch (IOException e) {
	    throw new IllegalStateException("Error sending request: " + e.getMessage());
	}
    }

    public static InputStream doDownload(GCOperation operation) {
	return sendRequest(operation);
    }

    public static Object doRequest(GCOperation operation) {
	String response = null;

	InputStream inputStream = sendRequest(operation);
	try {
	    response = StringUtils.toString(inputStream);
	} catch (IOException e) {
	    throw new IllegalStateException("Error reading response. " + e.getMessage(), e);
	}
	try {
	    ObjectMapper mapper = new ObjectMapper();
	    GCResponse responseObj = mapper.readValue(response, operation.getResponseClass());
	    // not checking if responseObj.getStatus() is 200 or not. some
	    // operations can return 400 or 404 as result
	    return responseObj;
	} catch (IOException e) {
	    throw new DOMException(DOMException.INVALID_STATE_ERR, "Error parsing response. " + e.getMessage());
	}
    }

    private static InputStream sendRequest(GCOperation operation) {
	HttpURLConnection connection = null;

	try {
	    connection = openConnection(operation.getRequestUrl(), operation.getConfig());
	    connection.setRequestMethod(operation.getRequestMethod());
	    if (!(operation instanceof Connectors) && !(operation instanceof SessionStart)) {
		if (operation.getConfig().getConnectorKey() == null) {
		    throw new IllegalStateException(
			    "Connector key is required. You can obtain connector key using 'Connectors' operation");
		}
		connection.setRequestProperty("connector_key", operation.getConfig().getConnectorKey());
	    }
	    connection.setRequestProperty("Authorization", "Bearer " + operation.getConfig().getBearerToken());
	    connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
	    addHeaders(connection, operation.getConfig().getCustomHeaders());

	    if (operation.getRequestMethod().equals("GET")) {
		connection.setDoOutput(false);
	    } else {
		connection.setDoOutput(true);
		if (operation.getRequestObject() != null) {
		    OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(),
			    Charset.forName("UTF-8"));
		    ObjectMapper mapper = new ObjectMapper();
		    String json = mapper.writeValueAsString(operation.getRequestObject());
		    out.write(json);
		    out.close();
		} else if (operation.getRequestJson() != null) {
		    OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(),
			    Charset.forName("UTF-8"));
		    out.write(operation.getRequestJson());
		    out.close();
		}
	    }

	    if (connection.getResponseCode() > 299) {
		if (connection.getErrorStream() != null) {
		    if (connection.getResponseCode() > 499) {
			if (connection.getResponseCode() == 503) {
			    throw new IllegalStateException("Service Temporarily Unavailable");
			} else {
			    throw new IllegalStateException(
				    "Server returned HTTP code " + connection.getResponseCode());
			}
		    } else {
			if (operation.allowErrorResponse()) {
			    return connection.getErrorStream();
			} else {
			    throw new IllegalStateException(
				    "Error sending request. " + StringUtils.toString(connection.getErrorStream()));
			}
		    }
		}
		throw new IllegalStateException("Error sending request. " + connection.getResponseMessage() + "("
			+ connection.getResponseCode() + ")");
	    }

	    return connection.getInputStream();
	} catch (IOException e) {
	    throw new IllegalStateException("Error sending request. " + e.getMessage(), e);
	}
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy