Example #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;
  }
Example #2
0
 /**
  * @param jarFileUri jar:file:/some/path/gluegen-rt.jar!/
  * @return JarFile as named by Uri within the given ClassLoader
  * @throws IllegalArgumentException null arguments
  * @throws IOException if the Jar file could not been found
  * @throws URISyntaxException
  */
 public static JarFile getJarFile(final Uri jarFileUri)
     throws IOException, IllegalArgumentException, URISyntaxException {
   if (null == jarFileUri) {
     throw new IllegalArgumentException("null jarFileUri");
   }
   if (DEBUG) {
     System.err.println("getJarFile.0: " + jarFileUri.toString());
   }
   final URL jarFileURL = jarFileUri.toURL();
   if (DEBUG) {
     System.err.println("getJarFile.1: " + jarFileURL.toString());
   }
   final URLConnection urlc = jarFileURL.openConnection();
   if (urlc instanceof JarURLConnection) {
     final JarURLConnection jarConnection = (JarURLConnection) jarFileURL.openConnection();
     final JarFile jarFile = jarConnection.getJarFile();
     if (DEBUG) {
       System.err.println("getJarFile res: " + jarFile.getName());
     }
     return jarFile;
   }
   if (DEBUG) {
     System.err.println("getJarFile res: NULL");
   }
   return null;
 }
