com.fasterxml.jackson.databind.MappingJsonFactory Java Examples

The following examples show how to use com.fasterxml.jackson.databind.MappingJsonFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CustomResourceOperationsImplTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private void assertForContext(CustomResourceOperationContext context) throws IOException {
  // CustomResourceOperationsImpl constructor invokes KubernetesDeserializer::registerCustomKind
  new CustomResourceOperationsImpl<>(context);

  JsonFactory factory = new MappingJsonFactory();
  JsonParser parser = factory.createParser("{\n" +
    "    \"apiVersion\": \"custom.group/v1alpha1\",\n" +
    "    \"kind\": \"MyCustomResource\"\n" +
    "}");

  KubernetesDeserializer deserializer = new KubernetesDeserializer();
  KubernetesResource resource = deserializer.deserialize(parser, null);

  assertThat(resource, instanceOf(MyCustomResource.class));
  assertEquals("custom.group/v1alpha1", ((MyCustomResource) resource).getApiVersion());
}
 
Example #2
Source File: WalletClient.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
private static <T> ByteArrayOutputStream serializeJSON(final T src) throws GAException {
    final ByteArrayOutputStream b = new ByteArrayOutputStream();
    try {
        new MappingJsonFactory().getCodec().writeValue(b, src);
    } catch (final IOException e) {
        throw new GAException(e.getMessage());
    }
    return b;
}
 
Example #3
Source File: StaticFlowEntries.java    From floodlight_with_topoguard with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the entry name of a flow mod
 * @param fmJson The OFFlowMod in a JSON representation
 * @return The name of the OFFlowMod, null if not found
 * @throws IOException If there was an error parsing the JSON
 */
public static String getEntryNameFromJson(String fmJson) throws IOException{
    MappingJsonFactory f = new MappingJsonFactory();
    JsonParser jp;
    
    try {
        jp = f.createJsonParser(fmJson);
    } catch (JsonParseException e) {
        throw new IOException(e);
    }
    
    jp.nextToken();
    if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
        throw new IOException("Expected START_OBJECT");
    }
    
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
            throw new IOException("Expected FIELD_NAME");
        }
        
        String n = jp.getCurrentName();
        jp.nextToken();
        if (jp.getText().equals("")) 
            continue;
        
        if (n == "name")
            return jp.getText();
    }
    
    return null;
}
 
Example #4
Source File: FirewallResource.java    From floodlight_with_topoguard with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts subnet mask from a JSON string
 * @param fmJson The JSON formatted string
 * @return The subnet mask
 * @throws IOException If there was an error parsing the JSON
 */
public static String jsonExtractSubnetMask(String fmJson) throws IOException {
    String subnet_mask = "";
    MappingJsonFactory f = new MappingJsonFactory();
    JsonParser jp;

    try {
        jp = f.createJsonParser(fmJson);
    } catch (JsonParseException e) {
        throw new IOException(e);
    }

    jp.nextToken();
    if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
        throw new IOException("Expected START_OBJECT");
    }

    while (jp.nextToken() != JsonToken.END_OBJECT) {
        if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
            throw new IOException("Expected FIELD_NAME");
        }

        String n = jp.getCurrentName();
        jp.nextToken();
        if (jp.getText().equals(""))
            continue;

        if (n == "subnet-mask") {
            subnet_mask = jp.getText();
            break;
        }
    }

    return subnet_mask;
}
 
Example #5
Source File: ReportBuilder.java    From tc-ansible-runner with MIT License 5 votes vote down vote up
public static void buildJsonReport(List<Playbook> playbooks, File resultFile) throws Exception {
    JsonFactory jf = new MappingJsonFactory();
    try (JsonGenerator jg = jf.createGenerator(resultFile, JsonEncoding.UTF8)) {
        jg.writeStartObject();
        jg.writeFieldName("playbooks");
        jg.writeObject(playbooks);
        jg.writeEndObject();
    } catch (Exception e) {
        throw e;
    }
    
}
 
Example #6
Source File: RestClient.java    From constellation with Apache License 2.0 5 votes vote down vote up
/**
 * Generate a json string from a flat Map<String, String> of key and values
 *
 * @param params A Map of key/value pairs
 * @return A json representation of a simple map
 *
 * @throws IOException
 */
