Search in sources :

Example 91 with JsonProcessingException

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonProcessingException in project incubator-pulsar by apache.

the class DiscoveryServiceWebTest method testTlsEnable.

@Test
public void testTlsEnable() throws Exception {
    // 1. start server with tls enable
    int port = nextFreePort();
    int tlsPort = nextFreePort();
    ServiceConfig config = new ServiceConfig();
    config.setWebServicePort(port);
    config.setWebServicePortTls(tlsPort);
    config.setTlsEnabled(true);
    config.setTlsCertificateFilePath(TLS_SERVER_CERT_FILE_PATH);
    config.setTlsKeyFilePath(TLS_SERVER_KEY_FILE_PATH);
    ServerManager server = new ServerManager(config);
    DiscoveryZooKeeperClientFactoryImpl.zk = mockZookKeeper;
    Map<String, String> params = new TreeMap<>();
    params.put("zookeeperServers", "dummy-value");
    params.put("zookeeperClientFactoryClass", DiscoveryZooKeeperClientFactoryImpl.class.getName());
    server.addServlet("/", DiscoveryServiceServlet.class, params);
    server.start();
    // 2. get ZookeeperCacheLoader to add more brokers
    final String redirect_broker_host = "broker-1";
    List<String> brokers = Lists.newArrayList(redirect_broker_host);
    brokers.stream().forEach(b -> {
        try {
            final String brokerUrl = b + ":" + port;
            final String brokerUrlTls = b + ":" + tlsPort;
            LoadReport report = new LoadReport("http://" + brokerUrl, "https://" + brokerUrlTls, null, null);
            String reportData = ObjectMapperFactory.getThreadLocal().writeValueAsString(report);
            ZkUtils.createFullPathOptimistic(mockZookKeeper, LOADBALANCE_BROKERS_ROOT + "/" + brokerUrl, reportData.getBytes(ZookeeperClientFactoryImpl.ENCODING_SCHEME), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        } catch (KeeperException.NodeExistsException ne) {
        // Ok
        } catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
            fail("failed while creating broker znodes");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            fail("failed while creating broker znodes");
        }
    });
    // 3. https request with tls enable at server side
    String serviceUrl = String.format("https://localhost:%s/", tlsPort);
    String requestUrl = serviceUrl + "admin/namespaces/p1/c1/n1";
    KeyManager[] keyManagers = null;
    TrustManager[] trustManagers = InsecureTrustManagerFactory.INSTANCE.getTrustManagers();
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(keyManagers, trustManagers, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sslCtx.getSocketFactory());
    try {
        InputStream response = new URL(requestUrl).openStream();
        fail("it should give unknown host exception as: discovery service redirects request to: " + redirect_broker_host);
    } catch (Exception e) {
        // 4. Verify: server accepts https request and redirected to one of the available broker host defined into
        // zk. and as broker-service is not up: it should give "UnknownHostException with host=broker-url"
        String host = e.getLocalizedMessage();
        assertEquals(e.getClass(), UnknownHostException.class);
        assertTrue(host.startsWith(redirect_broker_host));
    }
    server.stop();
}
Also used : ServerManager(org.apache.pulsar.discovery.service.server.ServerManager) UnknownHostException(java.net.UnknownHostException) InputStream(java.io.InputStream) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) TreeMap(java.util.TreeMap) URL(java.net.URL) KeeperException(org.apache.zookeeper.KeeperException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) UnknownHostException(java.net.UnknownHostException) TrustManager(javax.net.ssl.TrustManager) ServiceConfig(org.apache.pulsar.discovery.service.server.ServiceConfig) LoadReport(org.apache.pulsar.policies.data.loadbalancer.LoadReport) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) KeyManager(javax.net.ssl.KeyManager) KeeperException(org.apache.zookeeper.KeeperException) Test(org.testng.annotations.Test)

Example 92 with JsonProcessingException

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonProcessingException in project nakadi by zalando.

the class EventTypeDbRepository method saveEventType.

@Override
@Transactional
public EventType saveEventType(final EventTypeBase eventTypeBase) throws InternalNakadiException, DuplicatedEventTypeNameException {
    try {
        final DateTime now = new DateTime(DateTimeZone.UTC);
        final EventType eventType = new EventType(eventTypeBase, "1.0.0", now, now);
        jdbcTemplate.update("INSERT INTO zn_data.event_type (et_name, et_event_type_object) VALUES (?, ?::jsonb)", eventTypeBase.getName(), jsonMapper.writer().writeValueAsString(eventType));
        insertEventTypeSchema(eventType);
        return eventType;
    } catch (final JsonProcessingException e) {
        throw new InternalNakadiException("Serialization problem during persistence of event type", e);
    } catch (final DuplicateKeyException e) {
        throw new DuplicatedEventTypeNameException("EventType " + eventTypeBase.getName() + " already exists.", e);
    }
}
Also used : InternalNakadiException(org.zalando.nakadi.exceptions.InternalNakadiException) DuplicatedEventTypeNameException(org.zalando.nakadi.exceptions.DuplicatedEventTypeNameException) EventType(org.zalando.nakadi.domain.EventType) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) DateTime(org.joda.time.DateTime) DuplicateKeyException(org.springframework.dao.DuplicateKeyException) Transactional(org.springframework.transaction.annotation.Transactional)

