Esempio n. 1
1
  /**
   * Loads the drawing. By convention this method is invoked on a worker thread.
   *
   * @param progress A ProgressIndicator to inform the user about the progress of the operation.
   * @return The Drawing that was loaded.
   */
  protected Drawing loadDrawing(ProgressIndicator progress) throws IOException {
    Drawing drawing = createDrawing();
    if (getParameter("datafile") != null) {
      URL url = new URL(getDocumentBase(), getParameter("datafile"));
      URLConnection uc = url.openConnection();

      // Disable caching. This ensures that we always request the
      // newest version of the drawing from the server.
      // (Note: The server still needs to set the proper HTTP caching
      // properties to prevent proxies from caching the drawing).
      if (uc instanceof HttpURLConnection) {
        ((HttpURLConnection) uc).setUseCaches(false);
      }

      // Read the data into a buffer
      int contentLength = uc.getContentLength();
      InputStream in = uc.getInputStream();
      try {
        if (contentLength != -1) {
          in = new BoundedRangeInputStream(in);
          ((BoundedRangeInputStream) in).setMaximum(contentLength + 1);
          progress.setProgressModel((BoundedRangeModel) in);
          progress.setIndeterminate(false);
        }
        BufferedInputStream bin = new BufferedInputStream(in);
        bin.mark(512);

        // Read the data using all supported input formats
        // until we succeed
        IOException formatException = null;
        for (InputFormat format : drawing.getInputFormats()) {
          try {
            bin.reset();
          } catch (IOException e) {
            uc = url.openConnection();
            in = uc.getInputStream();
            in = new BoundedRangeInputStream(in);
            ((BoundedRangeInputStream) in).setMaximum(contentLength + 1);
            progress.setProgressModel((BoundedRangeModel) in);
            bin = new BufferedInputStream(in);
            bin.mark(512);
          }
          try {
            bin.reset();
            format.read(bin, drawing, true);
            formatException = null;
            break;
          } catch (IOException e) {
            formatException = e;
          }
        }
        if (formatException != null) {
          throw formatException;
        }
      } finally {
        in.close();
      }
    }
    return drawing;
  }
Esempio n. 2
0
 public void init() {
   try {
     url = new URL(urlStr);
     // 创建一个代理服务器对象
     proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, proxyPort));
     // 使用指定的代理服务器打开连接
     conn = url.openConnection(proxy);
     // 设置超时时长。
     conn.setConnectTimeout(5000);
     scan = new Scanner(conn.getInputStream());
     // 初始化输出流
     ps = new PrintStream("Index.htm");
     while (scan.hasNextLine()) {
       String line = scan.nextLine();
       // 在控制台输出网页资源内容
       System.out.println(line);
       // 将网页资源内容输出到指定输出流
       ps.println(line);
     }
   } catch (MalformedURLException ex) {
     System.out.println(urlStr + "不是有效的网站地址!");
   } catch (IOException ex) {
     ex.printStackTrace();
   }
   // 关闭资源
   finally {
     if (ps != null) {
       ps.close();
     }
   }
 }
 private boolean processURL(URL url, String baseDir, StatusWindow status) throws IOException {
   if (processedLinks.contains(url)) {
     return false;
   } else {
     processedLinks.add(url);
   }
   URLConnection connection = url.openConnection();
   InputStream in = new BufferedInputStream(connection.getInputStream());
   ArrayList list = processPage(in, baseDir, url);
   if ((status != null) && (list.size() > 0)) {
     status.setMaximum(list.size());
   }
   for (int i = 0; i < list.size(); i++) {
     if (status != null) {
       status.setMessage(Utils.trimFileName(list.get(i).toString(), 40), i);
     }
     if ((!((String) list.get(i)).startsWith("RUN"))
         && (!((String) list.get(i)).startsWith("SAVE"))
         && (!((String) list.get(i)).startsWith("LOAD"))) {
       processURL(
           new URL(url.getProtocol(), url.getHost(), url.getPort(), (String) list.get(i)),
           baseDir,
           status);
     }
   }
   in.close();
   return true;
 }