private String generateJsonFromFlatMap(final Map<String, String> params) throws IOException {
    final ByteArrayOutputStream json = new ByteArrayOutputStream();
    final JsonFactory jsonFactory = new MappingJsonFactory();
    try (JsonGenerator jg = jsonFactory.createGenerator(json)) {
        jg.writeStartObject();
        for (final Map.Entry<String, String> param : params.entrySet()) {
            jg.writeStringField(param.getKey(), param.getValue());
        }
        jg.writeEndObject();
        jg.flush();
    }

    return json.toString(StandardCharsets.UTF_8.name());
}
 
Example #7
Source File: HostResource.java    From floodlight_with_topoguard with Apache License 2.0 5 votes vote down vote up
protected void jsonToHostDefinition(String json, HostDefinition host) throws IOException {
    MappingJsonFactory f = new MappingJsonFactory();
    JsonParser jp;
    
    try {
        jp = f.createJsonParser(json);
    } catch (JsonParseException e) {
        throw new IOException(e);
    }
    
    jp.nextToken();
    if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
        throw new IOException("Expected START_OBJECT");
    }
    
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
            throw new IOException("Expected FIELD_NAME");
        }
        
        String n = jp.getCurrentName();
        jp.nextToken();
        if (jp.getText().equals("")) 
            continue;
        else if (n.equals("attachment")) {
            while (jp.nextToken() != JsonToken.END_OBJECT) {
                String field = jp.getCurrentName();
                if (field.equals("id")) {
                    host.attachment = jp.getText();
                } else if (field.equals("mac")) {
                    host.mac = jp.getText();
                }
            }
        }
    }
    
    jp.close();
}
 
Example #8
Source File: JSONMap.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
public JSONMap getMap(final String k) {
    try {
        final String v = get(k, null);
        if (v == null)
            return null;
        return new JSONMap(new MappingJsonFactory().getCodec().readValue(v, Map.class));
    } catch (final IOException e) {
        return null;
    }
}
 
Example #9
Source File: CryptoHelper.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
public static JSONMap decryptJSON(final byte[] encryptedData, final byte[] password, final byte[] salt) {
    final byte[] decrypted = decrypt_aes_cbc(encryptedData, password, salt);
    final Map<String, Object> json;
    try {
        json = new MappingJsonFactory().getCodec().readValue(new String(decrypted), Map.class);
    } catch (final IOException e) {
        throw new RuntimeException(e.getMessage()); // Coding error
    }
    return new JSONMap(json);
}
 
Example #10
Source File: CryptoHelper.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
public static byte[] encryptJSON(final JSONMap json, final byte[] password, final byte[] salt) {
    final ByteArrayOutputStream b = new ByteArrayOutputStream();
    try {
        new MappingJsonFactory().getCodec().writeValue(b, json.mData);
    } catch (final IOException e) {
        throw new RuntimeException(e.getMessage());// coding error
    }

    return encrypt_aes_cbc(b.toByteArray(), password, salt);
}
 
Example #11
Source File: HCBatchOperations.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * @return {@code com.fasterxml.jackson.databind.ObjectWriter} to serialize {@link IndexRequest} instances
 */
// FIXME: design - wrap with Serializer(?) to allow other implementations
protected ObjectWriter configuredWriter() {
    return new ExtendedObjectMapper(new MappingJsonFactory())
            .setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
            .addMixIn(IndexRequest.class, IndexRequestMixIn.class)
            .writerFor(IndexRequest.class);
}
 
Example #12
Source File: SpecificationLoader.java    From aws-cloudformation-template-schema with Apache License 2.0 5 votes vote down vote up
public SpecificationLoader() {
    jsonFactory = new MappingJsonFactory();
    mapperForJSON = new ObjectMapper(jsonFactory);
    mapperForJSON.configure(MapperFeature.USE_STD_BEAN_NAMING, true)
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        .configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false)
        .configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true)
        .configure(SerializationFeature.FAIL_ON_SELF_REFERENCES, true)
        .configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, true)
        .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
        .setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    jsonFactory.setCodec(mapperForJSON);
    mapperForJSON.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);
}
 
Example #13
Source File: ComplexTypeITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Override
public List<ComplexNestedType> unmarshall(Class<List<ComplexNestedType>> clazz, String obj) {
    try {
        JsonFactory jsonFactory = new MappingJsonFactory();
        JsonParser jsonParser = jsonFactory.createJsonParser(new StringReader(obj));
        return jsonParser.readValueAs(new TypeReference<List<ComplexNestedType>>() {
        });
    } catch ( Exception e ) {
        throw new RuntimeException(e);
    }            
}
 
