Search in sources :

Example 41 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project cas by apereo.

the class RestAuditTrailManager method getAuditRecordsSince.

@Override
public Set<AuditActionContext> getAuditRecordsSince(final LocalDate localDate) {
    try {
        LOGGER.debug("Sending query to audit REST endpoint to fetch records from [{}]", localDate);
        final HttpResponse response = HttpUtils.executeGet(properties.getUrl(), CollectionUtils.wrap("date", localDate.toEpochDay()));
        if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            final String result = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
            final TypeReference<Set<AuditActionContext>> values = new TypeReference<Set<AuditActionContext>>() {
            };
            return MAPPER.readValue(result, values);
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return new HashSet<>(0);
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) AuditActionContext(org.apereo.inspektr.audit.AuditActionContext) HttpResponse(org.apache.http.HttpResponse) TypeReference(com.fasterxml.jackson.core.type.TypeReference) HashSet(java.util.HashSet)

Example 42 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project blueocean-plugin by jenkinsci.

the class GithubServerContainer method create.

@CheckForNull
public ScmServerEndpoint create(@JsonBody JSONObject request) {
    List<ErrorMessage.Error> errors = Lists.newLinkedList();
    // Validate name
    final String name = (String) request.get(GithubServer.NAME);
    if (StringUtils.isEmpty(name)) {
        errors.add(new ErrorMessage.Error(GithubServer.NAME, ErrorMessage.Error.ErrorCodes.MISSING.toString(), GithubServer.NAME + " is required"));
    } else {
        GithubServer byName = findByName(name);
        if (byName != null) {
            errors.add(new ErrorMessage.Error(GithubServer.NAME, ErrorMessage.Error.ErrorCodes.ALREADY_EXISTS.toString(), GithubServer.NAME + " already exists for server at '" + byName.getApiUrl() + "'"));
        }
    }
    // Validate url
    final String url = (String) request.get(GithubServer.API_URL);
    if (StringUtils.isEmpty(url)) {
        errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.MISSING.toString(), GithubServer.API_URL + " is required"));
    } else {
        Endpoint byUrl = GitHubConfiguration.get().findEndpoint(url);
        if (byUrl != null) {
            errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.ALREADY_EXISTS.toString(), GithubServer.API_URL + " is already registered as '" + byUrl.getName() + "'"));
        }
    }
    if (StringUtils.isNotEmpty(url)) {
        // Validate that the URL represents a Github API endpoint
        try {
            HttpURLConnection connection = HttpRequest.get(url).connect();
            if (connection.getHeaderField("X-GitHub-Request-Id") == null) {
                errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.INVALID.toString(), ERROR_MESSAGE_INVALID_SERVER));
            } else {
                boolean isGithubCloud = false;
                boolean isGithubEnterprise = false;
                try {
                    InputStream inputStream;
                    int code = connection.getResponseCode();
                    if (200 <= code && code < 300) {
                        inputStream = HttpRequest.getInputStream(connection);
                    } else {
                        inputStream = HttpRequest.getErrorStream(connection);
                    }
                    TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
                    };
                    Map<String, String> responseBody = GithubScm.om.readValue(inputStream, typeRef);
                    isGithubCloud = code == 200 && responseBody.containsKey("current_user_url");
                    isGithubEnterprise = code == 401 && responseBody.containsKey("message");
                } catch (IOException ioe) {
                    LOGGER.log(Level.INFO, "Could not parse response body from Github");
                }
                if (!isGithubCloud && !isGithubEnterprise) {
                    errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.INVALID.toString(), ERROR_MESSAGE_INVALID_APIURL));
                }
            }
        } catch (Throwable e) {
            errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.INVALID.toString(), e.toString()));
            LOGGER.log(Level.INFO, "Could not connect to Github", e);
        }
    }
    if (errors.isEmpty()) {
        SecurityContext old = null;
        try {
            // We need to escalate privilege to add user defined endpoint to
            old = ACL.impersonate(ACL.SYSTEM);
            GitHubConfiguration config = GitHubConfiguration.get();
            String sanitizedUrl = discardQueryString(url);
            Endpoint endpoint = new Endpoint(sanitizedUrl, name);
            if (!config.addEndpoint(endpoint)) {
                errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.ALREADY_EXISTS.toString(), GithubServer.API_URL + " is already registered as '" + endpoint.getName() + "'"));
            } else {
                return new GithubServer(endpoint, getLink());
            }
        } finally {
            // reset back to original privilege level
            if (old != null) {
                SecurityContextHolder.setContext(old);
            }
        }
    }
    ErrorMessage message = new ErrorMessage(400, "Failed to create Github server");
    message.addAll(errors);
    throw new ServiceException.BadRequestException(message);
}
Also used : GitHubConfiguration(org.jenkinsci.plugins.github_branch_source.GitHubConfiguration) HashMap(java.util.HashMap) InputStream(java.io.InputStream) IOException(java.io.IOException) Endpoint(org.jenkinsci.plugins.github_branch_source.Endpoint) ScmServerEndpoint(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmServerEndpoint) HttpURLConnection(java.net.HttpURLConnection) Endpoint(org.jenkinsci.plugins.github_branch_source.Endpoint) ScmServerEndpoint(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmServerEndpoint) SecurityContext(org.acegisecurity.context.SecurityContext) JSONObject(net.sf.json.JSONObject) TypeReference(com.fasterxml.jackson.core.type.TypeReference) ErrorMessage(io.jenkins.blueocean.commons.ErrorMessage) CheckForNull(javax.annotation.CheckForNull)