Example #3
0
  /** 创建HttpURLConnection连接 */
  public HttpURLConnection createHttpURLConnection(String actionUrl, String method)
      throws IOException {

    disableConnectionReuseIfNecessary();
    HttpURLConnection httpConnection = null;
    // 请求实例对象Url
    URL url = new URL(actionUrl);
    // 判断验证数据类型
    if (url.getProtocol().toLowerCase(Locale.getDefault()).equals("https")) {
      trustAllHttpsCertificates();
      httpConnection = (HttpsURLConnection) url.openConnection();
    } else {
      httpConnection = (HttpURLConnection) url.openConnection();
    }
    httpConnection.setDoInput(true); // 允许输入
    httpConnection.setDoOutput(true); // 允许输出
    httpConnection.setUseCaches(false);
    httpConnection.setReadTimeout(5 * 1000); // 读取数据超时时间
    httpConnection.setConnectTimeout(5 * 1000); // 连接的超时时间
    httpConnection.setRequestMethod(method);

    httpConnection.setRequestProperty("Charsert", "UTF-8"); // 请求编码类型
    httpConnection.setRequestProperty("connection", "keep-alive"); // 维持连接
    httpConnection.setRequestProperty("Accept-Encoding", "gzip,deflate"); // 响应Gzip,Deflate压缩数据

    return httpConnection;
  }
  public static void main(String[] args) throws Exception {

    /** 1,2,3需要分别运行 */
    /////////// 1////////////////////////////////////////////////
    URL baidu = new URL("http://www.baidu.com/");
    URLConnection bc = baidu.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(bc.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
      System.out.println(inputLine);
    }
    ////////// 2/////////////////////////////////////////////////
    URL url = new URL("http://www.baidu.com/");
    HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
    urlcon.connect(); // 获取连接
    InputStream is = urlcon.getInputStream();
    BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
    StringBuffer bs = new StringBuffer();
    String l = null;
    while ((l = buffer.readLine()) != null) {
      bs.append(l).append("/n");
    }
    System.out.println(bs.toString());
    in.close();
    ////////// 3/////////////////

  }
  /**
   * @param target
   * @param repo
   * @param group
   * @param artifact
   * @param version
   * @param proxy
   * @throws IOException
   */
  public static boolean downloadJar(
      String storage, String repo, String group, String artifact, String version, Proxy proxy)
      throws IOException {

    String url = generateURL(repo, group, artifact, version);
    System.out.println("Downloading [" + url + "]...");
    URL u = new URL(url);

    URLConnection conn = null;
    if (proxy != null) {
      conn = u.openConnection(proxy);
    } else {
      conn = u.openConnection();
    }

    try {
      InputStream is = conn.getInputStream();
      save(storage + "/" + generateFileName(artifact, version), is);
      System.out.print(" Done.\n");
    } catch (FileNotFoundException ex) {
      System.out.print(" Not found.\n");
      //			ex.printStackTrace();
      return false;
    }
    /*
     * 5.0.10.FL.20111102/
     */

    return true;
  }
  /** Load config. */
  private void loadConfig() {
    try {

      if (properties.isEmpty()) {
        URL url = new URL(this.getCodeBase(), Constants.FTP_CONFIG_FILE_NAME);
        URLConnection uc = url.openConnection();
        properties.load(uc.getInputStream());
      }

      List<FtpConfig> ftpConfigs =
          JSON.parseObject(
              properties.getProperty(Constants.FTP_CONFIGS),
              new TypeReference<List<FtpConfig>>() {});
      int cfgIndex = (int) (Math.random() * (ftpConfigs.size() - 1));
      this.ftpConfig = ftpConfigs.get(cfgIndex);
      this.separator = ftpConfig.getOs() == OS.WINDOWS ? "\\" : "/";

      if (messageSource.isEmpty()) {
        URL murl = new URL(this.getCodeBase(), Constants.MESSAGE_SOURCE_NAME);
        URLConnection muc = murl.openConnection();
        messageSource.load(muc.getInputStream());
      }
    } catch (IOException e) {
      JOptionPane.showMessageDialog(this, getMessage(MessageCode.FTP_CONFIG_ERROR));
    }
  }
  @Test
  @RunAsClient
  @Ignore
  public void testUpdateAssetFromJaxB(@ArquillianResource URL baseURL) throws Exception {
    URL url = new URL(baseURL, "rest/packages/restPackage1/assets/model1");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty(
        "Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", MediaType.APPLICATION_XML);
    connection.connect();
    assertEquals(200, connection.getResponseCode());

    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    JAXBContext context = JAXBContext.newInstance(Asset.class);
    Unmarshaller un = context.createUnmarshaller();
    Asset a = (Asset) un.unmarshal(br);
    a.setDescription("An updated description.");
    a.setPublished(new Date(System.currentTimeMillis()));
    connection.disconnect();

    HttpURLConnection conn2 = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty(
        "Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    Marshaller ma = context.createMarshaller();
    conn2.setRequestMethod("PUT");
    conn2.setRequestProperty("Content-Type", MediaType.APPLICATION_XML);
    conn2.setRequestProperty("Content-Length", Integer.toString(a.toString().getBytes().length));
    conn2.setUseCaches(false);
    conn2.setDoInput(true);
    conn2.setDoOutput(true);
    ma.marshal(a, conn2.getOutputStream());
    assertEquals(200, connection.getResponseCode());
    conn2.disconnect();
  }
Example #8
0
  public String doPost(String urlAddress, Map<String, String> param) throws WeiboException {
    GlobalContext globalContext = GlobalContext.getInstance();
    String errorStr = globalContext.getString(R.string.timeout);
    globalContext = null;
    try {
      URL url = new URL(urlAddress);
      Proxy proxy = getProxy();
      HttpURLConnection uRLConnection;
      if (proxy != null) uRLConnection = (HttpURLConnection) url.openConnection(proxy);
      else uRLConnection = (HttpURLConnection) url.openConnection();

      uRLConnection.setDoInput(true);
      uRLConnection.setDoOutput(true);
      uRLConnection.setRequestMethod("POST");
      uRLConnection.setUseCaches(false);
      uRLConnection.setConnectTimeout(CONNECT_TIMEOUT);
      uRLConnection.setReadTimeout(READ_TIMEOUT);
      uRLConnection.setInstanceFollowRedirects(false);
      uRLConnection.setRequestProperty("Connection", "Keep-Alive");
      uRLConnection.setRequestProperty("Charset", "UTF-8");
      uRLConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
      uRLConnection.connect();

      DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream());
      out.write(Utility.encodeUrl(param).getBytes());
      out.flush();
      out.close();
      return handleResponse(uRLConnection);
    } catch (IOException e) {
      e.printStackTrace();
      throw new WeiboException(errorStr, e);
    }
  }
Example #9
0
  @Test
  public void shouldNotPostNodeWithInvalidPrimaryType() throws Exception {
    URL postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items/invalidPrimaryType");
    HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);

    String payload =
        "{ \"properties\": {\"jcr:primaryType\": \"invalidType\", \"testProperty\": \"testValue\", \"multiValuedProperty\": [\"value1\", \"value2\"]}}";
    connection.getOutputStream().write(payload.getBytes());

    assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_BAD_REQUEST));
    connection.disconnect();

    postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items/invalidPrimaryType");
    connection = (HttpURLConnection) postUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);

    assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_NOT_FOUND));
    connection.disconnect();
  }