Example #14
Source File: MonitorsResource.java    From floodlight_with_topoguard with Apache License 2.0 4 votes vote down vote up
protected LBMonitor jsonToMonitor(String json) throws IOException {
    MappingJsonFactory f = new MappingJsonFactory();
    JsonParser jp;
    LBMonitor monitor = new LBMonitor();
    
    try {
        jp = f.createJsonParser(json);
    } catch (JsonParseException e) {
        throw new IOException(e);
    }
    
    jp.nextToken();
    if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
        throw new IOException("Expected START_OBJECT");
    }
    
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
            throw new IOException("Expected FIELD_NAME");
        }
        
        String n = jp.getCurrentName();
        jp.nextToken();
        if (jp.getText().equals("")) 
            continue;
        else if (n.equals("monitor")) {
            while (jp.nextToken() != JsonToken.END_OBJECT) {
                String field = jp.getCurrentName();
                
                if (field.equals("id")) {
                    monitor.id = jp.getText();
                    continue;
                } 
                if (field.equals("name")) {
                    monitor.name = jp.getText();
                    continue;
                }
                if (field.equals("type")) {
                    monitor.type = Short.parseShort(jp.getText());
                    continue;
                }
                if (field.equals("delay")) {
                    monitor.delay = Short.parseShort(jp.getText());
                    continue;
                }
                if (field.equals("timeout")) {
                    monitor.timeout = Short.parseShort(jp.getText());
                    continue;
                }
                if (field.equals("attempts_before_deactivation")) {
                    monitor.attemptsBeforeDeactivation = Short.parseShort(jp.getText());
                    continue;
                }
                if (field.equals("network_id")) {
                    monitor.netId = jp.getText();
                    continue;
                }
                if (field.equals("address")) {
                    monitor.address = Integer.parseInt(jp.getText());
                    continue;
                }
                if (field.equals("protocol")) {
                    monitor.protocol = Byte.parseByte(jp.getText());
                    continue;
                }
                if (field.equals("port")) {
                    monitor.port = Short.parseShort(jp.getText());
                    continue;
                }
                if (field.equals("admin_state")) {
                    monitor.adminState = Short.parseShort(jp.getText());
                    continue;
                }
                if (field.equals("status")) {
                    monitor.status = Short.parseShort(jp.getText());
                    continue;
                }
                
                log.warn("Unrecognized field {} in " +
                        "parsing Vips", 
                        jp.getText());
            }
        }
    }
    jp.close();

    return monitor;
}
 
Example #15
Source File: JSONImporter.java    From robe with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void importStream(InputStream inputStream, OnItemHandler handler, String charSetName) throws Exception {


    JsonFactory factory = new MappingJsonFactory();

    JsonParser parser = factory.createParser(new InputStreamReader(inputStream, charSetName));

    JsonToken current;

    current = parser.nextToken();
    if (current != JsonToken.START_ARRAY) {
        throw new RuntimeException("Error: root should be object or array.");
    }

    while (parser.nextToken() != JsonToken.END_ARRAY) {
        if (parser.getCurrentName() == null)
            continue;
        T item = (T) parser.readValueAs(getDataClass());
        handler.onItem(item);

    }

}
 
Example #16
Source File: StaticFlowEntries.java    From floodlight_with_topoguard with Apache License 2.0 4 votes vote down vote up
/**
 * Turns a JSON formatted Static Flow Pusher string into a storage entry
 * Expects a string in JSON along the lines of:
 *        {
 *            "switch":       "AA:BB:CC:DD:EE:FF:00:11",
 *            "name":         "flow-mod-1",
 *            "cookie":       "0",
 *            "priority":     "32768",
 *            "ingress-port": "1",
 *            "actions":      "output=2",
 *        }
 * @param fmJson The JSON formatted static flow pusher entry
 * @return The map of the storage entry
 * @throws IOException If there was an error parsing the JSON
 */