Example 43 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project irontest by zheng-wang.

the class TeststepRunMapper method map.

public TeststepRun map(int index, ResultSet rs, StatementContext ctx) throws SQLException {
    TeststepRun teststepRun = new TeststepRun();
    ObjectMapper objectMapper = new ObjectMapper();
    teststepRun.setStartTime(rs.getTimestamp("starttime"));
    teststepRun.setDuration(rs.getLong("duration"));
    teststepRun.setResult(TestResult.getByText(rs.getString("result")));
    Teststep teststep = null;
    try {
        teststep = objectMapper.readValue(rs.getString("teststep"), Teststep.class);
    } catch (IOException e) {
        throw new SQLException("Failed to deserialize teststep JSON.", e);
    }
    teststepRun.setTeststep(teststep);
    // Use LinkedHashMap here instead of Object (for covering specific response type like DBAPIResponse),
    // because TeststepRun is used for displaying report, so JSON representation of the response is sufficient.
    LinkedHashMap response = null;
    try {
        response = objectMapper.readValue(rs.getString("response"), LinkedHashMap.class);
    } catch (IOException e) {
        throw new SQLException("Failed to deserialize response JSON.", e);
    }
    teststepRun.setResponse(response);
    teststepRun.setInfoMessage(rs.getString("info_message"));
    teststepRun.setErrorMessage(rs.getString("error_message"));
    List<AssertionVerification> assertionVerifications = null;
    try {
        assertionVerifications = new ObjectMapper().readValue(rs.getString("assertion_verifications"), new TypeReference<List<AssertionVerification>>() {
        });
    } catch (IOException e) {
        throw new SQLException("Failed to deserialize stepruns JSON.", e);
    }
    teststepRun.setAssertionVerifications(assertionVerifications);
    return teststepRun;
}
Also used : Teststep(io.irontest.models.teststep.Teststep) TeststepRun(io.irontest.models.testrun.TeststepRun) SQLException(java.sql.SQLException) IOException(java.io.IOException) AssertionVerification(io.irontest.models.assertion.AssertionVerification) TypeReference(com.fasterxml.jackson.core.type.TypeReference) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) LinkedHashMap(java.util.LinkedHashMap)

Example 44 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project hadoop by apache.

the class TestDataNodeMXBean method testDataNodeMXBeanBlockSize.