Example #10
0
  @Test
  public void shouldRetrieveDataFromXPathQuery() throws Exception {
    final String NODE_PATH = "/nodeForQuery";
    URL postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items" + NODE_PATH);
    HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);

    String payload = "{ \"properties\": {\"jcr:primaryType\": \"nt:unstructured\" }}";
    connection.getOutputStream().write(payload.getBytes());

    assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_CREATED));
    connection.disconnect();

    URL queryUrl = new URL(SERVER_URL + "/mode%3arepository/default/query");
    connection = (HttpURLConnection) queryUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/jcr+xpath");

    payload = "//nodeForQuery";
    connection.getOutputStream().write(payload.getBytes());
    JSONObject queryResult = new JSONObject(getResponseFor(connection));
    JSONArray results = (JSONArray) queryResult.get("rows");

    assertThat(results.length(), is(1));

    JSONObject result = (JSONObject) results.get(0);
    assertThat(result, is(notNullValue()));
    assertThat((String) result.get("jcr:path"), is(NODE_PATH));
    assertThat((String) result.get("jcr:primaryType"), is("nt:unstructured"));
  }
Example #11
0
 // Load image from network
 public static Bitmap getBitmapRemote(Context ctx, String url) {
   URL myFileUrl = null;
   Bitmap bitmap = null;
   try {
     Log.w(TAG, url);
     myFileUrl = new URL(url);
   } catch (MalformedURLException e) {
     e.printStackTrace();
   }
   try {
     HttpURLConnection conn = null;
     if (HttpUtil.WAP_INT == HttpUtil.getNetType(ctx)) {
       Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress("10.0.0.172", 80));
       conn = (HttpURLConnection) myFileUrl.openConnection(proxy);
     } else {
       conn = (HttpURLConnection) myFileUrl.openConnection();
     }
     conn.setConnectTimeout(10000);
     conn.setDoInput(true);
     conn.connect();
     InputStream is = conn.getInputStream();
     bitmap = BitmapFactory.decodeStream(is);
     is.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return bitmap;
 }
  public HurlStackConnection(
      String method,
      String url,
      boolean followRedirects,
      boolean useCaches,
      int connectTimeout,
      int readTimeout)
      throws IOException {
    Logger.debug(getClass().getSimpleName(), "creating new connection");

    URL urlObj = new URL(url);

    if (urlObj.getProtocol().equals("https")) {
      mConnection = (HttpsURLConnection) urlObj.openConnection();
    } else {
      mConnection = (HttpURLConnection) urlObj.openConnection();
    }

    mConnection.setDoInput(true);
    mConnection.setDoOutput(true);
    mConnection.setConnectTimeout(connectTimeout);
    mConnection.setReadTimeout(readTimeout);
    mConnection.setUseCaches(useCaches);
    mConnection.setInstanceFollowRedirects(followRedirects);
    mConnection.setRequestMethod(method);
  }
