Search in sources :

Example 31 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project open-kilda by telstra.

the class PathVerificationService method handlePacketIn.

private IListener.Command handlePacketIn(IOFSwitch sw, OFPacketIn pkt, FloodlightContext context) {
    long time = System.currentTimeMillis();
    logger.debug("packet_in {} received from {}", pkt.getXid(), sw.getId());
    VerificationPacket verificationPacket = null;
    Ethernet eth = IFloodlightProviderService.bcStore.get(context, IFloodlightProviderService.CONTEXT_PI_PAYLOAD);
    try {
        verificationPacket = deserialize(eth);
    } catch (Exception exception) {
        logger.error("Deserialization failure: {}, exception: {}", exception.getMessage(), exception);
        return Command.CONTINUE;
    }
    try {
        OFPort inPort = pkt.getVersion().compareTo(OFVersion.OF_12) < 0 ? pkt.getInPort() : pkt.getMatch().get(MatchField.IN_PORT);
        ByteBuffer portBB = ByteBuffer.wrap(verificationPacket.getPortId().getValue());
        portBB.position(1);
        OFPort remotePort = OFPort.of(portBB.getShort());
        long timestamp = 0;
        int pathOrdinal = 10;
        IOFSwitch remoteSwitch = null;
        boolean signed = false;
        for (LLDPTLV lldptlv : verificationPacket.getOptionalTLVList()) {
            if (lldptlv.getType() == 127 && lldptlv.getLength() == 12 && lldptlv.getValue()[0] == 0x0 && lldptlv.getValue()[1] == 0x26 && lldptlv.getValue()[2] == (byte) 0xe1 && lldptlv.getValue()[3] == 0x0) {
                ByteBuffer dpidBB = ByteBuffer.wrap(lldptlv.getValue());
                remoteSwitch = switchService.getSwitch(DatapathId.of(dpidBB.getLong(4)));
            } else if (lldptlv.getType() == 127 && lldptlv.getLength() == 12 && lldptlv.getValue()[0] == 0x0 && lldptlv.getValue()[1] == 0x26 && lldptlv.getValue()[2] == (byte) 0xe1 && lldptlv.getValue()[3] == 0x01) {
                ByteBuffer tsBB = ByteBuffer.wrap(lldptlv.getValue());
                /* skip OpenFlow OUI (4 bytes above) */
                long swLatency = sw.getLatency().getValue();
                timestamp = tsBB.getLong(4);
                /* include the RX switch latency to "subtract" it */
                timestamp = timestamp + swLatency;
            } else if (lldptlv.getType() == 127 && lldptlv.getLength() == 8 && lldptlv.getValue()[0] == 0x0 && lldptlv.getValue()[1] == 0x26 && lldptlv.getValue()[2] == (byte) 0xe1 && lldptlv.getValue()[3] == 0x02) {
                ByteBuffer typeBB = ByteBuffer.wrap(lldptlv.getValue());
                pathOrdinal = typeBB.getInt(4);
            } else if (lldptlv.getType() == 127 && lldptlv.getValue()[0] == 0x0 && lldptlv.getValue()[1] == 0x26 && lldptlv.getValue()[2] == (byte) 0xe1 && lldptlv.getValue()[3] == 0x03) {
                ByteBuffer bb = ByteBuffer.wrap(lldptlv.getValue());
                bb.position(4);
                byte[] tokenArray = new byte[lldptlv.getLength() - 4];
                bb.get(tokenArray, 0, tokenArray.length);
                String token = new String(tokenArray);
                try {
                    DecodedJWT jwt = verifier.verify(token);
                    signed = true;
                } catch (JWTVerificationException e) {
                    logger.error("Packet verification failed", e);
                    return Command.STOP;
                }
            }
        }
        if (remoteSwitch == null) {
            return Command.STOP;
        }
        if (!signed) {
            logger.warn("verification packet without sign");
            return Command.STOP;
        }
        U64 latency = (timestamp != 0 && (time - timestamp) > 0) ? U64.of(time - timestamp) : U64.ZERO;
        logger.debug("link discovered: {}-{} ===( {} ms )===> {}-{}", remoteSwitch.getId(), remotePort, latency.getValue(), sw.getId(), inPort);
        // this verification packet was sent from remote switch/port to received switch/port
        // so the link direction is from remote switch/port to received switch/port
        List<PathNode> nodes = Arrays.asList(new PathNode(remoteSwitch.getId().toString(), remotePort.getPortNumber(), 0, latency.getValue()), new PathNode(sw.getId().toString(), inPort.getPortNumber(), 1));
        OFPortDesc port = sw.getPort(inPort);
        long speed = Integer.MAX_VALUE;
        if (port.getVersion().compareTo(OFVersion.OF_13) > 0) {
            for (OFPortDescProp prop : port.getProperties()) {
                if (prop.getType() == 0x0) {
                    speed = ((OFPortDescPropEthernet) prop).getCurrSpeed();
                }
            }
        } else {
            speed = port.getCurrSpeed();
        }
        IslInfoData path = new IslInfoData(latency.getValue(), nodes, speed, IslChangeType.DISCOVERED, getAvailableBandwidth(speed));
        Message message = new InfoMessage(path, System.currentTimeMillis(), "system", null);
        final String json = MAPPER.writeValueAsString(message);
        logger.debug("about to send {}", json);
        producer.send(new ProducerRecord<>(TOPIC, json));
        logger.debug("packet_in processed for {}-{}", sw.getId(), inPort);
    } catch (JsonProcessingException exception) {
        logger.error("could not create json for path packet_in: {}", exception.getMessage(), exception);
    } catch (UnsupportedOperationException exception) {
        logger.error("could not parse packet_in message: {}", exception.getMessage(), exception);
    } catch (Exception exception) {
        logger.error("unknown error during packet_in message processing: {}", exception.getMessage(), exception);
        throw exception;
    }
    return Command.STOP;
}
Also used : IOFSwitch(net.floodlightcontroller.core.IOFSwitch) InfoMessage(org.openkilda.messaging.info.InfoMessage) OFMessage(org.projectfloodlight.openflow.protocol.OFMessage) Message(org.openkilda.messaging.Message) OFPortDescProp(org.projectfloodlight.openflow.protocol.OFPortDescProp) PathNode(org.openkilda.messaging.info.event.PathNode) ByteBuffer(java.nio.ByteBuffer) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) FloodlightModuleException(net.floodlightcontroller.core.module.FloodlightModuleException) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) U64(org.projectfloodlight.openflow.types.U64) OFPortDesc(org.projectfloodlight.openflow.protocol.OFPortDesc) InfoMessage(org.openkilda.messaging.info.InfoMessage) OFPortDescPropEthernet(org.projectfloodlight.openflow.protocol.OFPortDescPropEthernet) Ethernet(net.floodlightcontroller.packet.Ethernet) OFPort(org.projectfloodlight.openflow.types.OFPort) IslInfoData(org.openkilda.messaging.info.event.IslInfoData) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) LLDPTLV(net.floodlightcontroller.packet.LLDPTLV)

