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

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

Introduction

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

Prototype

@SuppressWarnings("unchecked")
    public <T> T readValue(byte[] src, JavaType valueType)
            throws IOException, JsonParseException, JsonMappingException 

Source Link

Usage

From source file:com.mobius.software.mqtt.performance.runner.util.RequestFormatter.java

public static List<ScenarioRequest> parseScenarioRequests(String json)
        throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    MultiScenarioData multiScenarioData = mapper.readValue(json, MultiScenarioData.class);
    if (!multiScenarioData.validate())
        throw new IllegalArgumentException("JSON file: one of the required fields is missing or invalid");

    List<ScenarioRequest> requests = new ArrayList<>();
    List<ClientController> controllers = multiScenarioData.getControllers();
    for (ClientController controller : controllers) {
        String baseURL = URLBuilder.buildBaseURL(controller.getHostname(), controller.getPort());
        for (ScenarioRequest request : controller.getRequests()) {
            request.updateBaseURL(baseURL);
            Scenario scenario = request.getScenario();
            if (scenario.getId() == null)
                scenario.setId(UUID.randomUUID());
            scenario.getProperties().setIdentifierRegex(controller.getIdentifierRegex());
            scenario.getProperties().setStartIdentifier(controller.getStartIdentifier());
            requests.add(request);/*from   w  ww  .  j  a v  a  2s . co  m*/
        }
    }
    return requests;
}

From source file:org.apache.unomi.itests.TestUtils.java

public static <T> T retrieveResourceFromResponse(HttpResponse response, Class<T> clazz) throws IOException {
    String jsonFromResponse = EntityUtils.toString(response.getEntity());
    ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
            false);//from w w  w.  j a  v  a  2 s  .  c om
    return mapper.readValue(jsonFromResponse, clazz);
}

From source file:com.mgatelabs.bytemapper.support.definitions.FormatDefinition.java

public static FormatDefinition load(InputStream is) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    FormatDefinition def;//ww  w. j av  a  2 s  . co  m
    try {
        def = mapper.readValue(is, FormatDefinition.class);
    } finally {
        is.close();
    }
    def.sanity();
    return def;
}

From source file:de.fionera.javamailer.main.Main.java

/**
 * Loads the Settings from the provided File
 *
 * @param file   The File where the {@link Settings} are saved
 * @param mapper The {@link ObjectMapper} Instance
 *//*from   w  ww.ja v a  2s.c o  m*/
private static void loadSettings(File file, ObjectMapper mapper) {

    Settings settings = new Settings();
    try {
        settings = mapper.readValue(file, Settings.class);
    } catch (IOException e) {
        e.printStackTrace();
    }

    senderList = settings.getSenderList();
    mailserverHostname = settings.getMailserverHostname();
    mailserverUsername = settings.getMailserverUsername();
    mailserverPassword = settings.getMailserverPassword();
    mailerServerCheckCertificate = settings.isMailerServerCheckCertificate();
    mailserverUseTLS = settings.isMailserverUseTLS();
    mailserverUseSSL = settings.isMailserverUseSSL();
    mailserverPort = settings.getMailserverPort();
    delayMails = settings.getDelayMails();
    amountMails = settings.getAmountMails();
}

From source file:com.krj.karbon.GetFriendsList.java

