Exemplo n.º 1
1
  private String getResult(String URL, HashMap optionalParameters) {
    StringBuilder sb = new StringBuilder();
    sb.append(URL);
    try {

      Iterator iterator = optionalParameters.keySet().iterator();

      int index = 0;
      while (iterator.hasNext()) {
        if (index == 0) {
          sb.append("?");
        } else {
          sb.append("&");
        }
        String key = (String) iterator.next();
        sb.append(key);
        sb.append("=");
        sb.append(URLEncoder.encode(optionalParameters.get(key).toString(), "UTF-8"));
        index++;
      }

      URI uri = new URI(String.format(sb.toString()));
      URL url = uri.toURL();

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

      conn.setRequestMethod("GET");
      conn.setRequestProperty("Accept", "application/json");
      conn.setRequestProperty("Authorization", "Bearer " + getAccessToken());
      if (conn.getResponseCode() != 200) {
        throw new RuntimeException(
            "Failed : HTTP error code : "
                + conn.getResponseCode()
                + " - "
                + conn.getResponseMessage());
      }

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

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

      conn.disconnect();

    } catch (IOException e) {

      e.printStackTrace();
      return null;
    } catch (URISyntaxException e) {
      e.printStackTrace();
      return null;
    }
    return sb.toString();
  }
Exemplo n.º 2
0
 private void downloadInternal(URI address, File destination) throws Exception {
   OutputStream out = null;
   URLConnection conn;
   InputStream in = null;
   try {
     URL url = address.toURL();
     out = new BufferedOutputStream(new FileOutputStream(destination));
     conn = url.openConnection();
     final String userAgentValue = calculateUserAgent();
     conn.setRequestProperty("User-Agent", userAgentValue);
     in = conn.getInputStream();
     byte[] buffer = new byte[BUFFER_SIZE];
     int numRead;
     long progressCounter = 0;
     while ((numRead = in.read(buffer)) != -1) {
       progressCounter += numRead;
       if (progressCounter / PROGRESS_CHUNK > 0) {
         System.out.print(".");
         progressCounter = progressCounter - PROGRESS_CHUNK;
       }
       out.write(buffer, 0, numRead);
     }
   } finally {
     System.out.println("");
     if (in != null) {
       in.close();
     }
     if (out != null) {
       out.close();
     }
   }
 }
Exemplo n.º 3
0
 void put(final URI uri, ArtifactData data) throws Exception {
   reporter.trace("put %s %s", uri, data);
   File tmp = createTempFile(repoDir, "mtp", ".whatever");
   tmp.deleteOnExit();
   try {
     copy(uri.toURL(), tmp);
     byte[] sha = SHA1.digest(tmp).digest();
     reporter.trace("SHA %s %s", uri, Hex.toHexString(sha));
     ArtifactData existing = get(sha);
     if (existing != null) {
       reporter.trace("existing");
       xcopy(existing, data);
       return;
     }
     File meta = new File(repoDir, Hex.toHexString(sha) + ".json");
     File file = new File(repoDir, Hex.toHexString(sha));
     rename(tmp, file);
     reporter.trace("file %s", file);
     data.file = file.getAbsolutePath();
     data.sha = sha;
     data.busy = false;
     CommandData cmddata = parseCommandData(data);
     if (cmddata.bsn != null) {
       data.name = cmddata.bsn + "-" + cmddata.version;
     } else data.name = Strings.display(cmddata.title, cmddata.bsn, cmddata.name, uri);
     codec.enc().to(meta).put(data);
     reporter.trace("TD = " + data);
   } finally {
     tmp.delete();
     reporter.trace("puted %s %s", uri, data);
   }
 }
Exemplo n.º 4
0
  public static int loadURIResource(URI uri, CPU cpu, int addr) {
    int i;

    System.out.println("loadURL: " + uri.toString());

    try {
      DataInputStream s = new DataInputStream(new BufferedInputStream(uri.toURL().openStream()));

      i = 0;
      try {
        while (true) {
          cpu.write8_a32(addr + i, s.readByte());
          i++;
        }
      } catch (EOFException e) {
        // end
      }
    } catch (IOException e) {
      e.printStackTrace(System.err);
      throw new IllegalArgumentException(e);
    }

    System.out.printf("loadURL: '%s' done, %dbytes.\n", uri.toString(), i);

    return i;
  }