@Test
public void testDataNodeMXBeanBlockSize() throws Exception {
    Configuration conf = new Configuration();
    try (MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build()) {
        DataNode dn = cluster.getDataNodes().get(0);
        for (int i = 0; i < 100; i++) {
            DFSTestUtil.writeFile(cluster.getFileSystem(), new Path("/foo" + String.valueOf(i) + ".txt"), "test content");
        }
        DataNodeTestUtils.triggerBlockReport(dn);
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName mxbeanName = new ObjectName("Hadoop:service=DataNode,name=DataNodeInfo");
        String bpActorInfo = (String) mbs.getAttribute(mxbeanName, "BPServiceActorInfo");
        Assert.assertEquals(dn.getBPServiceActorInfo(), bpActorInfo);
        LOG.info("bpActorInfo is " + bpActorInfo);
        TypeReference<ArrayList<Map<String, String>>> typeRef = new TypeReference<ArrayList<Map<String, String>>>() {
        };
        ArrayList<Map<String, String>> bpActorInfoList = new ObjectMapper().readValue(bpActorInfo, typeRef);
        int maxDataLength = Integer.valueOf(bpActorInfoList.get(0).get("maxDataLength"));
        int confMaxDataLength = dn.getConf().getInt(CommonConfigurationKeys.IPC_MAXIMUM_DATA_LENGTH, CommonConfigurationKeys.IPC_MAXIMUM_DATA_LENGTH_DEFAULT);
        int maxBlockReportSize = Integer.valueOf(bpActorInfoList.get(0).get("maxBlockReportSize"));
        LOG.info("maxDataLength is " + maxDataLength);
        LOG.info("maxBlockReportSize is " + maxBlockReportSize);
        assertTrue("maxBlockReportSize should be greater than zero", maxBlockReportSize > 0);
        assertEquals("maxDataLength should be exactly " + "the same value of ipc.maximum.data.length", confMaxDataLength, maxDataLength);
    }
}
Also used : Path(org.apache.hadoop.fs.Path) MiniDFSCluster(org.apache.hadoop.hdfs.MiniDFSCluster) Configuration(org.apache.hadoop.conf.Configuration) ArrayList(java.util.ArrayList) ObjectName(javax.management.ObjectName) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Map(java.util.Map) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) MBeanServer(javax.management.MBeanServer) Test(org.junit.Test)

Example 45 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project riposte by Nike-Inc.

the class RequestContentDeserializerHandlerTest method doChannelRead_uses_TypeReference_from_endpoint_requestContentType_method.

@Test
public void doChannelRead_uses_TypeReference_from_endpoint_requestContentType_method() throws Exception {
    // given
    TypeReference<String> customTypeReference = new TypeReference<String>() {
    };
    doReturn(customTypeReference).when(endpointMock).requestContentType();
    // when
    PipelineContinuationBehavior result = handler.doChannelRead(ctxMock, msg);
    // then
    ArgumentCaptor<TypeReference> typeRefArgumentCaptor = ArgumentCaptor.forClass(TypeReference.class);
    verify(requestInfoSpy).setupContentDeserializer(eq(defaultHandlerDeserializerMock), typeRefArgumentCaptor.capture());
    TypeReference<String> actualTypeRef = typeRefArgumentCaptor.getValue();
    assertThat(actualTypeRef).isSameAs(customTypeReference);
    assertThat(actualTypeRef).isNotSameAs(contentTypeRef);
    assertThat(result).isEqualTo(PipelineContinuationBehavior.CONTINUE);
}
Also used : PipelineContinuationBehavior(com.nike.riposte.server.handler.base.PipelineContinuationBehavior) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Test(org.junit.Test)

Aggregations

TypeReference (com.fasterxml.jackson.core.type.TypeReference)87 IOException (java.io.IOException)34 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)31 Test (org.junit.Test)25 Map (java.util.Map)19 List (java.util.List)16 HashMap (java.util.HashMap)12 ArrayList (java.util.ArrayList)11 StringWriter (java.io.StringWriter)8 BaseMandrillAnonymousListResponse (com.cribbstechnologies.clients.mandrill.model.response.BaseMandrillAnonymousListResponse)7 ImmutableMap (com.google.common.collect.ImmutableMap)7 InputStream (java.io.InputStream)7 MalformedURLException (java.net.MalformedURLException)7 JsonNode (com.fasterxml.jackson.databind.JsonNode)5 Collectors (java.util.stream.Collectors)5 SimpleModule (com.fasterxml.jackson.databind.module.SimpleModule)4 AuditInfo (io.druid.audit.AuditInfo)4 PublicAccount (io.nem.sdk.model.account.PublicAccount)4 NetworkType (io.nem.sdk.model.blockchain.NetworkType)4 NamespaceId (io.nem.sdk.model.namespace.NamespaceId)4