Example usage for com.fasterxml.jackson.databind ObjectMapper getTypeFactory

List of usage examples for com.fasterxml.jackson.databind ObjectMapper getTypeFactory

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper getTypeFactory.

Prototype

public TypeFactory getTypeFactory() 

Source Link

Document

Accessor for getting currently configured TypeFactory instance.

Usage

From source file:com.tage.calcite.adapter.druid.DruidConnectionImpl.java

/** Reads data source names from Druid. */
Set<String> tableNames() {
    final Map<String, String> requestHeaders = ImmutableMap.of("Content-Type", "application/json");
    final String data = null;
    final String url = coordinatorUrl + "/druid/coordinator/v1/metadata/datasources";
    if (CalcitePrepareImpl.DEBUG) {
        System.out.println("Druid: table names" + data + "; " + url);
    }/*www . j  a  va  2s  .c  o m*/
    try (InputStream in0 = post(url, data, requestHeaders, 10000, 1800000);
            InputStream in = traceResponse(in0)) {
        final ObjectMapper mapper = new ObjectMapper();
        final CollectionType listType = mapper.getTypeFactory().constructCollectionType(List.class,
                String.class);
        final List<String> list = mapper.readValue(in, listType);
        return ImmutableSet.copyOf(list);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.tage.calcite.adapter.druid.DruidConnectionImpl.java

/** Reads segment metadata, and populates a list of columns and metrics. */
void metadata(String dataSourceName, List<String> intervals, Map<String, SqlTypeName> fieldBuilder,
        Set<String> metricNameBuilder) {
    final String url = this.url + "/druid/v2/?pretty";
    final Map<String, String> requestHeaders = ImmutableMap.of("Content-Type", "application/json");
    final String data = DruidQuery.metadataQuery(dataSourceName, intervals);
    if (CalcitePrepareImpl.DEBUG) {
        System.out.println("Druid: " + data);
    }//from ww  w  . ja v a2  s . c  o m
    try (InputStream in0 = post(url, data, requestHeaders, 10000, 1800000);
            InputStream in = traceResponse(in0)) {
        final ObjectMapper mapper = new ObjectMapper();
        final CollectionType listType = mapper.getTypeFactory().constructCollectionType(List.class,
                JsonSegmentMetadata.class);
        final List<JsonSegmentMetadata> list = mapper.readValue(in, listType);
        in.close();
        for (JsonSegmentMetadata o : list) {
            for (Map.Entry<String, JsonColumn> entry : o.columns.entrySet()) {
                fieldBuilder.put(entry.getKey(), entry.getValue().sqlType());
            }
            if (o.aggregators != null) {
                for (Map.Entry<String, JsonAggregator> entry : o.aggregators.entrySet()) {
                    fieldBuilder.put(entry.getKey(), entry.getValue().sqlType());
                    metricNameBuilder.add(entry.getKey());
                }
            }
        }
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.openlmis.fulfillment.web.BaseWebIntegrationTest.java

<T> List<T> getPageContent(Page page, Class<T> type) {
    List content = page.getContent();

    if (isEmpty(content)) {
        // nothing to do
        return Collections.emptyList();
    }//w ww.ja  v  a  2s. com

    if (type.isInstance(content.get(0))) {
        // content contains instances of the given type
        return Collections.checkedList(content, type);
    }

    if (content.get(0) instanceof Map) {
        // jackson does not convert json to correct type
        // instead it use default operation and objects are
        // represented by Map

        // We have to do manually convert map to the given type =(
        ObjectMapper mapper = new ObjectMapper();
        mapper.findAndRegisterModules();

        TypeFactory factory = mapper.getTypeFactory();
        CollectionLikeType collectionType = factory.constructCollectionLikeType(List.class, type);

        return mapper.convertValue(content, collectionType);
    }

    throw new IllegalStateException("the page content contains unsupported type");
}

From source file:io.gatling.liferay.controller.BuilderViewController.java

/**
 * Updates all the scenarios from the JSON send by the view
 * /*from   w ww.  j  ava 2 s  .c  o m*/
 * The JSON represent all the default simulation, it is mapped into dtos and persisted
 * @param request
 * @param response
 * @param model
 * @throws SystemException
 * @throws PortalException
 */
@ActionMapping(params = "action=saveScenarios")
public void saveMyScenarios(final ActionRequest request, final ActionResponse response, final Model model)
        throws SystemException, PortalException {
    String json = ParamUtil.getString(request, "JSON");
    LOG.debug("saveScenario called:");

    //LOG.debug(json);
    ObjectMapper mapper = new ObjectMapper();
    try {
        List<ScenarioDTO> dtos = mapper.readValue(json,
                mapper.getTypeFactory().constructCollectionType(List.class, ScenarioDTO.class));
        for (ScenarioDTO scenarioDTO : dtos) {
            //Persist the related scenario
            ScenarioDTOMapper.persistData(scenarioDTO);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    // if the action is launched from a trashcan buton, deletes the related scenario
    String scenarioId = ParamUtil.getString(request, "scenarioId");
    if (!scenarioId.equals("notDefined")) {
        deleteScenario(Long.parseLong(scenarioId));
    }

    request.getPortletSession().setAttribute("panelNb", 1);
    response.setRenderParameter("render", "renderView");
}

From source file:aasdntool.AASDNTool.java

private void devicesActionPerformed(java.awt.event.ActionEvent evt) {
    StringBuffer response = new StringBuffer();

    try {// ww w. ja va  2  s .  c o  m
        URL obj = new URL("http://" + controllerIP + ":8080/wm/device/");
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // optional default is GET
        con.setRequestMethod("GET");

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + "http://" + controllerIP + ":8080/wm/device/");
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        ObjectMapper mapper = new ObjectMapper();

        List<Device> devList = mapper.readValue(response.toString(),
                mapper.getTypeFactory().constructCollectionType(List.class, Device.class));

        DefaultTableModel dtm = new DefaultTableModel(0, 0);

        // add header of the table
        String header[] = new String[] { "MAC Address" };

        // add header in table model
        dtm.setColumnIdentifiers(header);
        macTable.setModel(dtm);

        for (Device dev : devList) {
            dtm.addRow(new Object[] { dev.getMac() });
        }

    } catch (Exception e) {
        System.out.println("Exception occured:" + e);
    }
}

From source file:aasdntool.AASDNTool.java

private void openFlowSwitchesActionPerformed(java.awt.event.ActionEvent evt) {

    StringBuffer response = new StringBuffer();

    try {//w  ww  .j  a v a  2 s.c  o  m
        URL obj = new URL("http://" + controllerIP + ":8080/wm/core/controller/switches/json");
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // optional default is GET
        con.setRequestMethod("GET");

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + "http://" + controllerIP
                + ":8080/wm/core/controller/switches/json");
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        ObjectMapper mapper = new ObjectMapper();
        List<Switches> switchList = mapper.readValue(response.toString(),
                mapper.getTypeFactory().constructCollectionType(List.class, Switches.class));

        DefaultTableModel dtm = new DefaultTableModel(0, 0);

        // add header of the table
        String header[] = new String[] { "Switch DPID", "IP Address" };

        // add header in table model
        dtm.setColumnIdentifiers(header);
        switchTable.setModel(dtm);

        // add row dynamically into the table
        for (Switches sw : switchList) {
            dtm.addRow(new Object[] { sw.getDpid(), sw.getInetAddress() });
        }

    } catch (Exception e) {
        System.out.println("Exception Occured:" + e);
    }
}

From source file:org.wisdom.monitor.extensions.jcr.script.JcrScriptExecutorExtension.java

@Route(method = HttpMethod.GET, uri = "")
public Result index() throws Exception {
    Session session = jcrRepository.getSession();
    Optional<String> currentMigrationWorkspaceOptional = Arrays
            .asList(session.getWorkspace().getAccessibleWorkspaceNames()).stream()
            .filter(name -> name.startsWith(JCR_MIGRATION_PREFIX)).findFirst();
    String workspace = "";
    String script = "";
    List<Event> events = new ArrayList<>();
    if (currentMigrationWorkspaceOptional.isPresent()) {
        workspace = currentMigrationWorkspaceOptional.get();
        Node rootNode = session.getRepository().login(workspace).getRootNode();
        if (rootNode.hasNode("jcr:migrations")) {
            Node migrationNode = rootNode.getNode("jcr:migrations").getNode(workspace);
            script = migrationNode.getProperty("script").getString();
            ObjectMapper mapper = new ObjectMapper();
            SimpleModule module = new SimpleModule();
            module.addDeserializer(Event.class, new JcrEventDeserializer());
            mapper.registerModule(module);
            events = mapper.readValue(migrationNode.getProperty("events").getString(),
                    mapper.getTypeFactory().constructCollectionType(List.class, Event.class));
        }/*from   w  ww .ja v  a 2 s .  c o  m*/
    }
    return ok(render(scriptTemplate, "script", script, "workspace", workspace, "events", events,
            "eventFormatter", EVENT_FORMATTER));
}

From source file:com.aba.industry.manufacturing.impl.ManufacturingCalculatorImplUnitTests.java

@Test
public void testSleipnirBuildCosts() throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    InputStream bpDetailsIS = InventionCalculatorImplUnitTests.class
            .getResourceAsStream("/testSleipnirWithNullDecryptor-BlueprintDetails.json");
    InputStream costIndexesIS = InventionCalculatorImplUnitTests.class
            .getResourceAsStream("/testSleipnirWithNullDecryptor-CostIndexes.json");
    InputStream itemCostIS = InventionCalculatorImplUnitTests.class
            .getResourceAsStream("/testSleipnirWithNullDecryptor-ItemCosts.json");

    TypeFactory typeFactory = mapper.getTypeFactory();
    MapType mapType = typeFactory.constructMapType(HashMap.class, Integer.class, ItemCost.class);

    Map<Integer, ItemCost> itemCosts = mapper.readValue(itemCostIS, mapType);

    SystemCostIndexes costIndexes = mapper.readValue(costIndexesIS, SystemCostIndexes.class);
    BlueprintData bpData = mapper.readValue(bpDetailsIS, BlueprintData.class);

    IndustrySkillConfiguration industrySkills = new IndustrySkillConfiguration();

    industrySkills.setAdvancedIndustrySkillLevel(5);
    industrySkills.setIndustrySkillLevel(5);
    industrySkills.setPreference(ConfigurationType.EXCEPTIONAL);

    for (ActivityMaterialWithCost am : bpData.getActivityMaterials()
            .get(IndustryActivities.MANUFACTURING.getActivityId())) {
        ItemCost ic = itemCosts.get(am.getTypeId().intValue());

        am.setCost(ic.getSell());/*  w  w w .  j a v  a 2  s  .c  o  m*/
        am.setAdjustedCost(ic.getAdjusted());
    }

    BuildCalculationResult result = calc.calculateBuildCost(costIndexes, 1d, bpData, 2, 4, industrySkills);

    Assert.assertEquals(312429715.96, result.getMaterialCost(), 0.01);
    Assert.assertEquals(20036519.59, result.getInstallationFees(), 0.01);
    Assert.assertEquals(2003651.95, result.getInstallationTax(), 0.01);
    Assert.assertEquals(result.getProductId(), 22444l);
}

From source file:com.aba.industry.invention.impl.InventionCalculatorImplUnitTests.java

@Test
public void testSleipnirWithNullDecryptor() throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    InputStream bpDetailsIS = InventionCalculatorImplUnitTests.class
            .getResourceAsStream("/testSleipnirWithNullDecryptor-BlueprintDetails.json");
    InputStream costIndexesIS = InventionCalculatorImplUnitTests.class
            .getResourceAsStream("/testSleipnirWithNullDecryptor-CostIndexes.json");
    InputStream itemCostIS = InventionCalculatorImplUnitTests.class
            .getResourceAsStream("/testSleipnirWithNullDecryptor-ItemCosts.json");

    TypeFactory typeFactory = mapper.getTypeFactory();
    MapType mapType = typeFactory.constructMapType(HashMap.class, Integer.class, ItemCost.class);

    Map<Integer, ItemCost> itemCosts = mapper.readValue(itemCostIS, mapType);

    SystemCostIndexes costIndexes = mapper.readValue(costIndexesIS, SystemCostIndexes.class);
    BlueprintData bpData = mapper.readValue(bpDetailsIS, BlueprintData.class);
    Decryptor decryptor = null;//from w w w.  j a  va  2 s  . co  m
    InventionSkillConfiguration skillConfiguration = new InventionSkillConfiguration();

    skillConfiguration.setDatacoreOneSkillLevel(3);
    skillConfiguration.setDatacoreTwoSkillLevel(3);
    skillConfiguration.setEncryptionSkillLevel(4);

    for (ActivityMaterialWithCost am : bpData.getActivityMaterials()
            .get(IndustryActivities.INVENTION.getActivityId())) {
        ItemCost ic = itemCosts.get(am.getTypeId().intValue());

        am.setCost(ic.getSell());
        am.setAdjustedCost(ic.getAdjusted());
    }

    for (ActivityMaterialWithCost am : bpData.getActivityMaterials()
            .get(IndustryActivities.MANUFACTURING.getActivityId())) {
        ItemCost ic = itemCosts.get(am.getTypeId().intValue());

        am.setCost(ic.getSell());
        am.setAdjustedCost(ic.getAdjusted());
    }

    InventionCalculationResult result = calcImpl.calculateInventionCosts(costIndexes, 0.0d, bpData, decryptor,
            skillConfiguration);

    Assert.assertNotNull("Result should not be null", result);
    Assert.assertEquals(6808205.92, result.getCostPerSuccessfulInventionRun(), 0.01);
}