Example #13
0
 /**
  * 获取网络连接
  *
  * @param path
  * @return
  * @throws Exception
  */
 public static HttpURLConnection getConnection(Context context, String path) throws Exception {
   HttpURLConnection conn = null;
   URL url = new URL(path);
   boolean isProxy = false;
   // 网络检测
   ConnectivityManager cm =
       (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
   if (cm != null) {
     NetworkInfo nInfo = cm.getActiveNetworkInfo();
     if (nInfo != null) {
       if (!nInfo.getTypeName().equalsIgnoreCase("WIFI")) {
         isProxy = true;
       }
     }
   }
   if (isProxy) { // 设置代理
     String host = android.net.Proxy.getDefaultHost();
     int port = android.net.Proxy.getDefaultPort();
     SocketAddress sa = new InetSocketAddress(host, port);
     java.net.Proxy proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, sa);
     conn = (HttpURLConnection) url.openConnection(proxy);
   } else {
     conn = (HttpURLConnection) url.openConnection();
   }
   return conn;
 }
  @Test
  @RunAsClient
  public void testUpdateAssetFromAtomWithStateNotExist(@ArquillianResource URL baseURL)
      throws Exception {
    URL url = new URL(baseURL + "rest/packages/restPackage1/assets/model1");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty(
        "Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML);
    connection.connect();
    assertEquals(200, connection.getResponseCode());
    assertEquals(MediaType.APPLICATION_ATOM_XML, connection.getContentType());
    InputStream in = connection.getInputStream();
    assertNotNull(in);
    Document<Entry> doc = abdera.getParser().parse(in);
    Entry entry = doc.getRoot();

    // Update state
    ExtensibleElement metadataExtension = entry.getExtension(Translator.METADATA);
    ExtensibleElement stateExtension = metadataExtension.getExtension(Translator.STATE);
    stateExtension.<Element>getExtension(Translator.VALUE).setText("NonExistState");

    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty(
        "Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("PUT");
    connection.setRequestProperty("Content-type", MediaType.APPLICATION_ATOM_XML);
    connection.setDoOutput(true);
    entry.writeTo(connection.getOutputStream());
    assertEquals(500, connection.getResponseCode());
    connection.disconnect();
  }
 private void postToLoggly(final String event) {
   try {
     assert endpointUrl != null;
     URL endpoint = new URL(endpointUrl);
     final HttpURLConnection connection;
     if (proxy == null) {
       connection = (HttpURLConnection) endpoint.openConnection();
     } else {
       connection = (HttpURLConnection) endpoint.openConnection(proxy);
     }
     connection.setRequestMethod("POST");
     connection.setDoOutput(true);
     connection.addRequestProperty("Content-Type", this.layout.getContentType());
     connection.connect();
     sendAndClose(event, connection.getOutputStream());
     connection.disconnect();
     final int responseCode = connection.getResponseCode();
     if (responseCode != 200) {
       final String message = readResponseBody(connection.getInputStream());
       addError("Loggly post failed (HTTP " + responseCode + ").  Response body:\n" + message);
     }
   } catch (final IOException e) {
     addError("IOException while attempting to communicate with Loggly", e);
   }
 }
    public void taskData() {
      if ("https".equals(url.getProtocol())) {
        HttpsURLConnection httpsUrlConnection;
        try {

          URLrequestection = url.openConnection();
          httpsUrlConnection = (HttpsURLConnection) URLrequestection;
          httpsUrlConnection.setRequestMethod("GET");
        } catch (IOException e) {

          Log.d(
              "Exception ",
              "Message :" + e.getMessage() + "\n StackTrace: " + Log.getStackTraceString(e));
        }

      } else {
        URLConnection URLrequestection;
        HttpURLConnection httpUrlConnection;
        try {
          URLrequestection = url.openConnection();
          httpUrlConnection = (HttpURLConnection) URLrequestection;
          httpUrlConnection.setRequestMethod("GET");

        } catch (IOException e) {

          Log.d(
              "Exception ",
              "Message :" + e.getMessage() + "\n StackTrace: " + Log.getStackTraceString(e));
        }
      }
    }
Example #17
0
 public static void Main() {
   try {
     URL streams = new URL(sc2);
     URL bwstreams = new URL(bw);
     HttpURLConnection getstreams = (HttpURLConnection) streams.openConnection();
     HttpURLConnection getbwstreams = (HttpURLConnection) bwstreams.openConnection();
     InputStream in = new BufferedInputStream(getstreams.getInputStream());
     InputStream in2 = new BufferedInputStream(getbwstreams.getInputStream());
     Writer sw = new StringWriter();
     Writer sw2 = new StringWriter();
     char[] b = new char[1024];
     char[] c = new char[1024];
     Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
     Reader reader2 = new BufferedReader(new InputStreamReader(in2, "UTF-8"));
     int n, n2;
     while ((n = reader.read(b)) != -1) {
       sw.write(b, 0, n);
     }
     while ((n2 = reader2.read(c)) != -1) {
       sw2.write(c, 0, n2);
     }
     ss = sw.toString();
     ss2 = sw2.toString();
   } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
 private JarURLConnection openJarURLConnection(final URL url) throws IOException {
   final URL checkedUrl;
   if ("zip".equals(url.getProtocol())) {
     // WebLogic returns URL with "zip" protocol, returning a
     // weblogic.utils.zip.ZipURLConnection when opened
     // Easy fix is to convert this URL to jar URL
     checkedUrl = new URL(url.toExternalForm().replace("zip:/", "jar:file:/"));
   } else {
     checkedUrl = url;
   }
   URLConnection urlConnection = checkedUrl.openConnection();
   // GlassFish 4.1.1 is providing a URLConnection of type:
   // http://svn.apache.org/viewvc/felix/trunk/framework/src/main/java/org/
   // apache/felix/framework/URLHandlersBundleURLConnection.java?view=markup
   // Which does _not_ extend JarURLConnection.
   // This bit of reflection allows us to call the getLocalURL method which
   // actually returns a URL to a jar file.
   if (checkedUrl.getProtocol().startsWith("bundle")) {
     try {
       final Method m = urlConnection.getClass().getDeclaredMethod("getLocalURL");
       if (!m.isAccessible()) {
         m.setAccessible(true);
       }
       final URL jarUrl = (URL) m.invoke(urlConnection);
       urlConnection = jarUrl.openConnection();
     } catch (Exception ex) {
       throw new AssertionError("Couldn't read jar file URL from bundle: " + ex);
     }
   }
   if (urlConnection instanceof JarURLConnection) {
     return (JarURLConnection) urlConnection;
   } else {
     throw new AssertionError("Unknown URLConnection type: " + urlConnection.getClass().getName());
   }
 }
 public static HttpURLConnection getConnection(String urlStr) throws IOException {
   URL url = new URL(urlStr);
   NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
   if (null == activeNetworkInfo) {
     Log.w(TAG, "No active network available!");
     return null;
   }
   Proxy p = getProxy();
   String extra = activeNetworkInfo.getExtraInfo();
   // chinese mobile network
   if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE && p != null) {
     // cmwap, uniwap, 3gwap
     if (extra != null
         && (extra.startsWith("cmwap")
             || extra.startsWith("uniwap")
             || extra.startsWith("3gwap"))) {
       HttpURLConnection conn =
           (HttpURLConnection)
               new URL("http://" + p.address().toString() + url.getPath()).openConnection();
       conn.setRequestProperty(
           "X-Online-Host", url.getHost() + ":" + (url.getPort() == -1 ? "80" : url.getPort()));
       return conn;
     }
   }
   if (null != p) {
     // through proxy
     return (HttpURLConnection) url.openConnection(p);
   } else {
     return (HttpURLConnection) url.openConnection();
   }
 }
Example #20
0
  /** Generic method that posts a plugin to the metrics website */
  private void postPlugin(boolean isPing) throws IOException {
    // The plugin's description file containg all of the plugin data such as name, version, author,
    // etc
    final PluginDescriptionFile description = this.plugin.getDescription();

    // Construct the post data
    String data =
        Metrics.encode("guid")
            + '='
            + Metrics.encode(this.guid)
            + Metrics.encodeDataPair("version", description.getVersion())
            + Metrics.encodeDataPair("server", Bukkit.getVersion())
            + Metrics.encodeDataPair(
                "players", Integer.toString(Bukkit.getServer().getOnlinePlayers().length))
            + Metrics.encodeDataPair("revision", String.valueOf(Metrics.REVISION));

    // If we're pinging, append it
    if (isPing) {
      data += Metrics.encodeDataPair("ping", "true");
    }

    // Create the url
    final URL url =
        new URL(
            Metrics.BASE_URL
                + String.format(Metrics.REPORT_URL, this.plugin.getDescription().getName()));

    // Connect to the website
    URLConnection connection;

    // Mineshafter creates a socks proxy, so we can safely bypass it
    // It does not reroute POST requests so we need to go around it
    if (this.isMineshafterPresent()) {
      connection = url.openConnection(Proxy.NO_PROXY);
    } else {
      connection = url.openConnection();
    }

    connection.setDoOutput(true);

    // Write the data
    final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    writer.write(data);
    writer.flush();

    // Now read the response
    final BufferedReader reader =
        new BufferedReader(new InputStreamReader(connection.getInputStream()));
    final String response = reader.readLine();

    // close resources
    writer.close();
    reader.close();

    if (response.startsWith("ERR")) {
      throw new IOException(response); // Throw the exception
    }
    // if (response.startsWith("OK")) - We should get "OK" followed by an optional description if
    // everything goes right
  }
Example #21
0
  public String doGet(String urlStr, Map<String, String> param) throws WeiboException {
    GlobalContext globalContext = GlobalContext.getInstance();
    String errorStr = globalContext.getString(R.string.timeout);
    globalContext = null;
    InputStream is = null;
    try {

      StringBuilder urlBuilder = new StringBuilder(urlStr);
      urlBuilder.append("?").append(Utility.encodeUrl(param));
      URL url = new URL(urlBuilder.toString());
      AppLogger.d("get request" + url);
      Proxy proxy = getProxy();
      HttpURLConnection urlConnection;
      if (proxy != null) urlConnection = (HttpURLConnection) url.openConnection(proxy);
      else urlConnection = (HttpURLConnection) url.openConnection();

      urlConnection.setRequestMethod("GET");
      urlConnection.setDoOutput(false);
      urlConnection.setConnectTimeout(CONNECT_TIMEOUT);
      urlConnection.setReadTimeout(READ_TIMEOUT);
      urlConnection.setRequestProperty("Connection", "Keep-Alive");
      urlConnection.setRequestProperty("Charset", "UTF-8");
      urlConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");

      urlConnection.connect();

      return handleResponse(urlConnection);
    } catch (IOException e) {
      e.printStackTrace();
      throw new WeiboException(errorStr, e);
    }
  }
Example #22
0
  @Test
  public void shouldFailWholeTransactionIfOneNodeIsBad() throws Exception {
    URL postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items/invalidNestedPost");
    HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);

    String payload =
        "{ \"properties\": {\"jcr:primaryType\": \"nt:unstructured\", \"testProperty\": \"testValue\", \"multiValuedProperty\": [\"value1\", \"value2\"]},"
            + " \"children\": { \"childNode\" : { \"properties\": {\"jcr:primaryType\": \"invalidType\"}}}}";
    connection.getOutputStream().write(payload.getBytes());

    assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_BAD_REQUEST));
    connection.disconnect();

    postUrl =
        new URL(SERVER_URL + "/mode%3arepository/default/items/invalidNestedPost?mode:depth=1");
    connection = (HttpURLConnection) postUrl.openConnection();

    // Make sure that we can retrieve the node with a GET
    connection.setDoOutput(true);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);

    assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_NOT_FOUND));
    connection.disconnect();
  }
