Search in sources :

Example 96 with ObjectMapper

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper in project camel by apache.

the class LinkedInOAuthRequestFilter method getAccessToken.

private OAuthToken getAccessToken(String refreshToken) throws IOException {
    final String tokenUrl = String.format(ACCESS_TOKEN_URL, refreshToken, oAuthParams.getRedirectUri(), oAuthParams.getClientId(), oAuthParams.getClientSecret());
    final WebRequest webRequest = new WebRequest(new URL(tokenUrl), HttpMethod.POST);
    final WebResponse webResponse = webClient.loadWebResponse(webRequest);
    if (webResponse.getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException(String.format("Error getting access token: [%s: %s]", webResponse.getStatusCode(), webResponse.getStatusMessage()));
    }
    final long currentTime = System.currentTimeMillis();
    final ObjectMapper mapper = new ObjectMapper();
    final Map map = mapper.readValue(webResponse.getContentAsStream(), Map.class);
    final String accessToken = map.get("access_token").toString();
    final Integer expiresIn = Integer.valueOf(map.get("expires_in").toString());
    return new OAuthToken(refreshToken, accessToken, currentTime + TimeUnit.MILLISECONDS.convert(expiresIn, TimeUnit.SECONDS));
}
Also used : WebResponse(com.gargoylesoftware.htmlunit.WebResponse) WebRequest(com.gargoylesoftware.htmlunit.WebRequest) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map) URL(java.net.URL) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 97 with ObjectMapper

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper in project camel by apache.

the class MetricsMessageHistoryService method doStart.

@Override
protected void doStart() throws Exception {
    if (metricsRegistry == null) {
        Registry camelRegistry = getCamelContext().getRegistry();
        metricsRegistry = camelRegistry.lookupByNameAndType(MetricsComponent.METRIC_REGISTRY_NAME, MetricRegistry.class);
        // create a new metricsRegistry by default
        if (metricsRegistry == null) {
            metricsRegistry = new MetricRegistry();
        }
    }
    if (useJmx) {
        ManagementAgent agent = getCamelContext().getManagementStrategy().getManagementAgent();
        if (agent != null) {
            MBeanServer server = agent.getMBeanServer();
            if (server != null) {
                reporter = JmxReporter.forRegistry(metricsRegistry).registerWith(server).inDomain(jmxDomain).build();
                reporter.start();
            }
        } else {
            throw new IllegalStateException("CamelContext has not enabled JMX");
        }
    }
    // json mapper
    this.mapper = new ObjectMapper().registerModule(new MetricsModule(getRateUnit(), getDurationUnit(), false));
    if (getRateUnit() == TimeUnit.SECONDS && getDurationUnit() == TimeUnit.SECONDS) {
        // they both use same units so reuse
        this.secondsMapper = this.mapper;
    } else {
        this.secondsMapper = new ObjectMapper().registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.SECONDS, false));
    }
}
Also used : ManagementAgent(org.apache.camel.spi.ManagementAgent) MetricRegistry(com.codahale.metrics.MetricRegistry) MetricsModule(com.codahale.metrics.json.MetricsModule) MetricRegistry(com.codahale.metrics.MetricRegistry) Registry(org.apache.camel.spi.Registry) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) MBeanServer(javax.management.MBeanServer)

Example 98 with ObjectMapper

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper in project hadoop by apache.

the class DelegationTokenAuthenticationHandler method managementOperation.