public static List<SteamAccount> retrieve(String steamId) {
    String urlString = "";
    List<SteamAccount> friends = new ArrayList();
    try {//  w w w  .  j a va  2s.  c  o  m
        //http://api.steampowered.com/ISteamUser/GetFriendList/v0001/?key=06326BE3F53F72F8C6EF31C158FBACD7&steamid=76561197976892493&relationship=all
        String host = "http://api.steampowered.com/";
        String path = "ISteamUser/GetFriendList/v0001/";
        String key = "?key=06326BE3F53F72F8C6EF31C158FBACD7";
        String id = "&steamid=" + steamId;
        String relationship = "&relationship=all";
        urlString = host + path + key + id + relationship;

        URL url = new URL(urlString);

        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> JSONMap = mapper.readValue(url, Map.class);

        Map response = (Map) JSONMap.get("friendslist");

        if (response != null) {
            List<Map> friendMaps = (List<Map>) response.get("friends");
            if (friendMaps != null) {
                for (Map map : friendMaps) {

                    String steamid = (String) map.get("steamid");
                    SteamAccount friend = GetPlayerSummaries.retrieve(steamid);

                    friend.getOwnedGames();
                    friends.add(friend);
                }
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(GetOwnedGames.class.getName()).log(Level.SEVERE, null, ex);
    }

    return friends;
}

From source file:org.envirocar.analyse.util.Utils.java

public static Map<?, ?> parseJsonStream(InputStream stream) throws IOException {
    ObjectMapper om = new ObjectMapper();
    final Map<?, ?> json = om.readValue(stream, Map.class);
    return json;// w w  w .  j a  v  a 2  s .  co m
}

From source file:me.qisthi.cuit.helper.StorageHelper.java

public static List<String[]> readPreferenceStatusValue(Activity activity, String key) throws Exception {
    SharedPreferences sharedPreferences = activity.getPreferences(Context.MODE_PRIVATE);
    String jsonValue = sharedPreferences.getString(key, null);

    List<String[]> statuses;

    if (jsonValue != null) {
        ObjectMapper mapper = new ObjectMapper();
        statuses = mapper.readValue(jsonValue, new TypeReference<List<String[]>>() {
        });/*from  w ww .  j a v  a 2s  .  c  o  m*/

        return statuses;
    }
    return null;
}

From source file:org.hdl.tensorflow.yarn.appmaster.ClusterSpec.java

public static ClusterSpec fromJsonString(String json) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    return new ClusterSpec(objectMapper.readValue(json, Map.class));
}

From source file:com.brett.http.geo.baidu.GeoRequestHttpClient.java

public static JsonNode geoAcquire(String city) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    //    DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
    //    httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
    try {/* www  .ja  va 2 s .c o  m*/

        String address = URLEncoder.encode(city, "utf-8");

        String url = "http://api.map.baidu.com/geocoder/v2/?address={address}&output=json&ak=E4805d16520de693a3fe707cdc962045";

        url = url.replaceFirst("\\{address\\}", address);

        HttpGet httpget = new HttpGet(url);
        httpget.setHeader("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        httpget.setHeader("Accept-Encoding", "gzip, deflate, sdch");
        httpget.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
        httpget.setHeader("Cache-Control", "no-cache");
        httpget.setHeader("Connection", "keep-alive");
        httpget.setHeader("Referer",
                "http://developer.baidu.com/map/index.php?title=webapi/guide/webservice-geocoding");
        httpget.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36");

        System.out.println("Executing request httpget.getRequestLine() " + httpget.getRequestLine());

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity, "utf-8") : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }

        };
        String responseBody = httpclient.execute(httpget, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(HtmlDecoder.decode(responseBody));
        System.out.println(responseBody);

        System.out.println("----------------------------------------");

        ObjectMapper mapper = new ObjectMapper();
        mapper.readValue(responseBody, AddressCoord.class);
        //      JsonNode root = mapper.readTree(responseBody.substring("showLocation&&showLocation(".length(), responseBody.length()-1));

        // {"status":0,"result":{"location":{"lng":116.30783584945,"lat":40.056876296398},"precise":1,"confidence":80,"level":"\u5546\u52a1\u5927\u53a6"}}
        JsonNode root = mapper.readTree(responseBody);

        System.out.println("result : " + city + " = " + root.get("result"));

        return root;

    } finally {
        httpclient.close();
    }
}

From source file:com.codenvy.eclipse.core.CodenvyProjectDescriptor.java

public static CodenvyProjectDescriptor load(IProject project) {
    final IFile projectDescriptor = project.getFolder(CODENVY_FOLDER_NAME)
            .getFile(PROJECT_DESCRIPTOR_FILE_NAME);
    if (projectDescriptor.exists()) {
        final ObjectMapper mapper = new ObjectMapper();
        try {//from   w  ww.  j a  v a2  s.c  o  m

            return mapper.readValue(projectDescriptor.getContents(), CodenvyProjectDescriptor.class);

        } catch (IOException | CoreException e) {
            throw new RuntimeException(e);
        }
    }
    return null;
}