Esempio n. 4
0
 byte[] getJar(String address) {
   // System.out.println("getJar: "+address);
   byte[] data;
   try {
     URL url = new URL(address);
     IJ.showStatus("Connecting to " + IJ.URL);
     URLConnection uc = url.openConnection();
     int len = uc.getContentLength();
     if (IJ.debugMode) IJ.log("Updater (url): " + address + " " + len);
     if (len <= 0) return null;
     String name = address.contains("wsr") ? "daily build (" : "ij.jar (";
     IJ.showStatus("Downloading " + name + IJ.d2s((double) len / 1048576, 1) + "MB)");
     InputStream in = uc.getInputStream();
     data = new byte[len];
     int n = 0;
     while (n < len) {
       int count = in.read(data, n, len - n);
       if (count < 0) throw new EOFException();
       n += count;
       IJ.showProgress(n, len);
     }
     in.close();
   } catch (IOException e) {
     if (IJ.debugMode) IJ.log("" + e);
     return null;
   }
   if (IJ.debugMode) IJ.wait(6000);
   return data;
 }
Esempio n. 5
0
 public void start() throws Exception {
   URL url = new URL("http://localhost:5000/gameInit");
   URLConnection urlCon = url.openConnection();
   GameInitMessage gim = GameInitMessage.parseFrom(urlCon.getInputStream());
   urlCon.getInputStream().close();
   this.properties = new PropertyWrapper(gim);
   gameId = gim.getGameId();
 }
Esempio n. 6
0
  public static void main(String[] args) throws IOException {
    URLConnectionTest u = new URLConnectionTest();

    String urlName = "http://localhost/~huahan/PPServer/index.php/blog/index";
    URL url = new URL(urlName);
    URLConnection connection = url.openConnection();
    connection.connect();

    for (int i = 0; i < 10; i++) u.fun(connection);
  }
  private Permission getPermission(JarFile jarFile) {
    try {
      URLConnection uc = (URLConnection) getConnection(jarFile);
      if (uc != null) return uc.getPermission();
    } catch (IOException ioe) {
      // gulp
    }

    return null;
  }