public static Map<String, Object> jsonToStorageEntry(String fmJson) throws IOException {
    Map<String, Object> entry = new HashMap<String, Object>();
    MappingJsonFactory f = new MappingJsonFactory();
    JsonParser jp;
    
    try {
        jp = f.createJsonParser(fmJson);
    } catch (JsonParseException e) {
        throw new IOException(e);
    }
    
    jp.nextToken();
    if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
        throw new IOException("Expected START_OBJECT");
    }
    
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
            throw new IOException("Expected FIELD_NAME");
        }
        
        String n = jp.getCurrentName();
        jp.nextToken();
        if (jp.getText().equals("")) 
            continue;
        
        if (n == "name")
            entry.put(StaticFlowEntryPusher.COLUMN_NAME, jp.getText());
        else if (n == "switch")
            entry.put(StaticFlowEntryPusher.COLUMN_SWITCH, jp.getText());
        else if (n == "actions")
            entry.put(StaticFlowEntryPusher.COLUMN_ACTIONS, jp.getText());
        else if (n == "priority")
            entry.put(StaticFlowEntryPusher.COLUMN_PRIORITY, jp.getText());
        else if (n == "active")
            entry.put(StaticFlowEntryPusher.COLUMN_ACTIVE, jp.getText());
        else if (n == "wildcards")
            entry.put(StaticFlowEntryPusher.COLUMN_WILDCARD, jp.getText());
        else if (n == "ingress-port")
            entry.put(StaticFlowEntryPusher.COLUMN_IN_PORT, jp.getText());
        else if (n == "src-mac")
            entry.put(StaticFlowEntryPusher.COLUMN_DL_SRC, jp.getText());
        else if (n == "dst-mac")
            entry.put(StaticFlowEntryPusher.COLUMN_DL_DST, jp.getText());
        else if (n == "vlan-id")
            entry.put(StaticFlowEntryPusher.COLUMN_DL_VLAN, jp.getText());
        else if (n == "vlan-priority")
            entry.put(StaticFlowEntryPusher.COLUMN_DL_VLAN_PCP, jp.getText());
        else if (n == "ether-type")
            entry.put(StaticFlowEntryPusher.COLUMN_DL_TYPE, jp.getText());
        else if (n == "tos-bits")
            entry.put(StaticFlowEntryPusher.COLUMN_NW_TOS, jp.getText());
        else if (n == "protocol")
            entry.put(StaticFlowEntryPusher.COLUMN_NW_PROTO, jp.getText());
        else if (n == "src-ip")
            entry.put(StaticFlowEntryPusher.COLUMN_NW_SRC, jp.getText());
        else if (n == "dst-ip")
            entry.put(StaticFlowEntryPusher.COLUMN_NW_DST, jp.getText());
        else if (n == "src-port")
            entry.put(StaticFlowEntryPusher.COLUMN_TP_SRC, jp.getText());
        else if (n == "dst-port")
            entry.put(StaticFlowEntryPusher.COLUMN_TP_DST, jp.getText());
    }
    
    return entry;
}
 
Example #17
Source File: JsonRpcReaderUtil.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Decode the bytes to Json object.
 * @param in input of bytes
 * @param out ouput of Json object list
 * @param jrContext context for the last decoding process
 * @throws IOException IOException
 * @throws JsonParseException JsonParseException
 */
public static void readToJsonNode(ByteBuf in, List<Object> out, JsonReadContext jrContext)
        throws JsonParseException, IOException {
    int lastReadBytes = jrContext.getLastReadBytes();
    if (lastReadBytes == 0) {
        if (in.readableBytes() < 4) {
            return;
        }
        checkEncoding(in);
    }

    int i = lastReadBytes + in.readerIndex();
    Stack<Byte> bufStack = jrContext.getBufStack();
    for (; i < in.writerIndex(); i++) {
        byte b = in.getByte(i);
        switch (b) {
        case '{':
            if (!isDoubleQuote(bufStack)) {
                bufStack.push(b);
                jrContext.setStartMatch(true);
            }
            break;
        case '}':
            if (!isDoubleQuote(bufStack)) {
                bufStack.pop();
            }
            break;
        case '"':
            if (in.getByte(i - 1) != '\\') {
                if (!bufStack.isEmpty() && bufStack.peek() != '"') {
                    bufStack.push(b);
                } else {
                    bufStack.pop();
                }
            }
            break;
        default:
            break;
        }

        if (jrContext.isStartMatch() && bufStack.isEmpty()) {
            ByteBuf buf = in.readSlice(i - in.readerIndex() + 1);
            JsonParser jf = new MappingJsonFactory().createParser((DataInput) new ByteBufInputStream(buf));
            JsonNode jsonNode = jf.readValueAsTree();
            out.add(jsonNode);
            lastReadBytes = 0;
            jrContext.setLastReadBytes(lastReadBytes);
            break;
        }
    }

    if (i >= in.writerIndex()) {
        lastReadBytes = in.readableBytes();
        jrContext.setLastReadBytes(lastReadBytes);
    }
}
 