Exemplo n.º 5
0
 static {
   dict = null;
   String wnhome = System.getenv("WNHOME");
   String path =
       (new StringBuilder(String.valueOf(wnhome)))
           .append(File.separator)
           .append("dict")
           .toString();
   System.out.println(
       (new StringBuilder("Path to dictionary:")).append(getWNLocation()).toString());
   URL url = null;
   try {
     File f =
         new File(
             (new StringBuilder(String.valueOf(getWNLocation())))
                 .append(File.separator)
                 .append("dict")
                 .toString());
     URI uri = f.toURI();
     url = uri.toURL();
   } catch (MalformedURLException e) {
     e.printStackTrace();
   }
   dict = new Dictionary(url);
   dict.open();
 }
  protected void fetchHandlebars(String handlebarsName) throws MojoExecutionException {
    String downloadUrl = null;
    URLConnection conn = null;
    try {
      conn = handlebarsDownloadsUri.toURL().openConnection();
      List<GitHubDownloadDto> githubDownloadDtoList =
          JSON.decode(
              conn.getInputStream(),
              (new ArrayList<GitHubDownloadDto>() {}).getClass().getGenericSuperclass());
      for (GitHubDownloadDto githubDownloadDto : githubDownloadDtoList) {
        if (StringUtils.equals(githubDownloadDto.getName(), handlebarsName)) {
          downloadUrl = githubDownloadDto.getHtmlUrl();
        }
      }
    } catch (Exception e) {
      throw new MojoExecutionException("Failure fetch handlebars.", e);
    } finally {
      if (conn != null) {
        ((HttpURLConnection) conn).disconnect();
      }
    }

    conn = null;
    try {
      if (!cacheDir.exists()) {
        FileUtils.forceMkdir(cacheDir);
      }
      conn = new URL(downloadUrl).openConnection();
      if (((HttpURLConnection) conn).getResponseCode() == 302) {
        String location = conn.getHeaderField("Location");
        ((HttpURLConnection) conn).disconnect();
        conn = new URL(location).openConnection();
      }
      LOG.info("Fetch handlebars.js from GitHub (" + conn.getURL() + ")");
      IOUtils.copy(conn.getInputStream(), new FileOutputStream(new File(cacheDir, handlebarsName)));
    } catch (Exception e) {
      throw new MojoExecutionException("Failure fetch handlebars.", e);
    } finally {
      if (conn != null) {
        ((HttpURLConnection) conn).disconnect();
      }
    }
  }
Exemplo n.º 7
0
  private String deleteResult(String URL) {
    StringBuilder sb = new StringBuilder();
    sb.append(URL);
    try {

      URI uri = new URI(String.format(sb.toString()));
      URL url = uri.toURL();

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

      conn.setRequestMethod("DELETE");
      conn.setRequestProperty("Accept", "application/json");
      conn.setRequestProperty("Authorization", "Bearer " + getAccessToken());
      if (conn.getResponseCode() != 204) {
        throw new RuntimeException(
            "Failed : HTTP error code : "
                + conn.getResponseCode()
                + " - "
                + conn.getResponseMessage());
      }

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

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

      conn.disconnect();

    } catch (IOException e) {

      e.printStackTrace();
      return null;
    } catch (URISyntaxException e) {
      e.printStackTrace();
      return null;
    }
    return sb.toString();
  }
Exemplo n.º 8
0
    @Override
    public HTTPResponse call() throws Exception {
      final HttpURLConnection hc = (HttpURLConnection) uri.toURL().openConnection();
      try {
        hc.setDoOutput(true);
        hc.setRequestMethod(method.name());
        hc.setRequestProperty(MimeTypes.CONTENT_TYPE, MimeTypes.APP_XML);
        hc.getOutputStream().write(content);
        hc.getOutputStream().close();

        hc.setReadTimeout(SOCKET_TIMEOUT);
        while (!stop) {
          try {
            return new HTTPResponse(hc.getResponseCode());
          } catch (final SocketTimeoutException e) {
          }
        }
        return null;
      } finally {
        hc.disconnect();
      }
    }
Exemplo n.º 9
0
    @Override
    public HTTPResponse call() throws Exception {
      final HttpURLConnection hc = (HttpURLConnection) uri.toURL().openConnection();
      hc.setReadTimeout(SOCKET_TIMEOUT);
      try {
        while (!stop) {
          try {
            final int code = hc.getResponseCode();

            final InputStream input = hc.getInputStream();
            final ByteList bl = new ByteList();
            for (int i; (i = input.read()) != -1; ) bl.add(i);

            return new HTTPResponse(code, bl.toString());
          } catch (final SocketTimeoutException e) {
          }
        }
        return null;
      } finally {
        hc.disconnect();
      }
    }
Exemplo n.º 10
0
  protected ModuleSource loadFromActualUri(URI uri, URI base, Object validator) throws IOException {
    final URL url = uri.toURL();
    final long request_time = System.currentTimeMillis();
    final URLConnection urlConnection = openUrlConnection(url);
    final URLValidator applicableValidator;
    if (validator instanceof URLValidator) {
      final URLValidator uriValidator = ((URLValidator) validator);
      applicableValidator = uriValidator.appliesTo(uri) ? uriValidator : null;
    } else {
      applicableValidator = null;
    }
    if (applicableValidator != null) {
      applicableValidator.applyConditionals(urlConnection);
    }
    try {
      urlConnection.connect();
      if (applicableValidator != null
          && applicableValidator.updateValidator(
              urlConnection, request_time, urlConnectionExpiryCalculator)) {
        close(urlConnection);
        return NOT_MODIFIED;
      }

      return new ModuleSource(
          getReader(urlConnection),
          getSecurityDomain(urlConnection),
          uri,
          base,
          new URLValidator(uri, urlConnection, request_time, urlConnectionExpiryCalculator));
    } catch (FileNotFoundException e) {
      return null;
    } catch (RuntimeException e) {
      close(urlConnection);
      throw e;
    } catch (IOException e) {
      close(urlConnection);
      throw e;
    }
  }