Пример #1
0
 void handleRequest(InputStream in, OutputStream out) throws IOException {
   boolean newline = false;
   StringBuilder sb = new StringBuilder();
   while (true) {
     int ch = in.read();
     if (ch < 0) {
       throw new EOFException();
     }
     sb.append((char) ch);
     if (ch == '\r') {
       // empty
     } else if (ch == '\n') {
       if (newline) {
         // 2nd newline in a row, end of request
         break;
       }
       newline = true;
     } else {
       newline = false;
     }
   }
   String request = sb.toString();
   if (request.startsWith("GET / HTTP/1.") == false) {
     throw new IOException("Invalid request: " + request);
   }
   out.write("HTTP/1.0 200 OK\r\n\r\n".getBytes());
 }
Пример #2
0
 private <T> JsonResponse<T> commandResponse(String command, Type type) throws Exception {
   URI uri = this.getServerUri(command);
   //		URI uri = new URI( serverUri.toString() + URLEncoder.encode(command) );
   HttpURLConnection server = null;
   if (https) {
     server = (HttpsURLConnection) uri.toURL().openConnection();
   } else {
     server = (HttpURLConnection) uri.toURL().openConnection();
   }
   server.setConnectTimeout(30000);
   BufferedReader reader = new BufferedReader(new InputStreamReader(server.getInputStream()));
   // TypeToken cannot figure out T so instead it must be supplied
   // Type type = new TypeToken< JSONResponse<T> >() {}.getType();
   GsonBuilder build = new GsonBuilder();
   StringBuilder sBuild = new StringBuilder();
   String input;
   while ((input = reader.readLine()) != null) sBuild.append(input);
   reader.close();
   input = sBuild.toString();
   build.registerTypeAdapter(JsonBoolean.class, new JsonBooleanDeserializer());
   JsonResponse<T> response = null;
   try {
     response = build.create().fromJson(input, type);
     tryExtractError(response);
     return response;
   } catch (Exception e) {
     // well something messed up
     // if this part messes up then something REALLY bad happened
     response = build.create().fromJson(input, new TypeToken<JsonResponse<Object>>() {}.getType());
     tryExtractError(response);
     // DO NOT RETURN AN ACTUAL OBJECT!!!!!
     // this makes the code in the UI confused
     return null;
   }
 }
 @Override
 public String toString() {
   final StringBuilder sb = new StringBuilder("SSLSocketChannelWrapper{");
   sb.append("socketChannel=").append(socketChannel);
   sb.append('}');
   return sb.toString();
 }
Пример #4
0
  public static String getJSON(URL url, int timeout) {
    try {

      HttpURLConnection c = (HttpURLConnection) url.openConnection();

      c.setRequestMethod("GET");
      c.setRequestProperty("Content-length", "0");
      c.setUseCaches(false);
      c.setAllowUserInteraction(false);
      c.setConnectTimeout(timeout);
      c.setReadTimeout(timeout);
      c.connect();
      int status = c.getResponseCode();

      switch (status) {
        case 200:
        case 201:
          BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
          StringBuilder sb = new StringBuilder();
          String line;
          while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
          }
          br.close();
          return sb.toString();
      }

    } catch (Exception ex) {
      Logger.getLogger("").log(Level.SEVERE, null, ex);
    }
    return null;
  }
Пример #5
0
  public ArrayList<String> exceptions(String tvdbid) throws Exception {
    StringBuilder builder = new StringBuilder("exceptions");
    builder.append("&tvdbid=");
    builder.append(tvdbid);

    return this.<ArrayList<String>>commandData(
        builder.toString(), new TypeToken<JsonResponse<ArrayList<String>>>() {}.getType());
  }
Пример #6
0
  public boolean showUpdate(String tvdbid) throws Exception {
    StringBuilder builder = new StringBuilder("show.update");
    builder.append("&tvdbid=");
    builder.append(tvdbid);

    return this.<Object>commandSuccessful(
        builder.toString(), new TypeToken<JsonResponse<Object>>() {}.getType());
  }
Пример #7
0
  public Show show(String tvdbid) throws Exception {
    StringBuilder builder = new StringBuilder("show");
    builder.append("&tvdbid=");
    builder.append(tvdbid);

    return new Show(
        this.<ShowJson>commandData(
            builder.toString(), new TypeToken<JsonResponse<ShowJson>>() {}.getType()));
  }
