erainformatica.utility.JSONHelper.java Source code

Java tutorial

Introduction

Here is the source code for erainformatica.utility.JSONHelper.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 erainformatica.utility;

import erainformatica.tbjhelper.classes.InputFile;
import erainformatica.tbjhelper.classes.TelegramRequestResult;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONObject;

/**
 *
 * @author robertodedomenico
 */
public class JSONHelper {

    private static TelegramRequestResult<String> readAll(Reader rd) {
        try {
            StringBuilder sb = new StringBuilder();
            int cp;
            while ((cp = rd.read()) != -1) {
                sb.append((char) cp);
            }
            return new TelegramRequestResult<>(true, null, sb.toString());
        } catch (Exception e) {
            return new TelegramRequestResult<>(true, e.toString(), null);
        }
    }

    private static TelegramRequestResult<JSONObject> readJsonFromInputStream(InputStream is) {
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            TelegramRequestResult<String> jsonText = readAll(rd);
            if (jsonText.isRequestOk()) {
                JSONObject json = new JSONObject(jsonText.get());
                return new TelegramRequestResult<>(true, null, json);
            } else {
                return new TelegramRequestResult<>(false, "Error in parsing", null);
            }
        } catch (Exception e) {
            try {
                is.close();
            } catch (Exception ex) {
            }
            return new TelegramRequestResult<>(false, e.toString(), null);
        }
    }

    public static TelegramRequestResult<JSONObject> readJsonFromUrl(String url) {
        InputStream is = null;
        try {
            is = new URL(url).openStream();
            return readJsonFromInputStream(is);
        } catch (Exception e) {
            return new TelegramRequestResult<>(false, e.toString(), null);
        }
    }

    public static TelegramRequestResult<JSONObject> readJsonFromUrl(String url, InputFile file) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost uploadFile = new HttpPost(url);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        //builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);
        builder.addBinaryBody(file.getName(), file.getFile_content(), ContentType.APPLICATION_OCTET_STREAM,
                file.getName() + "." + file.getExtension());
        HttpEntity multipart = builder.build();

        uploadFile.setEntity(multipart);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(uploadFile);
        } catch (IOException ex) {
            Logger.getLogger(JSONHelper.class.getName()).log(Level.SEVERE, null, ex);
        }
        HttpEntity responseEntity = response.getEntity();

        try {
            return readJsonFromInputStream(responseEntity.getContent());
        } catch (Exception ex) {
            return new TelegramRequestResult<>(false, ex.toString(), null);
        }

    }
}