Example #23
0
  @JavascriptInterface
  public Boolean chooseMap(String mapName) {
    HttpURLConnection connection = null;
    OutputStreamWriter wr = null;
    BufferedReader rd = null;
    StringBuilder sb = null;
    String line = null;
    Boolean ret;

    URL serverAddress = null;

    try {
      serverAddress = new URL("http://env-3010859.jelastic.servint.net/Controller/chooseMap.jsp");

      // Set up the initial connection
      connection = (HttpURLConnection) serverAddress.openConnection();
      connection.setRequestMethod("GET");
      connection.setDoOutput(true);
      connection.setReadTimeout(10000);
      connection.setRequestProperty("mapName", mapName);
      connection = (HttpURLConnection) serverAddress.openConnection();

      // get the output stream writer and write the output to the server
      // not needed in this example
      /*
       * wr = new OutputStreamWriter(connection.getOutputStream());
       * wr.write(""); wr.flush();
       */

      // read the result from the server
      rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
      sb = new StringBuilder();

      while ((line = rd.readLine()) != null) {
        sb.append(line);
      }
      String result = sb.toString();
      ret = Boolean.parseBoolean(result);

    } catch (MalformedURLException e) {
      e.printStackTrace();
      ret = false;
    } catch (ProtocolException e) {
      e.printStackTrace();
      ret = false;
    } catch (IOException e) {
      e.printStackTrace();
      ret = false;
    } finally {
      // close the connection, set all objects to null
      connection.disconnect();
      rd = null;
      sb = null;
      wr = null;
      connection = null;
    }
    return (ret);
  }
