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;
10 import static java.util.Objects.requireNonNull;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.Lists;
14 import com.google.common.io.BaseEncoding;
15 import com.google.common.io.CharStreams;
17 import java.io.FileInputStream;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.io.InputStreamReader;
21 import java.util.List;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
26 * Parses PCEP messages from a text file. Messages need to follow this formatting:
28 * Received PCEP Open message. Length:28.
30 * 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
32 public final class PCEPHexDumpParser {
33 private static final int MINIMAL_LENGTH = 4;
34 private static final Logger LOG = LoggerFactory.getLogger(PCEPHexDumpParser.class);
35 private static final String LENGTH = "LENGTH:";
37 private PCEPHexDumpParser() {
38 throw new UnsupportedOperationException();
41 public static List<byte[]> parseMessages(final File file) throws IOException {
42 Preconditions.checkArgument(file != null, "Filename cannot be null");
43 return parseMessages(new FileInputStream(file));
46 public static List<byte[]> parseMessages(final InputStream is) throws IOException {
48 try (InputStreamReader isr = new InputStreamReader(is, "UTF-8")) {
49 return parseMessages(CharStreams.toString(isr));
53 private static List<byte[]> parseMessages(final String c) {
54 final String content = clearWhiteSpaceToUpper(c);
56 final List<byte[]> messages = Lists.newLinkedList();
57 int idx = content.indexOf(LENGTH, 0);
59 // next chars are final length, ending with '.'
60 final int lengthIdx = idx + LENGTH.length();
61 final int messageIdx = content.indexOf('.', lengthIdx);
62 final int length = Integer.parseInt(content.substring(lengthIdx, messageIdx));
64 final int messageEndIdx = messageIdx + (length * 2) + 1;
66 // Assert that message is longer than minimum 4(header.length == 4)
67 // If length in PCEP message would be 0, loop would never end
68 Preconditions.checkArgument(length >= MINIMAL_LENGTH, "Invalid message at index " + idx + ", length atribute is lower than "
72 final String hexMessage = content.substring(messageIdx + 1, messageEndIdx);
73 final byte[] message = BaseEncoding.base16().decode(hexMessage);
74 messages.add(message);
76 idx = content.indexOf(LENGTH, idx);
78 LOG.info("Succesfully extracted {} messages", messages.size());
82 private static String clearWhiteSpaceToUpper(final String line) {
83 return line.replaceAll("\\s", "").toUpperCase();