@Override
@SuppressWarnings("unchecked")
public boolean managementOperation(AuthenticationToken token, HttpServletRequest request, HttpServletResponse response) throws IOException, AuthenticationException {
    boolean requestContinues = true;
    String op = ServletUtils.getParameter(request, KerberosDelegationTokenAuthenticator.OP_PARAM);
    op = (op != null) ? StringUtils.toUpperCase(op) : null;
    if (isManagementOperation(request)) {
        KerberosDelegationTokenAuthenticator.DelegationTokenOperation dtOp = KerberosDelegationTokenAuthenticator.DelegationTokenOperation.valueOf(op);
        if (dtOp.getHttpMethod().equals(request.getMethod())) {
            boolean doManagement;
            if (dtOp.requiresKerberosCredentials() && token == null) {
                // Don't authenticate via DT for DT ops.
                token = authHandler.authenticate(request, response);
                if (token == null) {
                    requestContinues = false;
                    doManagement = false;
                } else {
                    doManagement = true;
                }
            } else {
                doManagement = true;
            }
            if (doManagement) {
                UserGroupInformation requestUgi = (token != null) ? UserGroupInformation.createRemoteUser(token.getUserName()) : null;
                // Create the proxy user if doAsUser exists
                String doAsUser = DelegationTokenAuthenticationFilter.getDoAs(request);
                if (requestUgi != null && doAsUser != null) {
                    requestUgi = UserGroupInformation.createProxyUser(doAsUser, requestUgi);
                    try {
                        ProxyUsers.authorize(requestUgi, request.getRemoteAddr());
                    } catch (AuthorizationException ex) {
                        HttpExceptionUtils.createServletExceptionResponse(response, HttpServletResponse.SC_FORBIDDEN, ex);
                        return false;
                    }
                }
                Map map = null;
                switch(dtOp) {
                    case GETDELEGATIONTOKEN:
                        if (requestUgi == null) {
                            throw new IllegalStateException("request UGI cannot be NULL");
                        }
                        String renewer = ServletUtils.getParameter(request, KerberosDelegationTokenAuthenticator.RENEWER_PARAM);
                        try {
                            Token<?> dToken = tokenManager.createToken(requestUgi, renewer);
                            map = delegationTokenToJSON(dToken);
                        } catch (IOException ex) {
                            throw new AuthenticationException(ex.toString(), ex);
                        }
                        break;
                    case RENEWDELEGATIONTOKEN:
                        if (requestUgi == null) {
                            throw new IllegalStateException("request UGI cannot be NULL");
                        }
                        String tokenToRenew = ServletUtils.getParameter(request, KerberosDelegationTokenAuthenticator.TOKEN_PARAM);
                        if (tokenToRenew == null) {
                            response.sendError(HttpServletResponse.SC_BAD_REQUEST, MessageFormat.format("Operation [{0}] requires the parameter [{1}]", dtOp, KerberosDelegationTokenAuthenticator.TOKEN_PARAM));
                            requestContinues = false;
                        } else {
                            Token<AbstractDelegationTokenIdentifier> dt = new Token();
                            try {
                                dt.decodeFromUrlString(tokenToRenew);
                                long expirationTime = tokenManager.renewToken(dt, requestUgi.getShortUserName());
                                map = new HashMap();
                                map.put("long", expirationTime);
                            } catch (IOException ex) {
                                throw new AuthenticationException(ex.toString(), ex);
                            }
                        }
                        break;
                    case CANCELDELEGATIONTOKEN:
                        String tokenToCancel = ServletUtils.getParameter(request, KerberosDelegationTokenAuthenticator.TOKEN_PARAM);
                        if (tokenToCancel == null) {
                            response.sendError(HttpServletResponse.SC_BAD_REQUEST, MessageFormat.format("Operation [{0}] requires the parameter [{1}]", dtOp, KerberosDelegationTokenAuthenticator.TOKEN_PARAM));
                            requestContinues = false;
                        } else {
                            Token<AbstractDelegationTokenIdentifier> dt = new Token();
                            try {
                                dt.decodeFromUrlString(tokenToCancel);
                                tokenManager.cancelToken(dt, (requestUgi != null) ? requestUgi.getShortUserName() : null);
                            } catch (IOException ex) {
                                response.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid delegation token, cannot cancel");
                                requestContinues = false;
                            }
                        }
                        break;
                }
                if (requestContinues) {
                    response.setStatus(HttpServletResponse.SC_OK);
                    if (map != null) {
                        response.setContentType(MediaType.APPLICATION_JSON);
                        Writer writer = response.getWriter();
                        ObjectMapper jsonMapper = new ObjectMapper(jsonFactory);
                        jsonMapper.writeValue(writer, map);
                        writer.write(ENTER);
                        writer.flush();
                    }
                    requestContinues = false;
                }
            }
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, MessageFormat.format("Wrong HTTP method [{0}] for operation [{1}], it should be " + "[{2}]", request.getMethod(), dtOp, dtOp.getHttpMethod()));
            requestContinues = false;
        }
    }
    return requestContinues;
}
Also used : AuthorizationException(org.apache.hadoop.security.authorize.AuthorizationException) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) AuthenticationToken(org.apache.hadoop.security.authentication.server.AuthenticationToken) Token(org.apache.hadoop.security.token.Token) IOException(java.io.IOException) AbstractDelegationTokenIdentifier(org.apache.hadoop.security.token.delegation.AbstractDelegationTokenIdentifier) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Writer(java.io.Writer) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation)