Example #24
0
 /**
  * Creates a new {@link HttpURLConnection}, sets the proxy, if available, and sets the User-Agent
  * property.
  *
  * @param url URL to connect to
  * @return a new connection.
  * @throws IOException if an I/O exception occurs.
  */
 public HttpURLConnection openConnection(String url) throws IOException {
   if (D) Log.i(TAG, "Open connection: " + url);
   URL u = new URL(url);
   HttpURLConnection urlConnection;
   if (proxy != null) urlConnection = (HttpURLConnection) u.openConnection(proxy);
   else urlConnection = (HttpURLConnection) u.openConnection();
   urlConnection.setRequestProperty("User-Agent", userAgent);
   return urlConnection;
 }
  @Override
  protected byte[] send(
      final byte[] request, final URL responderURL, final RequestOptions requestOptions)
      throws IOException {
    int size = request.length;
    HttpURLConnection httpUrlConnection;
    if (size <= MAX_LEN_GET && requestOptions.isUseHttpGetForRequest()) {
      String b64Request = Base64.toBase64String(request);
      String urlEncodedReq = URLEncoder.encode(b64Request, "UTF-8");
      StringBuilder urlBuilder = new StringBuilder();
      String baseUrl = responderURL.toString();
      urlBuilder.append(baseUrl);
      if (!baseUrl.endsWith("/")) {
        urlBuilder.append('/');
      }
      urlBuilder.append(urlEncodedReq);

      URL newURL = new URL(urlBuilder.toString());

      httpUrlConnection = (HttpURLConnection) newURL.openConnection();
      httpUrlConnection.setRequestMethod("GET");
    } else {
      httpUrlConnection = (HttpURLConnection) responderURL.openConnection();
      httpUrlConnection.setDoOutput(true);
      httpUrlConnection.setUseCaches(false);

      httpUrlConnection.setRequestMethod("POST");
      httpUrlConnection.setRequestProperty("Content-Type", CT_REQUEST);
      httpUrlConnection.setRequestProperty("Content-Length", java.lang.Integer.toString(size));
      OutputStream outputstream = httpUrlConnection.getOutputStream();
      outputstream.write(request);
      outputstream.flush();
    }

    InputStream inputstream = httpUrlConnection.getInputStream();
    if (httpUrlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
      inputstream.close();
      throw new IOException(
          "bad response: "
              + httpUrlConnection.getResponseCode()
              + "  "
              + httpUrlConnection.getResponseMessage());
    }
    String responseContentType = httpUrlConnection.getContentType();
    boolean isValidContentType = false;
    if (responseContentType != null) {
      if (responseContentType.equalsIgnoreCase(CT_RESPONSE)) {
        isValidContentType = true;
      }
    }
    if (!isValidContentType) {
      inputstream.close();
      throw new IOException("bad response: mime type " + responseContentType + " not supported!");
    }

    return IoUtil.read(inputstream);
  }