Esempio n. 8
0
  public void fun(URLConnection connection) {
    try {
      connection.connect();
      // print header fields

      Map<String, List<String>> headers = connection.getHeaderFields();
      for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
        String key = entry.getKey();
        for (String value : entry.getValue()) System.out.println(key + ": " + value);
      }

      // print convenience functions

      System.out.println("----------");
      System.out.println("getContentType: " + connection.getContentType());
      System.out.println("getContentLength: " + connection.getContentLength());
      System.out.println("getContentEncoding: " + connection.getContentEncoding());
      System.out.println("getDate: " + connection.getDate());
      System.out.println("getExpiration: " + connection.getExpiration());
      System.out.println("getLastModifed: " + connection.getLastModified());
      System.out.println("----------");

      Scanner in = new Scanner(connection.getInputStream());

      // print first ten lines of contents

      for (int n = 1; in.hasNextLine() && n <= 10; n++) System.out.println(in.nextLine());
      if (in.hasNextLine()) System.out.println(". . .");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  private void sendFile(InputStream in, URLConnection conn) throws IOException {
    conn.connect();

    OutputStream out = conn.getOutputStream();
    try {
      StreamUtils.copyStream(in, out, IO_BUFFER_SIZE);

    } finally {
      out.close();
    }
  }
Esempio n. 10
0
 public static String readURIToLocalURI(String uri) throws URISyntaxException, IOException {
   final PipelineContext pipelineContext =
       StaticExternalContext.getStaticContext().getPipelineContext();
   final URLConnection urlConnection = new URI(uri).toURL().openConnection();
   InputStream inputStream = null;
   try {
     inputStream = urlConnection.getInputStream();
     return inputStreamToAnyURI(pipelineContext, inputStream, REQUEST_SCOPE);
   } finally {
     if (inputStream != null) inputStream.close();
   }
 }
Esempio n. 11
0
  private TrackerInfo doRequest(
      String announce,
      String infoHash,
      String peerID,
      long uploaded,
      long downloaded,
      long left,
      String event)
      throws IOException {
    String s =
        announce
            + "?info_hash="
            + infoHash
            + "&peer_id="
            + peerID
            + "&port="
            + port
            + "&uploaded="
            + uploaded
            + "&downloaded="
            + downloaded
            + "&left="
            + left
            + ((event != NO_EVENT) ? ("&event=" + event) : "");
    URL u = new URL(s);
    if (Snark.debug >= Snark.INFO) Snark.debug("Sending TrackerClient request: " + u, Snark.INFO);

    URLConnection c = u.openConnection();
    c.connect();
    InputStream in = c.getInputStream();

    if (c instanceof HttpURLConnection) {
      // Check whether the page exists
      int code = ((HttpURLConnection) c).getResponseCode();
      if (code / 100 != 2) // We can only handle 200 OK responses
      throw new IOException(
            "Loading '" + s + "' gave error code " + code + ", it probably doesn't exists");
    }

    TrackerInfo info = new TrackerInfo(in, coordinator.getID(), coordinator.getMetaInfo());
    if (Snark.debug >= Snark.INFO) Snark.debug("TrackerClient response: " + info, Snark.INFO);
    lastRequestTime = System.currentTimeMillis();

    String failure = info.getFailureReason();
    if (failure != null) throw new IOException(failure);

    interval = info.getInterval() * 1000;
    return info;
  }
Esempio n. 12
0
 /**
  * Get the last modification date of an open URLConnection.
  *
  * <p>This handles the (broken at some point in the Java libraries) case of the file: protocol.
  *
  * @return last modified timestamp "as is"
  */
 public static long getLastModified(URLConnection urlConnection) {
   try {
     long lastModified = urlConnection.getLastModified();
     if (lastModified == 0 && "file".equals(urlConnection.getURL().getProtocol()))
       lastModified =
           new File(
                   URLDecoder.decode(
                       urlConnection.getURL().getFile(), STANDARD_PARAMETER_ENCODING))
               .lastModified();
     return lastModified;
   } catch (UnsupportedEncodingException e) {
     // Should not happen as we are using a required encoding
     throw new OXFException(e);
   }
 }
Esempio n. 13
0
 @Override
 protected void finalize() throws Throwable {
   // see http://java.net/jira/browse/JAX_WS-1087
   if (doReset) {
     c.setDefaultUseCaches(true);
   }
 }
Esempio n. 14
0
 public static String sendGet(String url, String params) {
   String result = "";
   BufferedReader in = null;
   try {
     String urlName = url + "?" + params;
     URL realUrl = new URL(urlName);
     URLConnection conn = realUrl.openConnection();
     conn.setRequestProperty("accept", "*/*");
     conn.setRequestProperty("connection", "Keep-Alive");
     conn.setRequestProperty(
         "user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
     conn.connect();
     Map<String, List<String>> map = conn.getHeaderFields();
     for (String key : map.keySet()) {
       System.out.println(key + "--->" + map.get(key));
     }
     in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
     String line;
     while ((line = in.readLine()) != null) {
       result += "\n" + line;
     }
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     try {
       if (in != null) {
         in.close();
       }
     } catch (IOException ex) {
       ex.printStackTrace();
     }
   }
   return result;
 }
Esempio n. 15
0
  // postToRestfulApi -
  // Note: params in the addr field need to be URLEncoded
  private String postToRestfulApi(
      String addr, String data, HttpServletRequest request, HttpServletResponse response) {
    if (localCookie) CookieHandler.setDefault(cm);
    String result = "";
    try {
      URLConnection connection = new URL(API_ROOT + addr).openConnection();
      String cookieVal = getBrowserInfiniteCookie(request);
      if (cookieVal != null) {
        connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
        connection.setDoInput(true);
      }
      connection.setDoOutput(true);
      connection.setRequestProperty("Accept-Charset", "UTF-8");

      // Post JSON string to URL
      OutputStream os = connection.getOutputStream();
      byte[] b = data.getBytes("UTF-8");
      os.write(b);

      // Receive results back from API
      InputStream is = connection.getInputStream();
      result = IOUtils.toString(is, "UTF-8");

      String newCookie = getConnectionInfiniteCookie(connection);
      if (newCookie != null && response != null) {
        setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
      }
    } catch (Exception e) {
      // System.out.println("Exception: " + e.getMessage());
    }
    return result;
  } // TESTED
Esempio n. 16
0
 /**
  * Get the last modification date of a URL.
  *
  * @return last modified timestamp "as is"
  */
 public static long getLastModified(URL url) throws IOException {
   if ("file".equals(url.getProtocol())) {
     // Optimize file: access. Also, this prevents throwing an exception if the file doesn't exist
     // as we try to close the stream below.
     return new File(URLDecoder.decode(url.getFile(), STANDARD_PARAMETER_ENCODING)).lastModified();
   } else {
     // Use URLConnection
     final URLConnection urlConnection = url.openConnection();
     if (urlConnection instanceof HttpURLConnection)
       ((HttpURLConnection) urlConnection).setRequestMethod("HEAD");
     try {
       return getLastModified(urlConnection);
     } finally {
       final InputStream is = urlConnection.getInputStream();
       if (is != null) is.close();
     }
   }
 }
 public static byte[] download(String urlString, String name) {
   int maxLength = 52428800; // 50MB
   URL url = null;
   boolean unknownLength = false;
   byte[] data = null;
   ;
   int n = 0;
   try {
     url = new URL(urlString);
     if (IJ.debugMode) IJ.log("PluginInstaller: " + urlString + "  " + url);
     if (url == null) return null;
     URLConnection uc = url.openConnection();
     int len = uc.getContentLength();
     unknownLength = len < 0;
     if (unknownLength) len = maxLength;
     if (name != null) IJ.showStatus("Downloading " + url.getFile());
     InputStream in = uc.getInputStream();
     data = new byte[len];
     int lenk = len / 1024;
     while (n < len) {
       int count = in.read(data, n, len - n);
       if (count < 0) break;
       n += count;
       if (name != null)
         IJ.showStatus("Downloading " + name + " (" + (n / 1024) + "/" + lenk + "k)");
       IJ.showProgress(n, len);
     }
     in.close();
   } catch (Exception e) {
     String msg = "" + e;
     if (!msg.contains("://")) msg += "\n   " + urlString;
     IJ.error("Plugin Installer", msg);
     return null;
   } finally {
     IJ.showProgress(1.0);
   }
   if (name != null) IJ.showStatus("");
   if (unknownLength) {
     byte[] data2 = data;
     data = new byte[n];
     for (int i = 0; i < n; i++) data[i] = data2[i];
   }
   return data;
 }
Esempio n. 18
0
  public static void download(String index, String fname) throws Exception {
    int avd = Integer.parseInt(index.split("-")[0]);
    String type;
    URL ylink_download;
    int dindex = Integer.parseInt(index.split("-")[1]);
    if (avd == 3) {
      ylink_download = new URL((av_set.get(dindex - 1)).split("\n")[0]);
      type = (av_set.get(dindex - 1)).split("\n")[1];
    } else if (avd == 2) {
      ylink_download = new URL((video_set.get(dindex - 1)).split("\n")[0]);
      type = (video_set.get(dindex - 1)).split("\n")[1];
    } else if (avd == 1) {
      ylink_download = new URL((audio_set.get(dindex - 1)).split("\n")[0]);
      type = (audio_set.get(dindex - 1)).split("\n")[1];
    } else {
      System.out.println("Enter valid input");
      return;
    }
    InputStream is = ylink_download.openStream();
    URLConnection con = (URLConnection) ylink_download.openConnection();
    double dsize = con.getContentLength() / 1048576;
    System.out.println("\nDownloading : " + dsize + " MB");
    if (con != null) {
      String wd = System.getProperty("user.dir");
      String fo = fname + "." + type.split("%2F")[1];
      File f = new File(wd, fo);

      FileOutputStream fos = new FileOutputStream(f);
      byte[] buffer = new byte[1024];
      progressbar t1 = new progressbar(dsize * 1048576, fo);
      t1.start();
      int len1 = 0;
      if (is != null) {
        while ((len1 = is.read(buffer)) > 0) {
          fos.write(buffer, 0, len1);
        }
      }
      if (fos != null) {
        fos.close();
      }
    }
    System.out.println("Download Complete");
  }
Esempio n. 19
0
  private URLConnection prepareConnection(String fileUploadUrl, long fileSize)
      throws RemoteException, InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, FileFaultFaultMsg,
          GuestOperationsFaultFaultMsg, InvalidStateFaultMsg, TaskInProgressFaultMsg,
          MalformedURLException, IOException, ProtocolException {

    // http://stackoverflow.com/questions/3386832/upload-a-file-using-http-put-in-java
    URL url = new URL(fileUploadUrl);
    URLConnection conn = url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    if (conn instanceof HttpURLConnection) {
      ((HttpURLConnection) conn).setRequestMethod("PUT");
    } else {
      throw new IllegalStateException("Unknown connection type");
    }

    conn.setRequestProperty("Content-type", "application/octet-stream");
    conn.setRequestProperty("Content-length", "" + fileSize);
    return conn;
  }
Esempio n. 20
0
  /**
   * Decides if the given source is newer than a class.
   *
   * @param source the source we may want to compile
   * @param cls the former class
   * @return true if the source is newer, false else
   * @throws IOException if it is not possible to open an connection for the given source
   * @see #getTimeStamp(Class)
   */
  protected boolean isSourceNewer(URL source, Class cls) throws IOException {
    long lastMod;

    // Special handling for file:// protocol, as getLastModified() often reports
    // incorrect results (-1)
    if (isFile(source)) {
      // Coerce the file URL to a File
      // See ClassNodeResolver.isSourceNewer for another method that replaces '|' with ':'.
      // WTF: Why is this done and where is it documented?
      String path = source.getPath().replace('/', File.separatorChar).replace('|', ':');
      File file = new File(path);
      lastMod = file.lastModified();
    } else {
      URLConnection conn = source.openConnection();
      lastMod = conn.getLastModified();
      conn.getInputStream().close();
    }
    long classTime = getTimeStamp(cls);
    return classTime + config.getMinimumRecompilationInterval() < lastMod;
  }
 public void run() {
   OutputStream outputstream = null;
   try {
     outputstream = c.getOutputStream();
   } catch (IOException ioexception) {
     b = ioexception;
   }
   a = outputstream;
   synchronized (event) {
     event.notifyAll();
   }
 }
Esempio n. 22
0
  public UrlNode(String location) {
    parser = new JSONParser();
    try {
      try {
        URLConnection conn = new URL(location).openConnection();
        InputStream response = conn.getInputStream();

        // STUPID hack to convert an InputStream to a String in one line:
        InputStream input = conn.getInputStream();
        try {
          this.content = new java.util.Scanner(input).useDelimiter("\\A").next();
          ContainerFactory containerFactory =
              new ContainerFactory() {
                public List creatArrayContainer() {
                  return new LinkedList();
                }

                public Map createObjectContainer() {
                  return new LinkedHashMap();
                }
              };

          try {
            Map json = (Map) parser.parse(content, containerFactory);
            Iterator iter = json.entrySet().iterator();
            data = new HashMap<String, String>();
            while (iter.hasNext()) {
              Map.Entry entry = (Map.Entry) iter.next();
              data.put(entry.getKey().toString(), entry.getValue().toString());
            }
          } catch (ParseException pe) {
          }
        } catch (java.util.NoSuchElementException e) {
          this.content = "{\"Error\": \"NO CONTENT\"}";
        }
      } catch (MalformedURLException e) {
      }
    } catch (IOException e) {
    }
  }
Esempio n. 23
0
  // callRestfulApi - Calls restful API and returns results as a string
  public String callRestfulApi(
      String addr, HttpServletRequest request, HttpServletResponse response) {
    if (localCookie) CookieHandler.setDefault(cm);

    try {
      ByteArrayOutputStream output = new ByteArrayOutputStream();
      URL url = new URL(API_ROOT + addr);
      URLConnection urlConnection = url.openConnection();
      String cookieVal = getBrowserInfiniteCookie(request);
      if (cookieVal != null) {
        urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
      }
      IOUtils.copy(urlConnection.getInputStream(), output);
      String newCookie = getConnectionInfiniteCookie(urlConnection);
      if (newCookie != null && response != null) {
        setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
      }
      return output.toString();
    } catch (IOException e) {
      System.out.println(e.getMessage());
      return null;
    }
  } // TESTED
Esempio n. 24
0
  /**
   * Makes a POST request and returns the server response.
   *
   * @param urlString the URL to post to
   * @param nameValuePairs a map of name/value pairs to supply in the request.
   * @return the server reply (either from the input stream or the error stream)
   */
  public static String doPost(String urlString, Map<String, String> nameValuePairs)
      throws IOException {
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);

    PrintWriter out = new PrintWriter(connection.getOutputStream());

    boolean first = true;
    for (Map.Entry<String, String> pair : nameValuePairs.entrySet()) {
      if (first) first = false;
      else out.print('&');
      String name = pair.getKey();
      String value = pair.getValue();
      out.print(name);
      out.print('=');
      out.print(URLEncoder.encode(value, "UTF-8"));
    }

    out.close();

    Scanner in;
    StringBuilder response = new StringBuilder();
    try {
      in = new Scanner(connection.getInputStream());
    } catch (IOException e) {
      if (!(connection instanceof HttpURLConnection)) throw e;
      InputStream err = ((HttpURLConnection) connection).getErrorStream();
      if (err == null) throw e;
      in = new Scanner(err);
    }

    while (in.hasNextLine()) {
      response.append(in.nextLine());
      response.append("\n");
    }

    in.close();
    return response.toString();
  }
  /**
   * Determine if a host is reachable by attempting to resolve the host name, and then attempting to
   * open a connection.
   *
   * @param hostName Name of the host to connect to.
   * @return {@code true} if a the host is reachable, {@code false} if the host name cannot be
   *     resolved, or if opening a connection to the host fails.
   */
  protected static boolean isHostReachable(String hostName) {
    try {
      // Assume host is unreachable if we can't get its dns entry without getting an exception
      //noinspection ResultOfMethodCallIgnored
      InetAddress.getByName(hostName);
    } catch (UnknownHostException e) {
      String message = Logging.getMessage("NetworkStatus.UnreachableTestHost", hostName);
      Logging.verbose(message);
      return false;
    } catch (Exception e) {
      String message = Logging.getMessage("NetworkStatus.ExceptionTestingHost", hostName);
      Logging.verbose(message);
      return false;
    }

    // Was able to get internet address, but host still might not be reachable because the address
    // might have been
    // cached earlier when it was available. So need to try something else.

    URLConnection connection = null;
    try {
      URL url = new URL("http://" + hostName);
      Proxy proxy = WWIO.configureProxy();
      if (proxy != null) connection = url.openConnection(proxy);
      else connection = url.openConnection();

      connection.setConnectTimeout(2000);
      connection.setReadTimeout(2000);
      String ct = connection.getContentType();
      if (ct != null) return true;
    } catch (IOException e) {
      String message = Logging.getMessage("NetworkStatus.ExceptionTestingHost", hostName);
      Logging.info(message);
    } finally {
      if (connection instanceof HttpURLConnection) ((HttpURLConnection) connection).disconnect();
    }

    return false;
  }
Esempio n. 26
0
  public static String doPost(String urlString, Map<Object, Object> nameValuePairs)
      throws IOException {
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);
    String encoding = connection.getContentEncoding();
    if (encoding == null) encoding = "ISO-8859-1";

    try (PrintWriter out = new PrintWriter(connection.getOutputStream())) {
      boolean first = true;
      for (Map.Entry<Object, Object> pair : nameValuePairs.entrySet()) {
        if (first) first = false;
        else out.print('&');
        String name = pair.getKey().toString();
        String value = pair.getValue().toString();
        out.print(name);
        out.print('=');
        out.print(URLEncoder.encode(value, encoding));
      }
    }

    StringBuilder response = new StringBuilder();
    try (Scanner in = new Scanner(connection.getInputStream(), encoding)) {
      while (in.hasNextLine()) {
        response.append(in.nextLine());
        response.append("\n");
      }
    } catch (IOException e) {
      if (!(connection instanceof HttpURLConnection)) throw e;
      InputStream err = ((HttpURLConnection) connection).getErrorStream();
      if (err == null) throw e;
      Scanner in = new Scanner(err);
      response.append(in.nextLine());
      response.append("\n");
    }

    return response.toString();
  }
