2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.protocol.util;
11 import java.io.FileInputStream;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.io.InputStreamReader;
15 import java.util.List;
17 import org.apache.commons.codec.DecoderException;
18 import org.apache.commons.codec.binary.Hex;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
22 import com.google.common.base.Preconditions;
23 import com.google.common.collect.Lists;
24 import com.google.common.io.CharStreams;
27 * Parses PCEP messages from a text file. Messages need to follow this formatting:
29 * Received PCEP Open message. Length:28.
31 * 20 01 00 1c 01 10 00 18 20 1e 78 03 00 10 00 04 00 00 00 05 00 1a 00 04 00 00 00 b4
33 public final class PCEPHexDumpParser {
34 private static final int MINIMAL_LENGTH = 4;
35 private static final Logger LOG = LoggerFactory.getLogger(PCEPHexDumpParser.class);
36 private static final String LENGTH = "LENGTH:";
38 private PCEPHexDumpParser() {
42 public static List<byte[]> parseMessages(final File file) throws IOException {
43 Preconditions.checkArgument(file != null, "Filename cannot be null");
44 return parseMessages(new FileInputStream(file));
47 public static List<byte[]> parseMessages(final InputStream is) throws IOException {
48 Preconditions.checkNotNull(is);
49 try (InputStreamReader isr = new InputStreamReader(is)) {
50 return parseMessages(CharStreams.toString(isr));
56 private static List<byte[]> parseMessages(final String c) {
57 final String content = clearWhiteSpaceToUpper(c);
59 final List<byte[]> messages = Lists.newLinkedList();
60 int idx = content.indexOf(LENGTH, 0);
62 // next chars are final length, ending with '.'
63 final int lengthIdx = idx + LENGTH.length();
64 final int messageIdx = content.indexOf('.', lengthIdx);
66 final int length = Integer.valueOf(content.substring(lengthIdx, messageIdx));
67 final int messageEndIdx = idx + length * 2;
69 // Assert that message is longer than minimum 4(header.length == 4)
70 // If length in PCEP message would be 0, loop would never end
71 Preconditions.checkArgument(length >= MINIMAL_LENGTH, "Invalid message at index " + idx + ", length atribute is lower than "
74 final String hexMessage = content.substring(idx, messageEndIdx);
75 byte[] message = null;
77 message = Hex.decodeHex(hexMessage.toCharArray());
78 } catch (final DecoderException e) {
79 new RuntimeException(e);
81 messages.add(message);
83 idx = content.indexOf(LENGTH, idx);
85 LOG.info("Succesfully extracted {} messages", messages.size());
89 private static String clearWhiteSpaceToUpper(final String line) {
90 return line.replaceAll("\\s", "").toUpperCase();