001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.camel.component.snmp;
018
019 import org.apache.camel.Converter;
020 import org.snmp4j.PDU;
021 import org.snmp4j.smi.VariableBinding;
022
023 @Converter
024 public final class SnmpConverters {
025 public static final String SNMP_TAG = "snmp";
026 public static final String ENTRY_TAG = "entry";
027 public static final String OID_TAG = "oid";
028 public static final String VALUE_TAG = "value";
029
030 private static final String SNMP_TAG_OPEN = '<' + SNMP_TAG + '>';
031 private static final String SNMP_TAG_CLOSE = "</" + SNMP_TAG + '>';
032 private static final String ENTRY_TAG_OPEN = '<' + ENTRY_TAG + '>';
033 private static final String ENTRY_TAG_CLOSE = "</" + ENTRY_TAG + '>';
034 private static final String OID_TAG_OPEN = '<' + OID_TAG + '>';
035 private static final String OID_TAG_CLOSE = "</" + OID_TAG + '>';
036 private static final String VALUE_TAG_OPEN = '<' + VALUE_TAG + '>';
037 private static final String VALUE_TAG_CLOSE = "</" + VALUE_TAG + '>';
038
039 private SnmpConverters() {
040 //Utility Class
041 }
042
043 /**
044 * Converts the given snmp pdu to a String body.
045 *
046 * @param pdu the snmp pdu
047 * @return the text content
048 */
049 @Converter
050 public static String toString(PDU pdu) {
051 // the output buffer
052 StringBuilder sb = new StringBuilder();
053
054 // prepare the header
055 sb.append(SNMP_TAG_OPEN);
056
057 // now loop all variables of the response
058 for (Object o : pdu.getVariableBindings()) {
059 VariableBinding b = (VariableBinding)o;
060
061 sb.append(ENTRY_TAG_OPEN);
062 sb.append(OID_TAG_OPEN);
063 sb.append(b.getOid().toString());
064 sb.append(OID_TAG_CLOSE);
065 sb.append(VALUE_TAG_OPEN);
066 sb.append(getXmlSafeString(b.getVariable().toString()));
067 sb.append(VALUE_TAG_CLOSE);
068 sb.append(ENTRY_TAG_CLOSE);
069 }
070
071 // prepare the footer
072 sb.append(SNMP_TAG_CLOSE);
073
074 return sb.toString();
075 }
076
077 private static String getXmlSafeString(String string) {
078 return string.replaceAll("<", "<").replaceAll(">", ">").replaceAll("&", "&").replaceAll("\"", """).replaceAll("'", "'");
079 }
080 }