Search in sources :

Example 16 with HTTPException

use of net.geoprism.dhis2.dhis2adapter.exception.HTTPException in project geoprism-registry by terraframe.

the class DHIS2SynchronizationManager method exportGeoObject.

/**
 * It's important that we try our best to maintain an accurate state between
 * our database and the DHIS2 database. The DHIS2Serailizer will create new
 * ids and save them as externalIds for GeoObjects that do not have
 * externalIds. If our push to DHIS2 for this new GeoObject fails for whatever
 * reason, then we want to rollback our database so that we do not store the
 * id which does not exist in the DHIS2 database.
 *
 * TODO : In the future perhaps we should directly ask DHIS2 if an object
 * exists and then we'll know
 *
 * @param level
 * @param go
 * @return
 * @throws ExportError
 */
@Transaction
private void exportGeoObject(DHIS2SyncConfig dhis2Config, DHIS2SyncLevel level, SortedSet<DHIS2SyncLevel> levels, Long rowIndex, VertexServerGeoObject serverGo, Boolean includeTranslations) throws DHIS2SyncError {
    DHIS2ImportResponse resp = null;
    JsonObject orgUnitJsonTree = null;
    String orgUnitJson = null;
    String externalId = null;
    try {
        externalId = serverGo.getExternalId(dhis2Config.getSystem());
        boolean isNew = (externalId == null);
        if (isNew && level.getSyncType() != DHIS2SyncLevel.Type.ALL) {
            NewGeoObjectInvalidSyncTypeError err = new NewGeoObjectInvalidSyncTypeError();
            err.setGeoObject(serverGo.getDisplayLabel().getValue());
            throw err;
        }
        if (isNew && level.getLevel() == 0 && this.ouLevel1.size() > 0) {
            throw new MultipleLevelOneOrgUnitException();
        }
        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(VertexServerGeoObject.class, new DHIS2GeoObjectJsonAdapters.DHIS2Serializer(dhis2, dhis2Config, level, this.date));
        orgUnitJsonTree = builder.create().toJsonTree(serverGo, serverGo.getClass()).getAsJsonObject();
        orgUnitJson = orgUnitJsonTree.toString();
        externalId = serverGo.getExternalId(dhis2Config.getSystem());
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("mergeMode", "MERGE"));
        try {
            JsonObject metadataPayload = new JsonObject();
            JsonArray orgUnits = new JsonArray();
            metadataPayload.add("organisationUnits", orgUnits);
            if (level.getSyncType() == DHIS2SyncLevel.Type.ALL) {
                orgUnits.add(orgUnitJsonTree);
            } else if (level.getSyncType() == DHIS2SyncLevel.Type.RELATIONSHIPS) {
                if (!orgUnitJsonTree.has("parent")) {
                    // Root level types do not have parents.
                    return;
                }
                JsonObject orgUnitRelationships = new JsonObject();
                // These attributes must be included at the requirement of DHIS2 API
                orgUnitRelationships.addProperty("id", orgUnitJsonTree.get("id").getAsString());
                orgUnitRelationships.addProperty("name", orgUnitJsonTree.get("name").getAsString());
                orgUnitRelationships.addProperty("shortName", orgUnitJsonTree.get("shortName").getAsString());
                orgUnitRelationships.addProperty("openingDate", orgUnitJsonTree.get("openingDate").getAsString());
                // We don't want to actually update any of these attributes, so if we can fetch the object from DHIS2
                // then use the values they have in their server instead.
                DHIS2Response orgUnitGetResp = dhis2.entityIdGet(DHIS2Objects.ORGANISATION_UNITS, externalId, params);
                if (orgUnitGetResp.isSuccess()) {
                    JsonObject jo = JsonParser.parseString(orgUnitGetResp.getResponse()).getAsJsonObject();
                    orgUnitRelationships.addProperty("name", jo.get("name").getAsString());
                    orgUnitRelationships.addProperty("shortName", jo.get("shortName").getAsString());
                    orgUnitRelationships.addProperty("openingDate", jo.get("openingDate").getAsString());
                }
                // These attributes are the ones we need to include to change the relationship
                orgUnitRelationships.add("parent", orgUnitJsonTree.get("parent").getAsJsonObject());
                orgUnitRelationships.addProperty("path", orgUnitJsonTree.get("path").getAsString());
                orgUnitRelationships.addProperty("level", orgUnitJsonTree.get("level").getAsInt());
                orgUnits.add(orgUnitRelationships);
            } else if (level.getSyncType() == DHIS2SyncLevel.Type.ORG_UNITS) {
                JsonObject orgUnitAttributes = orgUnitJsonTree.deepCopy();
                // Drop all attributes related to the parent / hierarchy
                orgUnitAttributes.remove("parent");
                orgUnitAttributes.remove("path");
                orgUnitAttributes.remove("level");
                orgUnits.add(orgUnitAttributes);
            }
            ImportStrategy strategy = isNew ? ImportStrategy.CREATE : ImportStrategy.UPDATE;
            params.add(new BasicNameValuePair("importStrategy", strategy.name()));
            resp = dhis2.metadataPost(params, new StringEntity(metadataPayload.toString(), Charset.forName("UTF-8")));
        } catch (InvalidLoginException e) {
            LoginException cgrlogin = new LoginException(e);
            throw cgrlogin;
        } catch (HTTPException e) {
            HttpError cgrhttp = new HttpError(e);
            throw cgrhttp;
        }
        this.service.validateDhis2Response(resp);
        if (isNew && level.getLevel() == 1 && this.ouLevel1.size() > 0) {
            this.ouLevel1.add(new OrganisationUnit());
        }
    } catch (Throwable t) {
        DHIS2SyncError er = new DHIS2SyncError(rowIndex, resp, orgUnitJson, t, serverGo.getCode());
        throw er;
    }
}
Also used : MultipleLevelOneOrgUnitException(net.geoprism.registry.etl.export.dhis2.MultipleLevelOneOrgUnitException) DHIS2GeoObjectJsonAdapters(net.geoprism.registry.etl.export.dhis2.DHIS2GeoObjectJsonAdapters) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) OrganisationUnit(net.geoprism.dhis2.dhis2adapter.response.model.OrganisationUnit) HTTPException(net.geoprism.dhis2.dhis2adapter.exception.HTTPException) GsonBuilder(com.google.gson.GsonBuilder) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) DHIS2SyncError(net.geoprism.registry.dhis2.DHIS2FeatureService.DHIS2SyncError) JsonArray(com.google.gson.JsonArray) StringEntity(org.apache.http.entity.StringEntity) ImportStrategy(net.geoprism.dhis2.dhis2adapter.response.model.ImportStrategy) NewGeoObjectInvalidSyncTypeError(net.geoprism.registry.etl.NewGeoObjectInvalidSyncTypeError) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) InvalidLoginException(net.geoprism.dhis2.dhis2adapter.exception.InvalidLoginException) LoginException(net.geoprism.registry.etl.export.LoginException) InvalidLoginException(net.geoprism.dhis2.dhis2adapter.exception.InvalidLoginException) DHIS2ImportResponse(net.geoprism.dhis2.dhis2adapter.response.DHIS2ImportResponse) HttpError(net.geoprism.registry.etl.export.HttpError) DHIS2Response(net.geoprism.dhis2.dhis2adapter.response.DHIS2Response) Transaction(com.runwaysdk.dataaccess.transaction.Transaction)