Example 93 with JsonProcessingException

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonProcessingException in project vind by RBMHTechnology.

the class JsonReportWriter method write.

@Override
public boolean write(Report report, String reportFile) {
    try {
        final File file = new File(reportFile);
        mapper.writeValue(file, report);
        return true;
    } catch (JsonProcessingException e) {
        log.error("Error writing report as Json string: {}", e.getMessage(), e);
        return false;
    } catch (IOException e) {
        log.error("Error writing report to file '{}': {}", reportFile, e.getMessage(), e);
        return false;
    }
}
Also used : IOException(java.io.IOException) File(java.io.File) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 94 with JsonProcessingException

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonProcessingException in project candlepin by candlepin.

the class EventBuilder method setEventData.

/**
 * This method is used with any type of event and any target entity.
 * <p>
 * Note: For {@link Type#MODIFIED} events, it can be called twice consecutively
 * to first pass in the original, and then the updated entity. Alternatively,
 * {@link #setEventData(Eventful, Eventful)} can be used in the same use case.
 * </p>
 * @param entity The target entity of the Event
 * @return The builder object
 */
public EventBuilder setEventData(Eventful entity) {
    if (entity != null) {
        // Be careful to check for null before setting so we don't overwrite anything useful
        if (entity instanceof Named && ((Named) entity).getName() != null) {
            event.setTargetName(((Named) entity).getName());
        }
        if (entity instanceof Owned) {
            String ownerId = ((Owned) entity).getOwnerId();
            if (ownerId != null) {
                event.setOwnerId(ownerId);
            }
        }
        if (entity instanceof Entitlement) {
            event.setReferenceType(Event.ReferenceType.POOL);
            Pool referencedPool = ((Entitlement) entity).getPool();
            if (referencedPool != null && referencedPool.getId() != null) {
                event.setReferenceId(referencedPool.getId());
            }
        }
        if (entity.getId() != null) {
            event.setEntityId((String) entity.getId());
            if (entity instanceof ConsumerProperty) {
                Consumer owningConsumer = ((ConsumerProperty) entity).getConsumer();
                if (owningConsumer != null && owningConsumer.getUuid() != null) {
                    event.setConsumerUuid(owningConsumer.getUuid());
                }
            }
        }
        if (event.getTarget().equals(Target.POOL) && event.getType().equals(Type.CREATED)) {
            Map<String, String> eventData = new HashMap<>();
            eventData.put("subscriptionId", ((Pool) entity).getSubscriptionId());
            try {
                event.setEventData(mapper.writeValueAsString(eventData));
            } catch (JsonProcessingException e) {
                log.error("Error while building JSON for pool.created event.", e);
                throw new IseException("Error while building JSON for pool.created event.");
            }
        }
    }
    return this;
}
Also used : Named(org.candlepin.model.Named) Owned(org.candlepin.model.Owned) Consumer(org.candlepin.model.Consumer) IseException(org.candlepin.common.exceptions.IseException) HashMap(java.util.HashMap) Pool(org.candlepin.model.Pool) Entitlement(org.candlepin.model.Entitlement) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ConsumerProperty(org.candlepin.model.ConsumerProperty)

Example 95 with JsonProcessingException

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonProcessingException in project jackson-core by FasterXML.

the class GeneratorFailFromReaderTest method _testFailOnWritingStringNotFieldName.

/*
    /**********************************************************
    /* Internal methods
    /**********************************************************
     */
private void _testFailOnWritingStringNotFieldName(JsonFactory f, boolean useReader) throws Exception {
    JsonGenerator gen;
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    if (useReader) {
        gen = f.createGenerator(ObjectWriteContext.empty(), new OutputStreamWriter(bout, "UTF-8"));
    } else {
        gen = f.createGenerator(ObjectWriteContext.empty(), bout, JsonEncoding.UTF8);
    }
    gen.writeStartObject();
    try {
        StringReader reader = new StringReader("a");
        gen.writeString(reader, -1);
        gen.flush();
        String json = bout.toString("UTF-8");
        fail("Should not have let " + gen.getClass().getName() + ".writeString() be used in place of 'writeFieldName()': output = " + json);
    } catch (JsonProcessingException e) {
        verifyException(e, "can not write a String");
    }
    gen.close();
}
Also used : StringReader(java.io.StringReader) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) OutputStreamWriter(java.io.OutputStreamWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Aggregations

JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)741 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)241 IOException (java.io.IOException)174 HashMap (java.util.HashMap)108 Map (java.util.Map)83 ArrayList (java.util.ArrayList)74 JsonNode (com.fasterxml.jackson.databind.JsonNode)73 Test (org.junit.Test)65 List (java.util.List)56 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)36 Collectors (java.util.stream.Collectors)30 InputStream (java.io.InputStream)26 Json (com.sequenceiq.cloudbreak.domain.json.Json)21 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)20 File (java.io.File)20 Function (java.util.function.Function)20 Logger (org.slf4j.Logger)20 Optional (java.util.Optional)19 Date (java.util.Date)18 Test (org.testng.annotations.Test)18