Package br.com.mutley.repository

Source Code of br.com.mutley.repository.CoderConnection

package br.com.mutley.repository;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.MessageFormat;

import br.com.mutley.data.Coder;
import br.com.mutley.exception.CoderWallException;

import com.google.gson.Gson;

public class CoderConnection {

  // Initialize with invalid content.
  private String jsonContent = "jasidjfi";

  public CoderConnection(String coderName) throws CoderWallException {
    URL url = null;
    BufferedReader buffer = null;
    try {
      url = new URL(getUrlAddress(coderName));
      InputStreamReader reader = new InputStreamReader(url.openStream());
      buffer = new BufferedReader(reader);

      jsonContent = buffer.readLine();

    } catch (MalformedURLException e) {

      sendErrorMessage(e.getMessage());

    } catch (FileNotFoundException e) {

      sendErrorMessage("User does not exists");

    } catch (IOException e) {

      sendErrorMessage(e.getMessage());

    } finally {
      try {

        if (buffer != null) {
          buffer.close();
        }

      } catch (IOException e) {

        sendErrorMessage(e.getMessage());

      }
    }

  }

  private void sendErrorMessage(String message) throws CoderWallException {
    throw new CoderWallException(message);
  }

  private String getUrlAddress(String coderName) {
    return MessageFormat
        .format("https://coderwall.com/{0}.json", coderName);
  }

  public Coder getCoder() {
    return new Gson().fromJson(jsonContent, Coder.class);
  }

}
TOP

Related Classes of br.com.mutley.repository.CoderConnection

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.