Example #26
0
  public static String getJSONString() {
    URL oracle = null;
    URLConnection yc = null;
    HttpURLConnection connection = null;
    int code = 0;
    String policy = "";
    URL oracle2 = null;
    URLConnection yc2 = null;
    HttpURLConnection connection2 = null;
    int code1 = 0;

    try {

      oracle =
          new URL(
              "http://10.76.110.84:8181/restconf/config/opendaylight-inventory:nodes/node/vRouter-R1/yang-ext:mount/vyatta-interfaces:interfaces/vyatta-interfaces-dataplane:dataplane/dp0p224p1/");

      connection = (HttpURLConnection) oracle.openConnection();

      yc = oracle.openConnection();
      code = connection.getResponseCode();
    } catch (MalformedURLException e) {

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

    if (code != 200) {
      // System.out.println("No Such Policy");
      // System.out.println(code);
      System.exit(0);
    }
    StringBuffer response = new StringBuffer();
    if (code == 200) {

      BufferedReader in;

      try {
        String inputLine;

        int lineno = 0;
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        while ((inputLine = in.readLine()) != null) {

          if (inputLine.equals("")) continue;

          response.append(inputLine + "\n");
        }
        // System.out.println(response);
      } catch (IOException e1) {

        e1.printStackTrace();
      }
    }
    return response.toString();
  }
  /** @return @Override public void run() { */
  public void checkUpdate() {

    String narutoversion = NarutoMod.version;

    try {
      NarutoMod.logger.info("Checking for updates...");
      URL url = new URL("http://www.sekwah.com/naruto-mod/UpdateInfo.txt");
      URLConnection connection = url.openConnection();
      connection.setConnectTimeout(5000);
      Scanner s = new Scanner(connection.getInputStream());
      int mcversion = Integer.parseInt(s.nextLine());
      int modversion = Integer.parseInt(s.nextLine());
      String newestdownloadlink = s.nextLine();
      s.close();

      if (mcversion == NarutoMod.mcversion && modversion == NarutoMod.modversion) {
        if (NarutoMod.isPreRelease) {
          updatetext = EnumChatFormatting.YELLOW + " - The official release is now available!";
          updatestatus = "updated";
          NarutoMod.logger.info("Current copy is up to date.");
        } else {
          updatetext = EnumChatFormatting.GREEN + " - The Naruto mod is up to date.";
          updatestatus = "updated";
          NarutoMod.logger.info("Current copy is up to date.");
        }
      } else if (mcversion <= NarutoMod.mcversion && modversion <= NarutoMod.modversion) {
        updatetext = EnumChatFormatting.AQUA + " - This is a pre release!";
        updatestatus = "updated";
        NarutoMod.logger.info("Current copy is a pre-release.");
      } else {
        updatetext = EnumChatFormatting.GOLD + " - An update is available!";
        updatestatus = "update";
        NarutoMod.logger.info("Update found.");
      }
    } catch (IOException ex) {
      updatetext = EnumChatFormatting.RED + " - Could not connect to the update info file :(";
    } catch (NumberFormatException ex) {
      updatetext = EnumChatFormatting.RED + " - Something is wrong with the update file.";
    }

    try {
      URL url = new URL("https://www.dropbox.com/s/staineiwde1azr8/Current%20Server%20IP.txt?dl=1");
      URLConnection connection = url.openConnection();
      connection.setConnectTimeout(4000);
      Scanner s = new Scanner(connection.getInputStream());
      joinenabled = Boolean.parseBoolean(s.nextLine());
      serverip = s.nextLine();
      serverport = Integer.parseInt(s.nextLine());
      servertext = s.nextLine();
      s.close();
    } catch (IOException ex) {
      joinenabled = false;
    } catch (NumberFormatException ex) {
      joinenabled = false;
    }
  }
 /**
  * Opens and returns a connection to the given URL.
  *
  * <p>The default implementation uses the given {@linkplain #setProxy(java.net.Proxy) proxy} - if
  * any - to open a connection.
  *
  * @param url the URL to open a connection to
  * @param proxy the proxy to use, may be {@code null}
  * @return the opened connection
  * @throws IOException in case of I/O errors
  */
 protected HttpURLConnection openConnection(URL url, Proxy proxy) throws IOException {
   // Bugs with reusing connections in Android 2.2 (Froyo) and older
   if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.FROYO) {
     System.setProperty("http.keepAlive", "false");
   }
   URLConnection urlConnection =
       (proxy != null ? url.openConnection(proxy) : url.openConnection());
   Assert.isInstanceOf(HttpURLConnection.class, urlConnection);
   return (HttpURLConnection) urlConnection;
 }