Esempio n. 27
0
  public void run() {
    try {
      fireConnecting();
      URLConnection connection = fileURL.openConnection();
      int max = connection.getContentLength();
      InputStream in = connection.getInputStream();
      OutputStream out = new FileOutputStream(fileDest);
      fireStarted();
      fireProgressChange(0, max);
      {
        int count = 0;
        int b = 0;
        int readCount = 0;
        byte[] buffer = new byte[1024 * 10];

        b = in.read();
        while (!canceling && b >= 0) {
          out.write(b);
          count += 1;
          readCount = in.read(buffer, 0, buffer.length);
          out.write(buffer, 0, readCount);
          count += readCount;
          fireProgressChange(count, max);
          b = in.read();
        }
      }
      in.close();
      out.close();
      if (!canceling) {
        fireDone(fileDest);
      } else {
        // fireCancel(fileDest);
      }
    } catch (Exception ex) {
      fireException(ex);
      ex.printStackTrace();
    }
  }
  public String urlReader(URL crowdFlower) {
    String jsonInput = "";

    try {
      URLConnection yc = crowdFlower.openConnection();
      BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
      String inputLine;

      while ((inputLine = in.readLine()) != null) {
        jsonInput = jsonInput + inputLine;
      }

      in.close();

      trapException(jsonInput);

    } catch (IOException e) {
      e.printStackTrace();
    } catch (CrowdFlowerException e) {
      e.printStackTrace();
    }

    return jsonInput;
  }