Example 17 with HTTPException

use of net.geoprism.dhis2.dhis2adapter.exception.HTTPException in project geoprism-registry by terraframe.

the class SynchronizationConfigService method getConfigForExternalSystem.

@Request(RequestType.SESSION)
public JsonObject getConfigForExternalSystem(String sessionId, String externalSystemId, String hierarchyTypeCode) {
    JsonObject ret = new JsonObject();
    // Add GeoObjectTypes
    GeoObjectType[] gots = ServiceFactory.getRegistryService().getGeoObjectTypes(sessionId, null, new String[] { hierarchyTypeCode }, PermissionContext.WRITE);
    CustomSerializer serializer = ServiceFactory.getRegistryService().serializer(sessionId);
    JsonArray jarray = new JsonArray();
    for (int i = 0; i < gots.length; ++i) {
        jarray.add(gots[i].toJSON(serializer));
    }
    ret.add("types", jarray);
    // Add DHIS2 OrgUnitGroups
    DHIS2ExternalSystem system = DHIS2ExternalSystem.get(externalSystemId);
    try {
        DHIS2TransportServiceIF dhis2 = DHIS2ServiceFactory.buildDhis2TransportService(system);
        JsonArray jaGroups = new JsonArray();
        MetadataGetResponse<OrganisationUnitGroup> resp = dhis2.<OrganisationUnitGroup>metadataGet(OrganisationUnitGroup.class);
        List<OrganisationUnitGroup> groups = resp.getObjects();
        for (OrganisationUnitGroup group : groups) {
            JsonObject joGroup = new JsonObject();
            joGroup.addProperty("id", group.getId());
            joGroup.addProperty("name", group.getName());
            jaGroups.add(joGroup);
        }
        ret.add("orgUnitGroups", jaGroups);
    } catch (InvalidLoginException e) {
        LoginException cgrlogin = new LoginException(e);
        throw cgrlogin;
    } catch (HTTPException | UnexpectedResponseException | IllegalArgumentException | BadServerUriException e) {
        HttpError cgrhttp = new HttpError(e);
        throw cgrhttp;
    }
    return ret;
}
Also used : DHIS2TransportServiceIF(net.geoprism.registry.etl.export.dhis2.DHIS2TransportServiceIF) HTTPException(net.geoprism.dhis2.dhis2adapter.exception.HTTPException) DHIS2ExternalSystem(net.geoprism.registry.graph.DHIS2ExternalSystem) JsonObject(com.google.gson.JsonObject) CustomSerializer(org.commongeoregistry.adapter.metadata.CustomSerializer) BadServerUriException(net.geoprism.dhis2.dhis2adapter.exception.BadServerUriException) JsonArray(com.google.gson.JsonArray) OrganisationUnitGroup(net.geoprism.dhis2.dhis2adapter.response.model.OrganisationUnitGroup) GeoObjectType(org.commongeoregistry.adapter.metadata.GeoObjectType) InvalidLoginException(net.geoprism.dhis2.dhis2adapter.exception.InvalidLoginException) LoginException(net.geoprism.registry.etl.export.LoginException) InvalidLoginException(net.geoprism.dhis2.dhis2adapter.exception.InvalidLoginException) UnexpectedResponseException(net.geoprism.dhis2.dhis2adapter.exception.UnexpectedResponseException) HttpError(net.geoprism.registry.etl.export.HttpError) Request(com.runwaysdk.session.Request)