Пример #8
0
 public History history(int limit) throws Exception {
   StringBuilder builder = new StringBuilder("history");
   builder.append("&limit=");
   builder.append(limit);
   ArrayList<HistoryJson> result =
       this.<ArrayList<HistoryJson>>commandData(
           builder.toString(), new TypeToken<JsonResponse<ArrayList<HistoryJson>>>() {}.getType());
   return new History(result);
 }
Пример #9
0
  public CacheStatus showCache(String tvdbid) throws Exception {
    StringBuilder builder = new StringBuilder("show.cache");
    builder.append("&tvdbid=");
    builder.append(tvdbid);

    return new CacheStatus(
        this.<CacheStatusJson>commandData(
            builder.toString(), new TypeToken<JsonResponse<CacheStatusJson>>() {}.getType()));
  }
Пример #10
0
 private static String toHexString(byte[] bytes) {
   StringBuilder sb = new StringBuilder(bytes.length * 3);
   for (int b : bytes) {
     b &= 0xff;
     sb.append(HEXDIGITS[b >> 4]);
     sb.append(HEXDIGITS[b & 15]);
     sb.append(' ');
   }
   return sb.toString();
 }
Пример #11
0
  public List<Integer> showSeasonList(String tvdbid) throws Exception {
    StringBuilder builder = new StringBuilder("show.seasonlist");
    builder.append("&tvdbid=");
    builder.append(tvdbid);

    ArrayList<Integer> result =
        this.<ArrayList<Integer>>commandData(
            builder.toString(), new TypeToken<JsonResponse<ArrayList<Integer>>>() {}.getType());

    return result;
  }
Пример #12
0
  public GetQuality showGetQuality(String tvdbid) throws Exception {
    StringBuilder builder = new StringBuilder("show.getquality");
    builder.append("&tvdbid=");
    builder.append(tvdbid);

    GetQualityJson result =
        this.<GetQualityJson>commandData(
            builder.toString(), new TypeToken<JsonResponse<GetQualityJson>>() {}.getType());

    return new GetQuality(result);
  }
Пример #13
0
  public URI showGetPoster(String tvdbid) throws Exception {
    StringBuilder builder = new StringBuilder("show.getposter");
    builder.append("&tvdbid=");
    builder.append(tvdbid);

    //		URI uri = new URI( serverUri.toString() + builder.toString() );
    //		HttpURLConnection server = (HttpURLConnection)uri.toURL().openConnection();
    //		server.connect();
    //		return server.getInputStream();
    return this.getServerUri(builder.toString());
  }
Пример #14
0
 public boolean episodeSetStatus(String tvdbid, String season, String episode, Status status)
     throws Exception {
   StringBuilder builder = new StringBuilder("episode.setstatus");
   builder.append("&tvdbid=");
   builder.append(tvdbid);
   builder.append("&season=");
   builder.append(season);
   builder.append("&episode=");
   builder.append(episode);
   builder.append("&status=");
   builder.append(status.toJson());
   return this.<Object>commandSuccessful(
       builder.toString(), new TypeToken<JsonResponse<Object>>() {}.getType());
 }
Пример #15
0
  public List<Season> showSeasons(String tvdbid) throws Exception {
    StringBuilder builder = new StringBuilder("show.seasons");
    builder.append("&tvdbid=");
    builder.append(tvdbid);

    SeasonsListJson result =
        this.<SeasonsListJson>commandData(
            builder.toString(), new TypeToken<JsonResponse<SeasonsListJson>>() {}.getType());
    List<Season> ret = new ArrayList<Season>();
    for (Map.Entry<String, SeasonsJson> entry : result.entrySet()) {
      ret.add(new Season(entry.getKey(), entry.getValue()));
    }
    return ret;
  }
Пример #16
0
 public Logs logs(Logs.LevelEnum minLevel) throws Exception {
   StringBuilder builder = new StringBuilder("logs");
   builder.append("&min_level=");
   switch (minLevel) {
     case DEBUG:
       builder.append("debug");
       break;
     case INFO:
       builder.append("info");
       break;
     case WARNING:
       builder.append("warning");
       break;
     case ERROR:
       builder.append("error");
       break;
     default:
       builder.append("error");
       break;
   }
   ArrayList<String> result =
       this.<ArrayList<String>>commandData(
           builder.toString(), new TypeToken<JsonResponse<ArrayList<String>>>() {}.getType());
   return new Logs(result);
 }
Пример #17
0
 public Episode episode(String tvdbid, String season, String episode, boolean full_path)
     throws Exception {
   StringBuilder builder = new StringBuilder("episode");
   builder.append("&tvdbid=");
   builder.append(tvdbid);
   builder.append("&season=");
   builder.append(season);
   builder.append("&episode=");
   builder.append(episode);
   builder.append("&full_path=");
   builder.append((full_path ? "1" : "0"));
   EpisodeJson json =
       this.<EpisodeJson>commandData(
           builder.toString(), new TypeToken<JsonResponse<EpisodeJson>>() {}.getType());
   return new Episode(json);
 }