Example #18
Source File: MembersResource.java    From floodlight_with_topoguard with Apache License 2.0 4 votes vote down vote up
protected LBMember jsonToMember(String json) throws IOException {
    MappingJsonFactory f = new MappingJsonFactory();
    JsonParser jp;
    LBMember member = new LBMember();
    
    try {
        jp = f.createJsonParser(json);
    } catch (JsonParseException e) {
        throw new IOException(e);
    }
    
    jp.nextToken();
    if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
        throw new IOException("Expected START_OBJECT");
    }
    
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
            throw new IOException("Expected FIELD_NAME");
        }
        
        String n = jp.getCurrentName();
        jp.nextToken();
        if (jp.getText().equals("")) 
            continue;
        if (n.equals("id")) {
            member.id = jp.getText();
            continue;
        } else
        if (n.equals("address")) {
            member.address = IPv4.toIPv4Address(jp.getText());
            continue;
        } else
        if (n.equals("port")) {
            member.port = Short.parseShort(jp.getText());
            continue;
        } else
        if (n.equals("connection_limit")) {
            member.connectionLimit = Integer.parseInt(jp.getText());
            continue;
        } else
        if (n.equals("admin_state")) {
            member.adminState = Short.parseShort(jp.getText());
            continue;
        } else
        if (n.equals("status")) {
            member.status = Short.parseShort(jp.getText());
            continue;
        } else
        if (n.equals("pool_id")) {
            member.poolId = jp.getText();
            continue;
        } 
        
        log.warn("Unrecognized field {} in " +
                "parsing Members", 
                jp.getText());
    }
    jp.close();

    return member;
}
 
Example #19
Source File: PoolsResource.java    From floodlight_with_topoguard with Apache License 2.0 4 votes vote down vote up
protected LBPool jsonToPool(String json) throws IOException {
    if (json==null) return null;

    MappingJsonFactory f = new MappingJsonFactory();
    JsonParser jp;
    LBPool pool = new LBPool();
    
    try {
        jp = f.createJsonParser(json);
    } catch (JsonParseException e) {
        throw new IOException(e);
    }
    
    jp.nextToken();
    if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
        throw new IOException("Expected START_OBJECT");
    }
    
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
            throw new IOException("Expected FIELD_NAME");
        }
        
        String n = jp.getCurrentName();
        jp.nextToken();
        if (jp.getText().equals("")) 
            continue;
        if (n.equals("id")) {
            pool.id = jp.getText();
            continue;
        } 
        if (n.equals("tenant_id")) {
            pool.tenantId = jp.getText();
            continue;
        } 
        if (n.equals("name")) {
            pool.name = jp.getText();
            continue;
        }
        if (n.equals("network_id")) {
            pool.netId = jp.getText();
            continue;
        }
        if (n.equals("lb_method")) {
            pool.lbMethod = Short.parseShort(jp.getText());
            continue;
        }
        if (n.equals("protocol")) {
            String tmp = jp.getText();
            if (tmp.equalsIgnoreCase("TCP")) {
                pool.protocol = IPv4.PROTOCOL_TCP;
            } else if (tmp.equalsIgnoreCase("UDP")) {
                pool.protocol = IPv4.PROTOCOL_UDP;
            } else if (tmp.equalsIgnoreCase("ICMP")) {
                pool.protocol = IPv4.PROTOCOL_ICMP;
            } 
            continue;
        }                    
        if (n.equals("vip_id")) {
            pool.vipId = jp.getText();
            continue;
        } 
        
        log.warn("Unrecognized field {} in " +
                "parsing Pools", 
                jp.getText());
    }
    jp.close();

    return pool;
}
 