Esempio n. 29
0
 byte[] getJar(String address) {
   byte[] data;
   boolean gte133 = version().compareTo("1.33u") >= 0;
   try {
     URL url = new URL(address);
     URLConnection uc = url.openConnection();
     int len = uc.getContentLength();
     String name = address.endsWith("ij/ij.jar") ? "daily build" : "ij.jar";
     IJ.showStatus("Downloading ij.jar (" + IJ.d2s((double) len / 1048576, 1) + "MB)");
     InputStream in = uc.getInputStream();
     data = new byte[len];
     int n = 0;
     while (n < len) {
       int count = in.read(data, n, len - n);
       if (count < 0) throw new EOFException();
       n += count;
       if (gte133) IJ.showProgress(n, len);
     }
     in.close();
   } catch (IOException e) {
     return null;
   }
   return data;
 }
Esempio n. 30
0
  // getConnectionInfiniteCookie
  public static String getConnectionInfiniteCookie(URLConnection urlConnection) {
    Map<String, List<String>> headers = urlConnection.getHeaderFields();
    Set<Map.Entry<String, List<String>>> entrySet = headers.entrySet();

    for (Map.Entry<String, List<String>> entry : entrySet) {
      String headerName = entry.getKey();
      if (headerName != null && headerName.equals("Set-Cookie")) {
        List<String> headerValues = entry.getValue();
        for (String value : headerValues) {
          if (value.contains("infinitecookie")) {
            int equalsLoc = value.indexOf("=");
            int semicolonLoc = value.indexOf(";");
            return value.substring(equalsLoc + 1, semicolonLoc);
          }
        }
      }
    }
    return null;
  } // TESTED