Пример #18
0
 void sendRequest(InputStream in, OutputStream out) throws IOException {
   out.write("GET / HTTP/1.0\r\n\r\n".getBytes());
   out.flush();
   StringBuilder sb = new StringBuilder();
   while (true) {
     int ch = in.read();
     if (ch < 0) {
       break;
     }
     sb.append((char) ch);
   }
   String response = sb.toString();
   if (response.startsWith("HTTP/1.0 200 ") == false) {
     throw new IOException("Invalid response: " + response);
   }
 }
Пример #19
0
  public FutureEpisodes future(FutureEpisodes.SortEnum sort) throws Exception {
    StringBuilder builder = new StringBuilder("future");
    builder.append("&sort=");
    switch (sort) {
      case DATE:
        builder.append("date");
        break;
      case NETWORK:
        builder.append("network");
        break;
      case NAME:
        builder.append("name");
        break;
      default:
        builder.append("date");
    }

    FutureEpisodes ret =
        this.<FutureEpisodes>commandData(
            builder.toString(), new TypeToken<JsonResponse<FutureEpisodes>>() {}.getType());
    for (FutureEpisode ep : ret.missed) {
      ep.when = TimeEnum.MISSED;
    }
    for (FutureEpisode ep : ret.today) {
      ep.when = TimeEnum.TODAY;
    }
    for (FutureEpisode ep : ret.soon) {
      ep.when = TimeEnum.SOON;
    }
    for (FutureEpisode ep : ret.later) {
      ep.when = TimeEnum.LATER;
    }
    return ret;
  }
Пример #20
0
  public Show show(String tvdbid, boolean fullSeasonListing) throws Exception {
    if (fullSeasonListing) {
      StringBuilder builder = new StringBuilder("show|show.seasons");
      builder.append("&tvdbid=");
      builder.append(tvdbid);

      ShowWithFullSeasonListing results =
          this.<ShowWithFullSeasonListing>commandData(
              builder.toString(),
              new TypeToken<JsonResponse<ShowWithFullSeasonListing>>() {}.getType());
      Show ret = new Show(results.show.data);
      ret.seasonList.clear();
      for (Map.Entry<String, SeasonsJson> season : results.seasons.data.entrySet()) {
        ret.seasonList.add(new Season(season.getKey(), season.getValue()));
      }
      return ret;
    } else {
      return show(tvdbid);
    }
  }
Пример #21
0
 public boolean showPause(String[] tvdbids, Boolean pause) throws Exception {
   StringBuilder builder = new StringBuilder();
   for (int i = 0; i < tvdbids.length; i++) {
     builder.append("show.pause_");
     builder.append(i);
     if (i < tvdbids.length - 1) builder.append("|");
   }
   for (int i = 0; i < tvdbids.length; i++) {
     builder.append("&show.pause_");
     builder.append(i);
     builder.append(".tvdbid=");
     builder.append(tvdbids[i]);
   }
   if (pause != null) {
     builder.append("&pause=");
     builder.append(pause ? "1" : "0");
   }
   return this.<Object>commandSuccessful(
       builder.toString(), new TypeToken<JsonResponse<Object>>() {}.getType());
 }
Пример #22
0
  private static String getRequest(HttpURLConnection connection, String data, String encoding) {
    PrintStream out = null;
    InputStream in = null;
    StringBuilder sb = new StringBuilder(1024);
    String result = "";
    try {
      connection.connect();
      out = new PrintStream(connection.getOutputStream(), false, encoding);
      out.print(data);
      out.flush();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      out.close();
    }

    try {
      if (200 == connection.getResponseCode()) {
        in = connection.getInputStream();
        sb.append(IOUtils.toString(in, encoding));
      } else {
        in = connection.getErrorStream();
        sb.append(IOUtils.toString(in, encoding));
      }
      result = sb.toString();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        in.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      if (null != connection) {
        connection.disconnect();
      }
    }

    return result;
  }
Пример #23
0
 public boolean showRefresh(String[] tvdbids) throws Exception {
   StringBuilder builder = new StringBuilder();
   for (int i = 0; i < tvdbids.length; i++) {
     builder.append("show.refresh_");
     builder.append(i);
     if (i < tvdbids.length - 1) builder.append("|");
   }
   for (int i = 0; i < tvdbids.length; i++) {
     builder.append("&show.refresh_");
     builder.append(i);
     builder.append(".tvdbid=");
     builder.append(tvdbids[i]);
   }
   return this.<Object>commandSuccessful(
       builder.toString(), new TypeToken<JsonResponse<Object>>() {}.getType());
 }