Example 99 with ObjectMapper

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper in project hadoop by apache.

the class SlowPeerTracker method getJson.

/**
   * Retrieve all valid reports as a JSON string.
   * @return serialized representation of valid reports. null if
   *         serialization failed.
   */
public String getJson() {
    Collection<ReportForJson> validReports = getJsonReports(MAX_NODES_TO_REPORT);
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        return objectMapper.writeValueAsString(validReports);
    } catch (JsonProcessingException e) {
        // Failed to serialize. Don't log the exception call stack.
        LOG.debug("Failed to serialize statistics" + e);
        return null;
    }
}
Also used : JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 100 with ObjectMapper

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper in project hadoop by apache.

the class JHEventHandlerForSigtermTest method testCountersToJSONEmpty.

@Test(timeout = 50000)
public void testCountersToJSONEmpty() throws Exception {
    JobHistoryEventHandler jheh = new JobHistoryEventHandler(null, 0);
    Counters counters = null;
    JsonNode jsonNode = JobHistoryEventUtils.countersToJSON(counters);
    String jsonStr = new ObjectMapper().writeValueAsString(jsonNode);
    String expected = "[]";
    Assert.assertEquals(expected, jsonStr);
    counters = new Counters();
    jsonNode = JobHistoryEventUtils.countersToJSON(counters);
    jsonStr = new ObjectMapper().writeValueAsString(jsonNode);
    expected = "[]";
    Assert.assertEquals(expected, jsonStr);
    counters.addGroup("DOCTORS", "Incarnations of the Doctor");
    jsonNode = JobHistoryEventUtils.countersToJSON(counters);
    jsonStr = new ObjectMapper().writeValueAsString(jsonNode);
    expected = "[{\"NAME\":\"DOCTORS\",\"DISPLAY_NAME\":\"Incarnations of the " + "Doctor\",\"COUNTERS\":[]}]";
    Assert.assertEquals(expected, jsonStr);
}
Also used : Counters(org.apache.hadoop.mapreduce.Counters) JsonNode(com.fasterxml.jackson.databind.JsonNode) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Aggregations

ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)6071 Test (org.junit.Test)2235 IOException (java.io.IOException)1016 JsonNode (com.fasterxml.jackson.databind.JsonNode)930 HashMap (java.util.HashMap)444 Map (java.util.Map)429 ArrayList (java.util.ArrayList)416 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)388 File (java.io.File)319 List (java.util.List)268 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)254 Before (org.junit.Before)246 Test (org.junit.jupiter.api.Test)238 DefaultObjectMapper (org.apache.druid.jackson.DefaultObjectMapper)202 InputStream (java.io.InputStream)185 SimpleModule (com.fasterxml.jackson.databind.module.SimpleModule)156 Matchers.containsString (org.hamcrest.Matchers.containsString)136 DefaultObjectMapper (io.druid.jackson.DefaultObjectMapper)127 TypeReference (com.fasterxml.jackson.core.type.TypeReference)123 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)121