Example #29
0
  public void send(Boolean secure) {
    try {
      if (secure) httpC = (HttpsURLConnection) url.openConnection();
      else httpC = (HttpURLConnection) url.openConnection();
      in = new BufferedReader(new InputStreamReader(httpC.getInputStream()));

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #30
0
  @Test
  public void shouldPostNodeToValidPathWithMixinTypes() throws Exception {
    URL postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items/withMixinType");
    HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);

    String payload = "{ \"properties\": {\"jcr:mixinTypes\": \"mix:referenceable\"}}";
    connection.getOutputStream().write(payload.getBytes());

    JSONObject body = new JSONObject(getResponseFor(connection));
    assertThat(body.length(), is(1));

    JSONObject properties = body.getJSONObject("properties");
    assertThat(properties, is(notNullValue()));
    assertThat(properties.length(), is(3));
    assertThat(properties.getString("jcr:primaryType"), is("nt:unstructured"));
    assertThat(properties.getString("jcr:uuid"), is(notNullValue()));

    JSONArray values = properties.getJSONArray("jcr:mixinTypes");
    assertThat(values, is(notNullValue()));
    assertThat(values.length(), is(1));
    assertThat(values.getString(0), is("mix:referenceable"));

    assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_CREATED));
    connection.disconnect();

    postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items/withMixinType");
    connection = (HttpURLConnection) postUrl.openConnection();

    // Make sure that we can retrieve the node with a GET
    connection.setDoOutput(true);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);
    body = new JSONObject(getResponseFor(connection));

    assertThat(body.length(), is(1));

    properties = body.getJSONObject("properties");
    assertThat(properties, is(notNullValue()));
    assertThat(properties.length(), is(3));
    assertThat(properties.getString("jcr:primaryType"), is("nt:unstructured"));
    assertThat(properties.getString("jcr:uuid"), is(notNullValue()));

    values = properties.getJSONArray("jcr:mixinTypes");
    assertThat(values, is(notNullValue()));
    assertThat(values.length(), is(1));
    assertThat(values.getString(0), is("mix:referenceable"));

    assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_OK));
    connection.disconnect();
  }