Example #20
Source File: VipsResource.java    From floodlight_with_topoguard with Apache License 2.0 4 votes vote down vote up
protected LBVip jsonToVip(String json) throws IOException {
    
    if (json==null) return null;
    
    MappingJsonFactory f = new MappingJsonFactory();
    JsonParser jp;
    LBVip vip = new LBVip();
    
    try {
        jp = f.createJsonParser(json);
    } catch (JsonParseException e) {
        throw new IOException(e);
    }
    
    jp.nextToken();
    if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
        throw new IOException("Expected START_OBJECT");
    }
    
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
            throw new IOException("Expected FIELD_NAME");
        }
        
        String n = jp.getCurrentName();
        jp.nextToken();
        if (jp.getText().equals("")) 
            continue;
 
        if (n.equals("id")) {
            vip.id = jp.getText();
            continue;
        } 
        if (n.equals("tenant_id")) {
            vip.tenantId = jp.getText();
            continue;
        } 
        if (n.equals("name")) {
            vip.name = jp.getText();
            continue;
        }
        if (n.equals("network_id")) {
            vip.netId = jp.getText();
            continue;
        }
        if (n.equals("protocol")) {
            String tmp = jp.getText();
            if (tmp.equalsIgnoreCase("TCP")) {
                vip.protocol = IPv4.PROTOCOL_TCP;
            } else if (tmp.equalsIgnoreCase("UDP")) {
                vip.protocol = IPv4.PROTOCOL_UDP;
            } else if (tmp.equalsIgnoreCase("ICMP")) {
                vip.protocol = IPv4.PROTOCOL_ICMP;
            } 
            continue;
        }
        if (n.equals("address")) {
            vip.address = IPv4.toIPv4Address(jp.getText());
            continue;
        }
        if (n.equals("port")) {
            vip.port = Short.parseShort(jp.getText());
            continue;
        }
        if (n.equals("pool_id")) {
            vip.pools.add(jp.getText());
            continue;
        }
        
        log.warn("Unrecognized field {} in " +
                "parsing Vips", 
                jp.getText());
    }
    jp.close();
    
    return vip;
}
 
Example #21
Source File: NetworkResource.java    From floodlight_with_topoguard with Apache License 2.0 4 votes vote down vote up
protected void jsonToNetworkDefinition(String json, NetworkDefinition network) throws IOException {
    MappingJsonFactory f = new MappingJsonFactory();
    JsonParser jp;
    
    try {
        jp = f.createJsonParser(json);
    } catch (JsonParseException e) {
        throw new IOException(e);
    }
    
    jp.nextToken();
    if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
        throw new IOException("Expected START_OBJECT");
    }
    
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
            throw new IOException("Expected FIELD_NAME");
        }
        
        String n = jp.getCurrentName();
        jp.nextToken();
        if (jp.getText().equals("")) 
            continue;
        else if (n.equals("network")) {
            while (jp.nextToken() != JsonToken.END_OBJECT) {
                String field = jp.getCurrentName();
                if (field == null) continue;
                if (field.equals("name")) {
                    network.name = jp.getText();
                } else if (field.equals("gateway")) {
                	String gw = jp.getText();
                	if ((gw != null) && (!gw.equals("null")))
                		network.gateway = gw;
                } else if (field.equals("id")) {
                	network.guid = jp.getText();
                } else {
                    log.warn("Unrecognized field {} in " +
                    		"parsing network definition", 
                    		jp.getText());
                }
            }
        }
    }
    
    jp.close();
}
 
Example #22
Source File: JsonOperatorDump.java    From yql-plus with Apache License 2.0 4 votes vote down vote up
public String dump(OperatorNode<? extends Operator> program) throws IOException {
    MappingJsonFactory factory = new MappingJsonFactory();
    ObjectMapper mapper = new ObjectMapper(factory);
    mapper.registerModule(new ProgramDumpModule());
    return mapper.writer().withDefaultPrettyPrinter().writeValueAsString(program);
}
 
Example #23
Source File: RecordStoreUtilities.java    From constellation with Apache License 2.0 4 votes vote down vote up
/**
 * Convert a JSON {@link InputStream} into a {@link RecordStore}.
 * <p>
 * The specified JSON stream should contain an array of objects, with each
 * object being converted to a record in the resulting {@link RecordStore}.
 * Each field in each object is converted to an entry in the corresponding
 * record.
 *
 * @param in An {@link InputStream} through which the JSON document will be
 * transported.
 * @return A {@link RecordStore} derived from the JSON document.
 * @throws IOException If something goes wrong while reading the JSON
 * document.
 */