Пример #24
0
  public boolean showPause(String tvdbid, Boolean pause) throws Exception {
    StringBuilder builder = new StringBuilder("show.pause");
    builder.append("&tvdbid=");
    builder.append(tvdbid);
    if (pause != null) {
      builder.append("&pause=");
      builder.append(pause ? "1" : "0");
    }

    return this.<Object>commandSuccessful(
        builder.toString(), new TypeToken<JsonResponse<Object>>() {}.getType());
  }
Пример #25
0
  public Season showSeasons(String tvdbid, String season) throws Exception {
    StringBuilder builder = new StringBuilder("show.seasons");
    builder.append("&tvdbid=");
    builder.append(tvdbid);
    builder.append("&season=");
    builder.append(season);

    SeasonsJson result =
        this.<SeasonsJson>commandData(
            builder.toString(), new TypeToken<JsonResponse<SeasonsJson>>() {}.getType());
    return new Season(season, result);
  }
Пример #26
0
 public SearchResults sbSearchTvDb(String query, Language language) throws Exception {
   StringBuilder builder = new StringBuilder("sb.searchtvdb");
   builder.append("&name=");
   builder.append(query);
   if (language != null) {
     builder.append("&lang=");
     builder.append(language.getAbbrev());
   }
   // having to use all these generics is kind of annoying
   TvDbResultsJson results =
       this.<TvDbResultsJson>commandData(
           builder.toString(), new TypeToken<JsonResponse<TvDbResultsJson>>() {}.getType());
   SearchResults ret = new SearchResults();
   for (TvDbResultJson json : results.results) { // lol results of results :)
     ret.results.add(new SearchResultTvDb(json));
   }
   return ret;
 }
Пример #27
0
  public String executeAPI(
      String jSON,
      String apiUrl,
      String url,
      boolean requireAuth,
      String user,
      String password,
      String requestMethod,
      BuildListener listener,
      boolean dynamicUserId,
      String buildID,
      int buildNumber,
      String workPlacePath,
      int connConnTimeOut,
      int connReadTimeout,
      boolean advConfig)
      throws Exception {

    try {

      boolean notInTestMode = true;
      if (listener == null) {
        notInTestMode = false;
      }

      String apiURL = url + "/rest" + apiUrl;

      if (notInTestMode) {
        listener
            .getLogger()
            .print("vManager vAPI - Trying to call vAPI '" + "/rest" + apiUrl + "'\n");
      }
      String input = jSON;
      HttpURLConnection conn =
          getVAPIConnection(
              apiURL,
              requireAuth,
              user,
              password,
              requestMethod,
              dynamicUserId,
              buildID,
              buildNumber,
              workPlacePath,
              listener,
              connConnTimeOut,
              connReadTimeout,
              advConfig);

      if ("PUT".equals(requestMethod) || "POST".equals(requestMethod)) {
        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();
      }

      if (conn.getResponseCode() != HttpURLConnection.HTTP_OK
          && conn.getResponseCode() != HttpURLConnection.HTTP_NO_CONTENT
          && conn.getResponseCode() != HttpURLConnection.HTTP_ACCEPTED
          && conn.getResponseCode() != HttpURLConnection.HTTP_CREATED
          && conn.getResponseCode() != HttpURLConnection.HTTP_PARTIAL
          && conn.getResponseCode() != HttpURLConnection.HTTP_RESET) {
        String reason = "";
        if (conn.getResponseCode() == 503)
          reason = "vAPI process failed to connect to remote vManager server.";
        if (conn.getResponseCode() == 401) reason = "Authentication Error";
        if (conn.getResponseCode() == 415)
          reason =
              "The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.  Check if you selected the right request method (GET/POST/DELETE/PUT).";
        if (conn.getResponseCode() == 405)
          reason =
              "The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource.  Check if you selected the right request method (GET/POST/DELETE/PUT).";
        if (conn.getResponseCode() == 412)
          reason = "vAPI requires vManager 'Integration Server' license.";
        String errorMessage =
            "Failed : HTTP error code : " + conn.getResponseCode() + " (" + reason + ")\n";
        if (notInTestMode) {
          listener.getLogger().print(errorMessage);
        }

        System.out.println(errorMessage);
        return errorMessage;
      }

      BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

      StringBuilder result = new StringBuilder();
      String output;
      while ((output = br.readLine()) != null) {
        result.append(output);
      }

      conn.disconnect();

      // Flush the output into workspace
      String fileOutput =
          workPlacePath + File.separator + buildNumber + "." + buildID + ".vapi.output";

      FileWriter writer = new FileWriter(fileOutput);

      writer.append(result.toString());
      writer.flush();
      writer.close();

      String textOut = "API Call Success: Output was saved into: " + fileOutput + "\n";

      if (notInTestMode) {
        listener.getLogger().print(textOut);
      } else {

        System.out.println(textOut);
      }

      return "success";

    } catch (Exception e) {
      listener.getLogger().print("Filed: Error: " + e.getMessage());
      return e.getMessage();
    }
  }