Example 18 with HTTPException

use of net.geoprism.dhis2.dhis2adapter.exception.HTTPException in project geoprism-registry by terraframe.

the class DHIS2TestService method metadataGet.

@Override
public <T> MetadataGetResponse<T> metadataGet(Class<?> dhis2Type, List<NameValuePair> params) throws InvalidLoginException, HTTPException {
    String objectNamePlural = DHIS2Objects.getPluralObjectNameFromClass(dhis2Type);
    try {
        if (objectNamePlural.equals(DHIS2Objects.OPTIONS)) {
            InputStream data = Thread.currentThread().getContextClassLoader().getResourceAsStream("dhis2/2.31.9/options.json");
            String resp = IOUtils.toString(data, "UTF-8");
            return new MetadataGetResponse<T>(resp, 200, objectNamePlural, dhis2Type);
        } else if (objectNamePlural.equals(DHIS2Objects.OPTIONSETS)) {
            InputStream data = Thread.currentThread().getContextClassLoader().getResourceAsStream("dhis2/2.31.9/optionsets.json");
            String resp = IOUtils.toString(data, "UTF-8");
            return new MetadataGetResponse<T>(resp, 200, objectNamePlural, dhis2Type);
        } else if (objectNamePlural.equals(DHIS2Objects.ATTRIBUTES)) {
            InputStream data = Thread.currentThread().getContextClassLoader().getResourceAsStream("dhis2/2.31.9/attributes.json");
            String resp = IOUtils.toString(data, "UTF-8");
            return new MetadataGetResponse<T>(resp, 200, objectNamePlural, dhis2Type);
        } else if (objectNamePlural.equals(DHIS2Objects.ORGANISATION_UNIT_GROUPS)) {
            InputStream data = Thread.currentThread().getContextClassLoader().getResourceAsStream("dhis2/default/organisationUnitGroups.json");
            String resp = IOUtils.toString(data, "UTF-8");
            return new MetadataGetResponse<T>(resp, 200, objectNamePlural, dhis2Type);
        } else {
            JsonObject jo = new JsonObject();
            JsonObject system = new JsonObject();
            system.addProperty("id", "eed3d451-4ff5-4193-b951-ffcc68954299");
            system.addProperty("rev", "86fbbf7");
            system.addProperty("version", "2.31.9");
            system.addProperty("date", "2020-07-17T23:03:46.853");
            jo.add("system", system);
            jo.add(objectNamePlural, new JsonArray());
            return new MetadataGetResponse<T>(jo.toString(), 200, objectNamePlural, dhis2Type);
        }
    } catch (IOException e) {
        throw new ProgrammingErrorException(e);
    }
}
Also used : JsonArray(com.google.gson.JsonArray) InputStream(java.io.InputStream) JsonObject(com.google.gson.JsonObject) MetadataGetResponse(net.geoprism.dhis2.dhis2adapter.response.MetadataGetResponse) IOException(java.io.IOException) ProgrammingErrorException(com.runwaysdk.dataaccess.ProgrammingErrorException)

Aggregations

HTTPException (net.geoprism.dhis2.dhis2adapter.exception.HTTPException)13 JsonObject (com.google.gson.JsonObject)8 JsonArray (com.google.gson.JsonArray)7 InvalidLoginException (net.geoprism.dhis2.dhis2adapter.exception.InvalidLoginException)7 HttpError (net.geoprism.registry.etl.export.HttpError)7 LoginException (net.geoprism.registry.etl.export.LoginException)7 IOException (java.io.IOException)6 BadServerUriException (net.geoprism.dhis2.dhis2adapter.exception.BadServerUriException)6 NameValuePair (org.apache.http.NameValuePair)6 URISyntaxException (java.net.URISyntaxException)5 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)5 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)5 ArrayList (java.util.ArrayList)4 UnexpectedResponseException (net.geoprism.dhis2.dhis2adapter.exception.UnexpectedResponseException)4 DHIS2Response (net.geoprism.dhis2.dhis2adapter.response.DHIS2Response)4 ProgrammingErrorException (com.runwaysdk.dataaccess.ProgrammingErrorException)3 GsonBuilder (com.google.gson.GsonBuilder)2 Request (com.runwaysdk.session.Request)2 MetadataGetResponse (net.geoprism.dhis2.dhis2adapter.response.MetadataGetResponse)2 Attribute (net.geoprism.dhis2.dhis2adapter.response.model.Attribute)2