public static RecordStore fromJson(final InputStream in) throws IOException {
    final RecordStore recordStore;
    try (final JsonParser parser = new MappingJsonFactory().createParser(in)) {
        recordStore = new GraphRecordStore();
        JsonToken currentToken = parser.nextToken();
        if (currentToken != JsonToken.START_ARRAY) {
            return null;
        }
        while (true) {
            currentToken = parser.nextToken();
            if (currentToken == JsonToken.START_OBJECT) {
                recordStore.add();

                while (true) {
                    currentToken = parser.nextToken();
                    if (currentToken == JsonToken.FIELD_NAME) {
                        String fieldName = parser.getCurrentName();

                        String fieldValue;
                        currentToken = parser.nextToken();
                        if (currentToken == JsonToken.VALUE_STRING || currentToken == JsonToken.VALUE_NUMBER_INT || currentToken == JsonToken.VALUE_NUMBER_FLOAT) {
                            fieldValue = parser.getValueAsString();
                        } else {
                            return null;
                        }

                        recordStore.set(fieldName, fieldValue);

                    } else if (currentToken == JsonToken.END_OBJECT) {
                        break;
                    } else {
                        return null;
                    }
                }
            } else if (currentToken == JsonToken.END_ARRAY) {
                break;
            } else {
                return null;
            }
        }
    }

    return recordStore;
}
 
Example #24
Source File: CompositeNodeState.java    From constellation with Apache License 2.0 4 votes vote down vote up
/**
 * De-serialise this state from the String representation of a JSON Node.
 *
 * @param s The composite state string
 *
 * @return The De-serialised CompositeNodeState.
 * @throws IllegalArgumentException If there is an issue with reading the
 * JSON.
 */
public static CompositeNodeState createFromString(final String s) {

    if (s == null || s.isEmpty()) {
        return null;
    }
    try (final JsonParser parser = new MappingJsonFactory().createParser(s)) {
        final JsonNode jn = parser.readValueAsTree();
        final int nodeId = jn.get(NODE_ID).asInt();

        final ExpandedCompositeNodeState expandedState;
        if (jn.hasNonNull(EXPANDED_STATE)) {
            final JsonNode expandedNode = jn.get(EXPANDED_STATE);
            final RecordStore compositeNodeStore = RecordStoreUtilities.fromJson(new ByteArrayInputStream(expandedNode.get(COMPOSITE_NODE_STORE).asText().getBytes(StandardCharsets.UTF_8.name())));
            final String compositeId = expandedNode.get(COMPOSITE_ID).asText();
            final boolean isAffecting = expandedNode.get(AFFECTING).asBoolean();
            final int numberOfNodes = expandedNode.get(NUMBER_OF_NODES).asInt();
            expandedState = new ExpandedCompositeNodeState(compositeNodeStore, compositeId, isAffecting, numberOfNodes);
        } else {
            expandedState = null;
        }

        final ContractedCompositeNodeState contractedState;
        if (jn.hasNonNull(CONTRACTED_STATE)) {
            final JsonNode contractedNode = jn.get(CONTRACTED_STATE);
            final RecordStore constituentNodeStore = RecordStoreUtilities.fromJson(new ByteArrayInputStream(contractedNode.get(CONSTITUENT_NODE_STORE).asText().getBytes(StandardCharsets.UTF_8.name())));
            final List<String> expandedIds = new ArrayList<>();
            final Iterator<JsonNode> expandedIdsIterator = contractedNode.get(EXPANDED_IDS).iterator();
            while (expandedIdsIterator.hasNext()) {
                expandedIds.add(expandedIdsIterator.next().asText());
            }
            final List<String> affectedExpandedIds = new ArrayList<>();
            final Iterator<JsonNode> affectedExpandedIdsIterator = contractedNode.get(AFFECTED_EXPANDED_IDS).iterator();
            while (affectedExpandedIdsIterator.hasNext()) {
                affectedExpandedIds.add(affectedExpandedIdsIterator.next().asText());
            }
            final float[] mean = new float[3];
            final Iterator<JsonNode> meanIterator = contractedNode.get(MEAN).iterator();
            int i = 0;
            while (meanIterator.hasNext() && i < 3) {
                mean[i++] = (float) meanIterator.next().asDouble();
            }
            contractedState = new ContractedCompositeNodeState(constituentNodeStore, expandedIds, affectedExpandedIds, mean);
        } else {
            contractedState = null;
        }

        return new CompositeNodeState(nodeId, expandedState, contractedState);
    } catch (IOException ex) {
        System.out.println(ex.getLocalizedMessage());
        throw new IllegalArgumentException("Error converting this string to a composite node state");
    }

}