Search in sources :

Example 1 with Metadata

use of org.folio.rest.jaxrs.model.Metadata in project raml-module-builder by folio-org.

the class RestVerticle method populateMetaData.

private void populateMetaData(Object entity, Map<String, String> okapiHeaders, String path) {
    // try to populate meta data section of the passed in json (converted to pojo already as this stage)
    // will only succeed if the pojo (json schema) has a reference to the metaData schema.
    // there should not be a metadata schema declared in the json schema unless it is the OOTB meta data schema
    // the created date and by fields are stored in the db in separate columns on insert trigger so that even if
    // we overwrite them here, the correct value will be set in the db level via a trigger on update
    String json;
    try {
        String userId = okapiHeaders.get(OKAPI_USERID_HEADER);
        if (userId == null) {
            String token = okapiHeaders.get(OKAPI_HEADER_TOKEN);
            String[] split = token.split("\\.");
            // the split array contains the 3 parts of the token - the body is the middle part
            json = JwtUtils.getJson(split[1]);
            JsonObject j = new JsonObject(json);
            userId = j.getString("user_id");
        }
        if (userId != null) {
            Metadata md = new Metadata();
            md.setUpdatedDate(new Date());
            md.setCreatedDate(new Date());
            md.setCreatedByUserId(userId);
            md.setUpdatedByUserId(userId);
            try {
                /* if a metadata section is passed in by client, we cannot assume it is correct.
           * entity.getClass().getMethod("getMetaData",
          new Class[] { }).invoke(entity);*/
                entity.getClass().getMethod("setMetadata", new Class[] { Metadata.class }).invoke(entity, md);
            } catch (Exception e) {
                // do nothing - if this is thrown then the setMetaData() failed, assume pojo
                // (aka) json schema - didnt include a reference to it.
                log.debug(e.getMessage(), e);
            }
        }
    } catch (Exception e) {
        log.warn("Problem parsing " + OKAPI_HEADER_TOKEN + " header, for path " + path + " - " + e.getMessage());
    }
}
Also used : Metadata(org.folio.rest.jaxrs.model.Metadata) JsonObject(io.vertx.core.json.JsonObject) Date(java.util.Date) UnrecognizedPropertyException(com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException)

Example 2 with Metadata

use of org.folio.rest.jaxrs.model.Metadata in project raml-module-builder by folio-org.

the class DemoRamlRestTest method postData.

/**
 * for POST
 */
private void postData(TestContext context, String url, Buffer buffer, int errorCode, int mode, String contenttype, String tenant, boolean userIdHeader) {
    // save stacktrace for async handler
    Exception stacktrace = new RuntimeException();
    Async async = context.async();
    HttpClient client = vertx.createHttpClient();
    HttpClientRequest request = null;
    if (mode == 0) {
        request = client.putAbs(url);
    } else if (mode == 1) {
        request = client.postAbs(url);
    } else {
        request = client.deleteAbs(url);
    }
    request.exceptionHandler(error -> {
        async.complete();
        context.fail(new RuntimeException(error.getMessage(), stacktrace));
    }).handler(response -> {
        int statusCode = response.statusCode();
        // is it 2XX
        log.info(statusCode + ", " + errorCode + " expected status at " + System.currentTimeMillis() + " mode " + mode + " for " + url);
        if (statusCode == errorCode) {
            if (statusCode == 422) {
                String str = response.getHeader("Content-type");
                if (str != null && str.contains("application/json")) {
                    context.assertTrue(true);
                } else {
                    context.fail(new RuntimeException("422 response code should contain a content type header of application/json", stacktrace));
                }
            } else if (statusCode == 201) {
                response.bodyHandler(responseData -> {
                    String date = (String) new JsonPathParser(responseData.toJsonObject()).getValueAt("metadata.createdDate");
                    if (date == null && userIdHeader) {
                        context.fail(new RuntimeException("metaData schema createdDate missing from returned json", stacktrace));
                    }
                });
            }
            context.assertTrue(true);
        } else {
            response.bodyHandler(responseData -> {
                context.fail(new RuntimeException("got unexpected response code, expected: " + errorCode + ", received code: " + statusCode + " mode " + mode + " for url " + url + "\ndata:" + responseData.toString(), stacktrace));
            });
        }
        if (!async.isCompleted()) {
            async.complete();
        }
    });
    request.setChunked(true);
    request.putHeader("X-Okapi-Request-Id", "999999999999");
    if (tenant != null) {
        request.putHeader("x-okapi-tenant", tenant);
    }
    request.putHeader("Accept", "application/json,text/plain");
    if (userIdHeader) {
        request.putHeader("X-Okapi-User-Id", "af23adf0-61ba-4887-bf82-956c4aae2260");
    }
    if (contenttype != null) {
        request.putHeader("Content-type", contenttype);
    } else {
        if (mode == 0 || mode == 2) {
            request.putHeader("Content-type", "application/json");
        } else {
            request.putHeader("Content-type", "multipart/form-data; boundary=MyBoundary");
        }
    }
    if (buffer != null) {
        request.write(buffer);
    }
    request.end();
}
Also used : TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) RestVerticle(org.folio.rest.RestVerticle) BeforeClass(org.junit.BeforeClass) AES(org.folio.rest.security.AES) Date(java.util.Date) MimeBodyPart(javax.mail.internet.MimeBodyPart) RunWith(org.junit.runner.RunWith) SimpleDateFormat(java.text.SimpleDateFormat) VertxUtils(org.folio.rest.tools.utils.VertxUtils) LoggerFactory(io.vertx.core.logging.LoggerFactory) ArrayList(java.util.ArrayList) BodyPart(javax.mail.BodyPart) BigDecimal(java.math.BigDecimal) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientResponse(io.vertx.core.http.HttpClientResponse) Locale(java.util.Locale) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) JsonObject(io.vertx.core.json.JsonObject) Datetime(org.folio.rest.jaxrs.model.Datetime) Metadata(org.folio.rest.jaxrs.model.Metadata) Logger(io.vertx.core.logging.Logger) MimeMultipart(javax.mail.internet.MimeMultipart) AfterClass(org.junit.AfterClass) RmbtestsClient(org.folio.rest.client.RmbtestsClient) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Vertx(io.vertx.core.Vertx) IOException(java.io.IOException) Test(org.junit.Test) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) JsonPathParser(org.folio.rest.tools.parser.JsonPathParser) Data(org.folio.rest.jaxrs.model.Data) File(java.io.File) NetworkUtils(org.folio.rest.tools.utils.NetworkUtils) Book(org.folio.rest.jaxrs.model.Book) IOUtils(org.apache.commons.io.IOUtils) Messages(org.folio.rest.tools.messages.Messages) List(java.util.List) InternetHeaders(javax.mail.internet.InternetHeaders) Buffer(io.vertx.core.buffer.Buffer) DeploymentOptions(io.vertx.core.DeploymentOptions) AdminClient(org.folio.rest.client.AdminClient) HttpMethod(io.vertx.core.http.HttpMethod) SecretKey(javax.crypto.SecretKey) PersistMethod(org.folio.rest.jaxrs.resource.AdminResource.PersistMethod) Handler(io.vertx.core.Handler) HttpClient(io.vertx.core.http.HttpClient) HttpClientRequest(io.vertx.core.http.HttpClientRequest) Async(io.vertx.ext.unit.Async) HttpClient(io.vertx.core.http.HttpClient) JsonPathParser(org.folio.rest.tools.parser.JsonPathParser) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 3 with Metadata