Example 32 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project open-kilda by telstra.

the class TopologyTest method verifyEmittedValues.

@Test
public void verifyEmittedValues() {
    MkClusterParam clusterParam = new MkClusterParam();
    clusterParam.setSupervisors(1);
    withSimulatedTimeLocalCluster(clusterParam, new TestJob() {

        @Override
        public void run(ILocalCluster cluster) throws JsonProcessingException {
            MockedSources mockedSources = new MockedSources();
            mockedSources.addMockData(builder.getSpoutId(), new Values(SWITCH_ID));
            Config config = new Config();
            config.setDebug(true);
            CompleteTopologyParam topologyParam = new CompleteTopologyParam();
            topologyParam.setMockedSources(mockedSources);
            topologyParam.setStormConf(config);
            Map<?, ?> result = completeTopology(cluster, builder.build(), topologyParam);
            assertTrue(multiseteq(new Values(new Values(SWITCH_ID)), readTuples(result, builder.getSpoutId())));
            assertTrue(multiseteq(new Values(new Values(SWITCH_ID)), readTuples(result, builder.getConfirmationBoltId())));
        }
    });
}
Also used : ILocalCluster(org.apache.storm.ILocalCluster) MockedSources(org.apache.storm.testing.MockedSources) TestJob(org.apache.storm.testing.TestJob) Config(org.apache.storm.Config) CompleteTopologyParam(org.apache.storm.testing.CompleteTopologyParam) Values(org.apache.storm.tuple.Values) MkClusterParam(org.apache.storm.testing.MkClusterParam) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Map(java.util.Map) Test(org.junit.Test)

