rogerthat.topdesk.bizz.Util.java Source code

Java tutorial

Introduction

Here is the source code for rogerthat.topdesk.bizz.Util.java

Source

/*
 * Copyright 2018 Mobicage NV
 * NOTICE: THIS FILE HAS BEEN MODIFIED BY MOBICAGE NV IN ACCORDANCE WITH THE APACHE LICENSE VERSION 2.0
 * Copyright (c) 2011-2018, GIG Technology NV
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 * must display the following acknowledgement:
 * This product includes software developed by GIG Technology NV.
 * 4. Neither the name of the GIG Technology NV nor the
 * names of its contributors may be used to endorse or promote products
 * derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY GIG TECHNOLOGY NV "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL GIG TECHNOLOGY NV BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @@license_version:1.13@@
 */

package rogerthat.topdesk.bizz;

import com.google.appengine.api.urlfetch.*;
import org.apache.http.HttpEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.jivesoftware.smack.util.Base64;
import org.json.JSONObject;
import rogerthat.topdesk.dal.Settings;

import javax.mail.internet.ContentType;
import javax.mail.internet.ParseException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Logger;

public class Util {
    private static final Logger log = Logger.getLogger(Util.class.getName());

    static String getContent(HTTPResponse response) throws ParseException, UnsupportedEncodingException {
        String contentType = getHeader(response, "Content-Type");
        String characterSet = null;
        if (contentType != null) {
            ContentType type = new ContentType(contentType);
            characterSet = type.getParameter("charset");
        }
        if (characterSet == null) {
            characterSet = "ASCII";
        }
        log.info("characterset: " + characterSet);
        return new String(response.getContent(), characterSet);
    }

    private static String getHeader(HTTPResponse response, String headerName) {
        for (HTTPHeader header : response.getHeaders()) {
            if (header.getName().equals(headerName)) {
                return header.getValue();
            }
        }
        return null;
    }

    public static String topdeskAPIGet(String apiKey, String path) throws IOException, ParseException {
        final Settings settings = Settings.get();
        URL url = new URL(settings.get("TOPDESK_API_URL") + path);
        HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET, FetchOptions.Builder.withDeadline(30));
        request.addHeader(new HTTPHeader("Authorization", "TOKEN id=\"" + apiKey + "\""));
        request.addHeader(new HTTPHeader("Content-type", "application/json"));
        request.addHeader(new HTTPHeader("Accept", "application/json"));
        URLFetchService urlFetch = URLFetchServiceFactory.getURLFetchService();
        HTTPResponse response = urlFetch.fetch(request);
        String content = getContent(response);
        int responseCode = response.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new TopdeskApiException(
                    "GET to " + path + " failed with response code " + responseCode + "\nContent:" + content);
        }
        return content;
    }

    public static String topdeskAPIPost(String apiKey, String path, JSONObject jsonData)
            throws IOException, ParseException {
        final Settings settings = Settings.get();
        URL url = new URL(settings.get("TOPDESK_API_URL") + path);
        HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST, FetchOptions.Builder.withDeadline(30));
        request.setPayload(jsonData.toString().getBytes("UTF-8"));
        String authHeader = "TOKEN id=\"" + apiKey + "\"";
        log.info("Authorization header: " + authHeader);
        request.addHeader(new HTTPHeader("Authorization", authHeader));
        request.addHeader(new HTTPHeader("Content-type", "application/json"));
        request.addHeader(new HTTPHeader("Accept", "application/json"));
        URLFetchService urlFetch = URLFetchServiceFactory.getURLFetchService();
        HTTPResponse response = urlFetch.fetch(request);
        String content = getContent(response);
        int responseCode = response.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new TopdeskApiException(
                    "POST to " + path + " failed with response code " + responseCode + "\nContent:" + content);
        }
        return content;
    }

    public static String getTopdeskApiKey() throws IOException, ParseException {
        final Settings settings = Settings.get();
        final String loginString = "Basic " + Base64.encodeBytes(
                (settings.get("TOPDESK_USERNAME") + ":" + settings.get("TOPDESK_PASSWORD")).getBytes());
        log.info("loginString: " + loginString);
        URLFetchService urlFetch = URLFetchServiceFactory.getURLFetchService();
        URL url = new URL(settings.get("TOPDESK_API_URL") + "/login");
        HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET, FetchOptions.Builder.withDeadline(30));
        request.addHeader(new HTTPHeader("Authorization", loginString));
        HTTPResponse response = urlFetch.fetch(request);
        String content = getContent(response);
        if (response.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new TopdeskApiException(
                    "Could not login\n Response code " + response.getResponseCode() + "\nContent:" + content);
        } else {
            return content;
        }
    }

    public static byte[] download(String downloadUrl) throws IOException {
        URL url = new URL(downloadUrl);
        log.info("Downloading " + downloadUrl);
        HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET, FetchOptions.Builder.withDeadline(30));
        URLFetchService urlFetch = URLFetchServiceFactory.getURLFetchService();
        HTTPResponse response = urlFetch.fetch(request);
        int responseCode = response.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new RuntimeException(
                    "Downloading of image " + downloadUrl + " failed with response code " + responseCode);
        }
        return response.getContent();
    }

    public static void addMultipartBodyToRequest(HttpEntity entity, HTTPRequest req) throws IOException {
        /*
         * turn Entity to byte[] using ByteArrayOutputStream
         */
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        entity.writeTo(bos);
        byte[] body = bos.toByteArray();

        /*
         * extract multipart boundary (body starts with --boundary\r\n)
         */
        String boundary = new BufferedReader(new StringReader(new String(body))).readLine();
        boundary = boundary.substring(2, boundary.length());

        /*
         * add multipart header and body
         */
        req.addHeader(new HTTPHeader("Content-type", "multipart/form-data; boundary=" + boundary));
        req.setPayload(body);
    }

    public static void uploadFile(String apiUrl, String apiKey, String unid, byte[] content, String contentType,
            String fileName) throws IOException, ParseException {
        URL url = new URL(apiUrl + "/api/incident/upload/" + unid);
        HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST, FetchOptions.Builder.withDeadline(30));
        log.info("Uploading attachment of size " + content.length / 1000 + "KB");
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE).addBinaryBody("filename", content,
                        org.apache.http.entity.ContentType.create(contentType), fileName);

        addMultipartBodyToRequest(multipartEntityBuilder.build(), request);
        String authHeader = "TOKEN id=\"" + apiKey + "\"";
        request.addHeader(new HTTPHeader("Authorization", authHeader));
        URLFetchService urlFetch = URLFetchServiceFactory.getURLFetchService();
        HTTPResponse response = urlFetch.fetch(request);
        int responseCode = response.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            String responseContent = getContent(response);
            throw new TopdeskApiException("Uploading image " + fileName + " failed with response code "
                    + responseCode + "\nContent:" + responseContent);
        }
    }
}