Пример #28
0
 public boolean episodeSetStatus(String tvdbid, List<SeasonEpisodePair> episodes, Status status)
     throws Exception {
   StringBuilder builder = new StringBuilder();
   builder.append("episode.setstatus_0");
   for (int i = 1; i < episodes.size(); i++) {
     builder.append("|episode.setstatus_");
     builder.append(i);
   }
   builder.append("&tvdbid=");
   builder.append(tvdbid);
   builder.append("&status=");
   builder.append(status.toJson());
   for (int i = 0; i < episodes.size(); i++) {
     SeasonEpisodePair p = episodes.get(i);
     builder.append("&episode.setstatus_");
     builder.append(i);
     builder.append(".season=");
     builder.append(p.season);
     builder.append("&episode.setstatus_");
     builder.append(i);
     builder.append(".episode=");
     builder.append(p.episode);
   }
   return this.<Object>commandSuccessful(
       builder.toString(), new TypeToken<JsonResponse<Object>>() {}.getType());
 }
Пример #29
0
  public boolean showAddNew(
      String tvdbid,
      Language language,
      Boolean seasonFolders,
      Status status,
      EnumSet<Show.Quality> initial,
      EnumSet<Quality> archive)
      throws Exception {
    StringBuilder builder = new StringBuilder("show.addnew");
    builder.append("&tvdbid=");
    builder.append(tvdbid);
    if (language != null) {
      builder.append("&lang=");
      builder.append(language.getAbbrev());
    }
    if (seasonFolders != null) {
      // the option isnt called season folders anymore
      if (apiVersion >= 3) {
        builder.append("&flatten_folders=");
      } else {
        builder.append("&season_folder=");
      }
      // if you pass me a boolean you better damn well have checked the version number
      builder.append(seasonFolders ? "1" : "0");
    }
    if (status != null) {
      builder.append("&status=");
      builder.append(status.toJson());
    }
    if (initial != null) {
      builder.append("&initial=");
      Iterator<Quality> iter = initial.iterator();
      if (iter.hasNext()) {
        builder.append(iter.next().toString().toLowerCase());
        while (iter.hasNext()) {
          builder.append("|");
          builder.append(iter.next().toString().toLowerCase());
        }
      }
    }
    if (archive != null) {
      builder.append("&archive=");
      Iterator<Show.Quality> iter = archive.iterator();
      if (iter.hasNext()) {
        builder.append(iter.next().toString().toLowerCase());
        while (iter.hasNext()) {
          builder.append("|");
          builder.append(iter.next().toString().toLowerCase());
        }
      }
    }

    return this.<Object>commandSuccessful(
        builder.toString(), new TypeToken<JsonResponse<Object>>() {}.getType());
  }
Пример #30
0
  public boolean showSetQuality(
      String tvdbid, EnumSet<Show.Quality> initial, EnumSet<Show.Quality> archive)
      throws Exception {
    StringBuilder builder = new StringBuilder("show.setquality");
    builder.append("&tvdbid=");
    builder.append(tvdbid);
    if (initial != null) {
      builder.append("&initial=");
      Iterator<Quality> iter = initial.iterator();
      if (iter.hasNext()) {
        builder.append(iter.next().toString().toLowerCase());
        while (iter.hasNext()) {
          builder.append("|");
          builder.append(iter.next().toString().toLowerCase());
        }
      }
    }
    if (archive != null) {
      builder.append("&archive=");
      Iterator<Quality> iter = archive.iterator();
      if (iter.hasNext()) {
        builder.append(iter.next().toString().toLowerCase());
        while (iter.hasNext()) {
          builder.append("|");
          builder.append(iter.next().toString().toLowerCase());
        }
      }
    }

    return this.<Object>commandSuccessful(
        builder.toString(), new TypeToken<JsonResponse<Object>>() {}.getType());
  }