Example 33 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project open-kilda by telstra.

the class KafkaMessageProducer method send.

/**
 * Sends messages to WorkFlowManager.
 *
 * @param topic  kafka topic
 * @param object object to serialize and send
 */
public void send(final String topic, final Object object) {
    String message;
    try {
        message = MAPPER.writeValueAsString(object);
    } catch (JsonProcessingException exception) {
        logger.error("Unable to serialize object: object={}", object, exception);
        throw new MessageException(DATA_INVALID, System.currentTimeMillis());
    }
    kafkaTemplate.send(topic, message).addCallback(new ListenableFutureCallback<SendResult<String, String>>() {

        @Override
        public void onSuccess(SendResult<String, String> result) {
            logger.debug("Message sent: topic={}, message={}", topic, message);
        }

        @Override
        public void onFailure(Throwable exception) {
            logger.error("Unable to send message: topic={}, message={}", topic, message, exception);
        }
    });
}
Also used : MessageException(org.openkilda.messaging.error.MessageException) SendResult(org.springframework.kafka.support.SendResult) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 34 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project airlift by airlift.

the class SmileMapper method readFrom.

@Override
public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream inputStream) throws IOException {
    Object object;
    try {
        JsonParser jsonParser = new SmileFactory().createParser(inputStream);
        // Important: we are NOT to close the underlying stream after
        // mapping, so we need to instruct parser:
        jsonParser.disable(JsonParser.Feature.AUTO_CLOSE_SOURCE);
        object = objectMapper.readValue(jsonParser, objectMapper.getTypeFactory().constructType(genericType));
    } catch (Exception e) {
        // we want to return a 400 for bad JSON but not for a real IO exception
        if (e instanceof IOException && !(e instanceof JsonProcessingException) && !(e instanceof EOFException)) {
            throw (IOException) e;
        }
        // log the exception at debug so it can be viewed during development
        // Note: we are not logging at a higher level because this could cause a denial of service
        log.debug(e, "Invalid json for Java type %s", type);
        // Invalid json request. Throwing exception so the response code can be overridden using a mapper.
        throw new JsonMapperParsingException(type, e);
    }
    return object;
}
Also used : SmileFactory(com.fasterxml.jackson.dataformat.smile.SmileFactory) EOFException(java.io.EOFException) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) EOFException(java.io.EOFException) JsonParser(com.fasterxml.jackson.core.JsonParser)

Example 35 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project connect-utils by jcustenborder.

the class RstTemplateHelper method jsonExample.

public String jsonExample(ConnectorTemplate template) {
    StringWriter writer = new StringWriter();
    final ObjectNode outputNode = createJsonNode(template);
    final String json;
    try {
        json = this.objectMapper.writeValueAsString(outputNode);
    } catch (JsonProcessingException e) {
        throw new IllegalStateException(e);
    }
    writer.write(".. code-block:: json");
    writer.write('\n');
    writer.write("    :name: connector.json");
    writer.write('\n');
    List<Integer> emphasizeLines = emphasizeLines(json);
    if (!emphasizeLines.isEmpty()) {
        writer.write("    :emphasize-lines: ");
        writer.write(Joiner.on(',').join(emphasizeLines));
        writer.write('\n');
    }
    writer.write('\n');
    writer.write(indent(json));
    writer.write('\n');
    return writer.toString();
}
Also used : StringWriter(java.io.StringWriter) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Aggregations

JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)648 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)205 IOException (java.io.IOException)156 HashMap (java.util.HashMap)105 Map (java.util.Map)77 ArrayList (java.util.ArrayList)67 JsonNode (com.fasterxml.jackson.databind.JsonNode)54 List (java.util.List)50 Test (org.junit.Test)44 InputStream (java.io.InputStream)24 Collectors (java.util.stream.Collectors)24 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)23 Json (com.sequenceiq.cloudbreak.domain.json.Json)21 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)20 Function (java.util.function.Function)18 Test (org.testng.annotations.Test)18 File (java.io.File)17 Date (java.util.Date)17 UnsupportedEncodingException (java.io.UnsupportedEncodingException)15 URL (java.net.URL)15