use of org.folio.rest.jaxrs.model.Metadata in project raml-module-builder by folio-org.

the class MetadataUtil method createMetadata.

/**
 * @return Metadata where createdDate and updatedDate are set to current time and
 * createdByUserId and updatedByUserId are set to the
 * {@link RestVerticle.OKAPI_USERID_HEADER} header, using {@code user_id} from the
 * {@link RestVerticle.OKAPI_HEADER_TOKEN} as a fall-back. The token is used without
 * validation.
 */
public static Metadata createMetadata(Map<String, String> okapiHeaders) {
    String userId = okapiHeaders.get(RestVerticle.OKAPI_USERID_HEADER);
    if (userId == null) {
        try {
            userId = new OkapiToken(okapiHeaders.get(RestVerticle.OKAPI_HEADER_TOKEN)).getUserIdWithoutValidation();
        } catch (Exception e) {
        // ignore, userId remains null
        }
    }
    Metadata md = new Metadata();
    md.setUpdatedDate(new Date());
    md.setCreatedDate(md.getUpdatedDate());
    md.setCreatedByUserId(userId);
    md.setUpdatedByUserId(userId);
    return md;
}
Also used : Metadata(org.folio.rest.jaxrs.model.Metadata) OkapiToken(org.folio.okapi.common.OkapiToken) Date(java.util.Date)

Example 4 with Metadata

use of org.folio.rest.jaxrs.model.Metadata in project raml-module-builder by folio-org.

the class MetadataUtilTest method createMetadataFromToken.

@Test
void createMetadataFromToken() {
    Metadata metadata = MetadataUtil.createMetadata(headers(RestVerticle.OKAPI_HEADER_TOKEN, token));
    assertThat(metadata.getCreatedByUserId(), is("bar"));
    assertThat(metadata.getUpdatedByUserId(), is("bar"));
    assertNow(metadata.getCreatedDate());
    assertNow(metadata.getUpdatedDate());
}
Also used : Metadata(org.folio.rest.jaxrs.model.Metadata) Test(org.junit.jupiter.api.Test)

Example 5 with Metadata

use of org.folio.rest.jaxrs.model.Metadata in project raml-module-builder by folio-org.

the class MetadataUtilTest method createMetadataFromUserId.

@Test
void createMetadataFromUserId() {
    Metadata metadata = MetadataUtil.createMetadata(headers(RestVerticle.OKAPI_HEADER_TOKEN, token, RestVerticle.OKAPI_USERID_HEADER, "foo"));
    assertThat(metadata.getCreatedByUserId(), is("foo"));
    assertThat(metadata.getUpdatedByUserId(), is("foo"));
    assertNow(metadata.getCreatedDate());
    assertNow(metadata.getUpdatedDate());
}
Also used : Metadata(org.folio.rest.jaxrs.model.Metadata) Test(org.junit.jupiter.api.Test)

Aggregations

Metadata (org.folio.rest.jaxrs.model.Metadata)8 Date (java.util.Date)4 JsonObject (io.vertx.core.json.JsonObject)3 Test (org.junit.jupiter.api.Test)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 IOException (java.io.IOException)2 Book (org.folio.rest.jaxrs.model.Book)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 UnrecognizedPropertyException (com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException)1 DeploymentOptions (io.vertx.core.DeploymentOptions)1 Handler (io.vertx.core.Handler)1 Vertx (io.vertx.core.Vertx)1 Buffer (io.vertx.core.buffer.Buffer)1 HttpClient (io.vertx.core.http.HttpClient)1 HttpClientRequest (io.vertx.core.http.HttpClientRequest)1 HttpClientResponse (io.vertx.core.http.HttpClientResponse)1 HttpMethod (io.vertx.core.http.HttpMethod)1 Logger (io.vertx.core.logging.Logger)1 LoggerFactory (io.vertx.core.logging.LoggerFactory)1 Async (io.vertx.ext.unit.Async)1