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

org.bdware.doip.httprepo.HttpRepoHandler Maven / Gradle / Ivy

There is a newer version: 1.5.4
Show newest version
package org.bdware.doip.httprepo;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import io.netty.channel.ChannelHandlerContext;
import org.apache.http.HttpHost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.doip.RocksDBUtil;
import org.bdware.doip.audit.client.AuditIrpClient;
import org.bdware.doip.codec.digitalObject.DigitalObject;
import org.bdware.doip.codec.digitalObject.DoType;
import org.bdware.doip.codec.digitalObject.Element;
import org.bdware.doip.codec.doipMessage.DoipMessage;
import org.bdware.doip.codec.doipMessage.DoipMessageFactory;
import org.bdware.doip.codec.doipMessage.DoipResponseCode;
import org.bdware.doip.endpoint.server.DoipRequestHandler;
import org.bdware.doip.endpoint.server.RepositoryHandler;
import org.bdware.irp.exception.IrpClientException;
import org.bdware.irp.irplib.exception.IrpServerException;
import org.bdware.irp.stateinfo.StateInfoBase;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.NoRouteToHostException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class HttpRepoHandler implements DoipRequestHandler, RepositoryHandler {
    private static final Logger LOGGER = LogManager.getLogger(HttpRepoHandler.class);
    AuditIrpClient irpClient;
    public String repoId;
    RocksDBUtil doTable = RocksDBUtil.loadDB("./httpDOTable", false);
    PoolingHttpClientConnectionManager cm;

    public HttpRepoHandler(AuditIrpClient irpClient, String repoId) {
        this.irpClient = irpClient;
        this.repoId = repoId;
        cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(2000);
        cm.setDefaultMaxPerRoute(50);
    }

    @Override
    public DoipMessage onRequest(ChannelHandlerContext ctx, DoipMessage msg) {
        DoipMessage result = handle(msg);
        return result;
    }

    private DoipMessage handle(DoipMessage msg) {
        DoipMessageFactory.DoipMessageBuilder builder = new DoipMessageFactory.DoipMessageBuilder();
        DoipMessage ret = builder.createResponse(DoipResponseCode.Invalid, msg).create();
        ret.body.encodedData = "Failed!!!".getBytes(StandardCharsets.UTF_8);
        return ret;
    }

    @Override
    public DoipMessage handleHello(DoipMessage doipMessage) {
        DoipMessageFactory.DoipMessageBuilder builder = new DoipMessageFactory.DoipMessageBuilder();
        DoipMessage ret = builder.createResponse(DoipResponseCode.Invalid, doipMessage).create();
        ret.body.encodedData = "Hello".getBytes(StandardCharsets.UTF_8);
        return ret;
    }

    @Override
    public DoipMessage handleListOps(DoipMessage doipMessage) {
        return onRequest(null, doipMessage);
    }

    @Override
    public DoipMessage handleCreate(DoipMessage doipMessage) {
        DoipMessageFactory.DoipMessageBuilder builder = new DoipMessageFactory.DoipMessageBuilder();
        try {
            JsonObject attr = prettyAttr(doipMessage);
            String doid = createHttp(attr);
            DoipMessage ret = builder.createResponse(DoipResponseCode.Success, doipMessage).create();
            ret.header.parameters.id = doid;
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
            DoipMessage ret = builder.createResponse(DoipResponseCode.Invalid, doipMessage).create();
            ret.body.encodedData = e.getMessage().getBytes(StandardCharsets.UTF_8);
            return ret;
        }
    }

    private JsonObject prettyAttr(DoipMessage doipMessage) throws Exception {
        JsonObject attr = doipMessage.body.getDataAsDigitalObject().attributes;
        String url = attr.get("url").getAsString();
        if (!url.startsWith("https://") && !url.startsWith("http://")) {
            throw new IrpServerException("unsupported  uri type");
        }
        String str = attr.get("method").getAsString().toUpperCase();
        switch (str) {
            case "GET":
            case "POST":
            case "PUT":
            case "DELETE":
            case "OPTION":
                attr.addProperty("method", str);
                break;
            default:
                attr.addProperty("method", "GET");
        }
        JsonElement headers = getPropWithDefault(attr, "headers", new JsonObject()).getAsJsonObject();
        attr.remove("headers");
        if (headers.isJsonObject()) {
            attr.add("headers", headers);
        }
        return attr;
    }

    private JsonElement getPropWithDefault(JsonObject attr, String headers, JsonElement jsonObject) {
        try {
            return attr.get(headers);
        } catch (Exception e) {
            return jsonObject;
        }
    }

    public String createHttp(JsonObject httpInfo) {
        //检查前缀是不是repo自身id,后缀是要获取的对应do
        StateInfoBase base = new StateInfoBase();
        base.handleValues = new JsonObject();
        base.handleValues.addProperty("repoId", repoId);
        base.handleValues.addProperty("createTime", System.currentTimeMillis());
        String ret = null;
        try {
            ret = irpClient.register(base);
            doTable.put(ret, httpInfo.toString());
        } catch (IrpClientException e) {
            e.printStackTrace();
        }
        return ret;
    }


    @Override
    public DoipMessage handleUpdate(DoipMessage doipMessage) {
        DoipMessageFactory.DoipMessageBuilder builder = new DoipMessageFactory.DoipMessageBuilder();
        try {
            JsonObject attr = prettyAttr(doipMessage);
            String doid = doipMessage.header.parameters.id;
            if (doid != null && doTable.get(doid) != null) {
                doTable.put(doid, attr.toString());
            }
            DoipMessage ret = builder.createResponse(DoipResponseCode.Success, doipMessage).create();
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
            DoipMessage ret = builder.createResponse(DoipResponseCode.Invalid, doipMessage).create();
            ret.body.encodedData = e.getMessage().getBytes(StandardCharsets.UTF_8);
            return ret;
        }
    }

    @Override
    public DoipMessage handleDelete(DoipMessage doipMessage) {
        DoipMessageFactory.DoipMessageBuilder builder = new DoipMessageFactory.DoipMessageBuilder();
        try {
            String doid = doipMessage.header.parameters.id;
            irpClient.unRegister(doid);
            doTable.delete(doid);
            builder.createResponse(DoipResponseCode.Success, doipMessage);
            builder.setBody("success".getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            e.printStackTrace();
            builder.createResponse(DoipResponseCode.Declined, doipMessage);
            builder.setBody(e.getMessage().getBytes(StandardCharsets.UTF_8));
        }
        return builder.create();
    }

    private void sendHttpRequest(URL url) {

// Increase max connections for localhost:80 to 50
        HttpHost localhost = new HttpHost("locahost", 80);

        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(cm)
                .build();
//        HttpGet
//         httpClient.execute();
    }

    @Override
    public DoipMessage handleRetrieve(DoipMessage doipMessage) {
        DoipMessageFactory.DoipMessageBuilder builder = new DoipMessageFactory.DoipMessageBuilder();
        String urlStr2 = "===";
        try {
            JsonObject attr = JsonParser.parseString(doTable.get(doipMessage.header.parameters.id)).getAsJsonObject();
            JsonObject headers = getPropWithDefault(doipMessage.header.parameters.attributes,
                    "headers", new JsonObject()).getAsJsonObject();
            String query = getPropWithDefault(doipMessage.header.parameters.attributes,
                    "query", new JsonPrimitive("")).getAsString();
            String method = attr.get("method").getAsString();
            JsonObject defaultHeader = attr.getAsJsonObject("headers");
            for (String key : headers.keySet())
                defaultHeader.add(key, headers.get(key));
            byte[] body = doipMessage.body.encodedData;
            String urlStr = attr.get("url").getAsString() + query;
            urlStr2 = urlStr;
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(method);
            for (String key : defaultHeader.keySet())
                connection.setRequestProperty(key, defaultHeader.get(key).getAsString());
            connection.setDoOutput(true);
            connection.setDoInput(true);
            if (body != null && body.length > 0) {
                connection.getOutputStream().write(body);
                connection.getOutputStream().flush();
            }
            JsonObject respHeader =
                    loadHeader(connection);
            byte[] buff = loadAllBytesAndClose(connection.getInputStream());
            byte[] errBuff = loadAllBytesAndClose(connection.getErrorStream());
            connection.disconnect();
            builder.createResponse(DoipResponseCode.Success, doipMessage);
            builder.addAttributes("headers", respHeader.toString());
            builder.addAttributes("responseCode", connection.getResponseCode());
            builder.addAttributes("responseMessage", connection.getResponseMessage());
            DigitalObject digitalObject = new DigitalObject(doipMessage.header.parameters.id, DoType.DO);
            Element element = new Element(doipMessage.header.parameters.id, "bytes");
            element.setData(buff);
            digitalObject.addElements(element);
            Element error = new Element(doipMessage.header.parameters.id, "bytes");
            error.setData(errBuff);
            digitalObject.addElements(error);
            builder.setBody(digitalObject);
            return builder.create();
        } catch (NoRouteToHostException e) {
            LOGGER.error("----->" + urlStr2);
            builder.createResponse(DoipResponseCode.Declined, doipMessage);
            builder.setBody(e.getMessage().getBytes(StandardCharsets.UTF_8));
            return builder.create();
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("=======>" + urlStr2);
            builder.createResponse(DoipResponseCode.Declined, doipMessage);
            builder.setBody(e.getMessage().getBytes(StandardCharsets.UTF_8));
            return builder.create();
        }
    }

    private byte[] loadAllBytesAndClose(InputStream inputStream) {
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        try {
            byte[] buff = new byte[1024];
            for (int l = 0; (l = inputStream.read(buff)) > 0; ) {
                bo.write(buff, 0, l);
            }
            inputStream.close();
        } catch (Exception e) {
            //silently
        }
        return bo.toByteArray();
    }

    private JsonObject loadHeader(HttpURLConnection connection) {
        JsonObject jo = new JsonObject();
        try {
            for (String key : connection.getHeaderFields().keySet()) {
                jo.addProperty(key, connection.getHeaderField(key));
            }
        } catch (Exception e) {
        }
        return jo;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy