Java Code Examples for javax.net.ssl.HttpsURLConnection#setConnectTimeout()

The following examples show how to use javax.net.ssl.HttpsURLConnection#setConnectTimeout() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MCLeaks.java    From LiquidBounce with GNU General Public License v3.0 6 votes vote down vote up
private static URLConnection preparePostRequest(final String body) {
    try {
        final HttpsURLConnection connection = (HttpsURLConnection) new URL("https://auth.mcleaks.net/v1/redeem").openConnection();
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(10000);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201");
        connection.setDoOutput(true);

        final DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
        dataOutputStream.write(body.getBytes(StandardCharsets.UTF_8));
        dataOutputStream.flush();
        dataOutputStream.close();

        return connection;
    }catch(final Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 2
Source File: SimpleSessionServerRequester.java    From Cleanstone with MIT License 6 votes vote down vote up
@Async(value = "mcLoginExec")
public ListenableFuture<SessionServerResponse> request(Connection connection, LoginData loginData,
                                                       PublicKey publicKey) {
    try {
        String authHash = LoginCrypto.generateAuthHash(connection.getSharedSecret(), publicKey);
        URL url = new URL(SESSION_SERVER_URL
                + String.format("?username=%s&serverId=%s&ip=%s", loginData.getPlayerName(), authHash,
                URLEncoder.encode(connection.getAddress().getHostAddress(), "UTF-8")));
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-Type", "application/json");
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);
        try (Reader reader = new InputStreamReader(con.getInputStream(), Charsets.UTF_8)) {
            Gson gson = new Gson();
            return new AsyncResult<>(gson.fromJson(reader, SessionServerResponse.class));
        }
    } catch (IOException e) {
        throw new RuntimeException("Failed to contact session servers", e);
    }
}
 
Example 3
Source File: JUnit5HttpsApiTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private Response get() throws Exception {
    final URL url = new URL("https://foo.bar.not.existing.talend.com/component/test?api=true");
    final HttpsURLConnection connection = HttpsURLConnection.class.cast(url.openConnection());
    connection.setSSLSocketFactory(handler.getSslContext().getSocketFactory());
    connection.setConnectTimeout(300000);
    connection.setReadTimeout(20000);
    connection.connect();
    final int responseCode = connection.getResponseCode();
    try {
        final Map<String, String> headers = connection
                .getHeaderFields()
                .entrySet()
                .stream()
                .filter(e -> e.getKey() != null)
                .collect(toMap(Map.Entry::getKey, e -> e.getValue().stream().collect(joining(","))));
        return new ResponseImpl(headers, responseCode, IO.readBytes(connection.getInputStream()));
    } finally {
        connection.disconnect();
    }
}
 
Example 4
Source File: UpdateNotifier.java    From SuperVanish with Mozilla Public License 2.0 6 votes vote down vote up
private String fetchLatestVersion() {
    try {
        HttpsURLConnection con = (HttpsURLConnection) new URL(
                "https://api.spigotmc.org/legacy/update.php?resource=1331").openConnection();
        con.setConnectTimeout(20 * 1000);
        con.setReadTimeout(20 * 1000);
        String version;
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            version = reader.readLine();
        }
        con.disconnect();
        if (version.length() <= 7)
            return version;
        else throw new RuntimeException("'" + version + "' is not a valid version");
    } catch (Exception e) {
        plugin.log(Level.WARNING, "Failed to check for an update: "
                + e.getMessage());
        return "Error";
    }
}
 
Example 5
Source File: HttpTransportImpl.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private HttpsURLConnection getConnection(String request, int connectTimeout, int readTimeout) throws IOException {
    String correctedRequest = request;
    if (StringUtils.isNotBlank(correctedRequest)) {
        correctedRequest = fixRequest(correctedRequest);
        URL url = new URL(this.uri + correctedRequest);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        if (connection != null) {
            connection.setConnectTimeout(connectTimeout);
            connection.setReadTimeout(readTimeout);
            if (sslSocketFactory != null) {
                connection.setSSLSocketFactory(sslSocketFactory);
            }
            if (hostnameVerifier != null) {
                connection.setHostnameVerifier(hostnameVerifier);
            }
        }
        return connection;
    }
    return null;
}
 
Example 6
Source File: HttpsClientRequest.java    From product-microgateway with Apache License 2.0 5 votes vote down vote up
private static HttpsURLConnection getURLConnection(String requestUrl, String serverHome)
        throws IOException {
    setSSlSystemProperties(serverHome);
    URL url = new URL(requestUrl);

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setReadTimeout(30000);
    conn.setConnectTimeout(15000);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setAllowUserInteraction(false);
    return conn;
}
 
Example 7
Source File: MineSkinAPI.java    From SkinsRestorerX with GNU General Public License v3.0 5 votes vote down vote up
private String queryURL(String url, String query, int timeout) throws IOException {
    for (int i = 0; i < 3; i++) { // try 3 times, if server not responding
        try {
            MetricsCounter.incrAPI(url);
            HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-length", String.valueOf(query.length()));
            con.setRequestProperty("Accept", "application/json");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setRequestProperty("User-Agent", "SkinsRestorer");
            con.setConnectTimeout(timeout);
            con.setReadTimeout(timeout);
            con.setDoOutput(true);
            con.setDoInput(true);
            DataOutputStream output = new DataOutputStream(con.getOutputStream());
            output.writeBytes(query);
            output.close();
            String outstr = "";
            InputStream _is;
            try {
                _is = con.getInputStream();
            } catch (Exception e) {
                _is = con.getErrorStream();
            }
            DataInputStream input = new DataInputStream(_is);
            for (int c = input.read(); c != -1; c = input.read()) {
                outstr += (char) c;
            }
            input.close();
            return outstr;
        } catch (Exception ignored) {
        }
    }
    return "";
}
 
Example 8
Source File: HttpUtil.java    From util4j with Apache License 2.0 5 votes vote down vote up
public HttpURLConnection buildSSLConn(String url)throws Exception {
	SSLContext sc = SSLContext.getInstance("SSL");  
       sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());  
       URL console = new URL(url);  
       HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();  
       conn.setSSLSocketFactory(sc.getSocketFactory());  
       conn.setHostnameVerifier(new TrustAnyHostnameVerifier());  
	conn.setConnectTimeout(connectTimeOut);
	conn.setReadTimeout(readTimeOut);
	return conn;
}
 
Example 9
Source File: HttpKit.java    From mblog with GNU General Public License v3.0 5 votes vote down vote up
private static HttpsURLConnection initHttps(String url, String method, Map<String, String> headers)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    TrustManager[] tm = {new MyX509TrustManager()};
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new SecureRandom());

    SSLSocketFactory ssf = sslContext.getSocketFactory();
    URL _url = new URL(url);
    HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
    http.setHostnameVerifier(new TrustAnyHostnameVerifier());

    http.setConnectTimeout(25000);

    http.setReadTimeout(25000);
    http.setRequestMethod(method);
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    http.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");

    if ((headers != null) && (!headers.isEmpty())) {
        for (Entry entry : headers.entrySet()) {
            http.setRequestProperty((String) entry.getKey(), (String) entry.getValue());
        }
    }
    http.setSSLSocketFactory(ssf);
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    return http;
}
 
Example 10
Source File: RandomOrgClient.java    From JSON-RPC-Java with MIT License 5 votes vote down vote up
/** POST JSON to server and return JSON response.
 ** 
 ** @param json request to post. 
 **
 ** @return JSON response.
 **
 ** @throws IOException @see java.io.IOException
 ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException
 ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received.
 **/
private JsonObject post(JsonObject json) throws IOException, MalformedURLException, RandomOrgBadHTTPResponseException {

	HttpsURLConnection con = (HttpsURLConnection) new URL("https://api.random.org/json-rpc/1/invoke").openConnection();
	con.setConnectTimeout(this.httpTimeout);

	// headers		
	con.setRequestMethod("POST");
	con.setRequestProperty("Content-Type", "application/json");
	
	// send JSON
	con.setDoOutput(true);
	DataOutputStream dos = new DataOutputStream(con.getOutputStream());
	dos.writeBytes(json.toString());
	dos.flush();
	dos.close();

	// check response
	int responseCode = con.getResponseCode();
	
	// return JSON...
	if (responseCode == HttpsURLConnection.HTTP_OK) {
		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();

		return new JsonParser().parse(response.toString()).getAsJsonObject();
		
	// ...or throw error
	} else {
		throw new RandomOrgBadHTTPResponseException("Error " + responseCode + ": " + con.getResponseMessage());
	}
}
 
Example 11
Source File: SDSageSession.java    From sagetv with Apache License 2.0 5 votes vote down vote up
private InputStreamReader delete(URL url, boolean retry) throws IOException, SDException
{
  if (SDSession.debugEnabled())
  {
    SDSession.writeDebugLine("DELETE " + url.toString());
  }

  // Verified javax.net.ssl.HttpsURLConnection is present in OpenJDK 7+.
  HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
  connection.setRequestMethod("DELETE");
  connection.setConnectTimeout(TIMEOUT);
  connection.setReadTimeout(TIMEOUT);
  connection.setRequestProperty("User-Agent", USER_AGENT);
  connection.setRequestProperty("Accept", "application/json");
  connection.setRequestProperty("Accept-Encoding", "deflate,gzip");
  connection.setRequestProperty("Accept-Charset", "ISO-8859-1");
  if (token != null)
    connection.setRequestProperty("token", token);

  // Schedules Direct will return an http error 403 if the token has expired. The token can expire
  // because another program is using the same account, so we try once to get the token back.
  if (retry && connection.getResponseCode() == 403)
  {
    token = null;
    authenticate();
    return delete(url, false);
  }

  try
  {
    // We can timeout just getting the InputStream.
    return SDUtils.getStream(connection);
  }
  catch (java.net.SocketTimeoutException e)
  {
    throw new SDException(SDErrors.SAGETV_COMMUNICATION_ERROR);
  }
}
 
Example 12
Source File: HttpClient.java    From iyzipay-java with MIT License 5 votes vote down vote up
private String send(String url, HttpMethod httpMethod, InputStream content, Map<String, String> headers) {
    URLConnection raw;
    HttpsURLConnection conn = null;
    try {
        raw = new URL(url).openConnection();
        conn = HttpsURLConnection.class.cast(raw);

        conn.setSSLSocketFactory(socketFactory);
        conn.setRequestMethod(httpMethod.name());

        conn.setConnectTimeout(TIMEOUT);
        conn.setReadTimeout(TIMEOUT);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(false);

        prepareHeaders(headers, conn);
        if (content != null) {
            prepareRequestBody(httpMethod, content, conn);
        }

        return new String(body(conn), Charset.forName("UTF-8"));
    } catch (Exception e) {
        throw new HttpClientException(e.getMessage(), e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}
 
Example 13
Source File: EvepraisalGetter.java    From jeveassets with GNU General Public License v2.0 4 votes vote down vote up
public static String post(Map<Item, Long> itemCounts) {
	DecimalFormat number  = new DecimalFormat("0");
	StringBuilder builder = new StringBuilder();
	for (Map.Entry<Item, Long> entry : itemCounts.entrySet()) {
		builder.append(entry.getKey().getTypeName());
		builder.append(" ");
		builder.append(number.format(entry.getValue()));
		builder.append("\r\n");
	}
	StringBuilder urlParameters = new StringBuilder();
	//market=jita&raw_textarea=avatar&persist=no
	urlParameters.append("market=");
	urlParameters.append(encode("jita"));
	urlParameters.append("&raw_textarea=");
	urlParameters.append(encode(builder.toString()));
	try {
		URL obj = new URL("https://evepraisal.com/appraisal.json");
		HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

		// add request header
		con.setRequestMethod("POST");
		con.setConnectTimeout(10000);
		con.setReadTimeout(10000);

		// Send post request
		con.setDoOutput(true);
		try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
			wr.writeBytes(urlParameters.toString());
			wr.flush();
		}

		StringBuilder response;
		try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
			String inputLine;
			response = new StringBuilder();
			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
		}
		// read json
		Gson gson = new GsonBuilder().create();
		Result result = gson.fromJson(response.toString(), Result.class);
		return result.getID();
		// set data
	} catch (IOException | JsonParseException ex) {
		LOG.error(ex.getMessage(), ex);
	}
	return null;
}
 
Example 14
Source File: SfmtaApiCaller.java    From core with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Posts the JSON string to the URL. For either the telemetry or the stop
 * command.
 * 
 * @param baseUrl
 * @param jsonStr
 * @return True if successfully posted the data
 */
private static boolean post(String baseUrl, String jsonStr) {
	try {
		// Create the connection
		URL url = new URL(baseUrl);
		HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

		// Set parameters for the connection
		con.setRequestMethod("POST"); 
		con.setRequestProperty("content-type", "application/json");
		con.setDoOutput(true);
		con.setDoInput(true);
		con.setUseCaches (false);
		
		// API now uses basic authentication
		String authString = login.getValue() + ":" + password.getValue();
		byte[] authEncBytes =
				Base64.encodeBase64(authString.getBytes());
		String authStringEnc = new String(authEncBytes);
		con.setRequestProperty("Authorization", "Basic "
				+ authStringEnc);

		// Set the timeout so don't wait forever (unless timeout is set to 0)
		int timeoutMsec = timeout.getValue();
		con.setConnectTimeout(timeoutMsec);
		con.setReadTimeout(timeoutMsec);

		// Write the json data to the connection
		DataOutputStream wr = new DataOutputStream(con.getOutputStream ());
		wr.writeBytes(jsonStr);
		wr.flush();
		wr.close();
		
		// Get the response
		int responseCode = con.getResponseCode();
		
		// If wasn't successful then log the response so can debug
		if (responseCode != 200) {			
			String responseStr = "";
			if (responseCode != 500) {
				// Response code indicates there was a problem so get the
				// reply in case API returned useful error message
				InputStream inputStream = con.getErrorStream();
				if (inputStream != null) {
					BufferedReader in =
							new BufferedReader(new InputStreamReader(
									inputStream));
					String inputLine;
					StringBuffer response = new StringBuffer();
					while ((inputLine = in.readLine()) != null) {
						response.append(inputLine);
					}
					in.close();
					responseStr = response.toString();
				}
			}

			// Lot that response code indicates there was a problem
			logger.error("Bad HTTP response {} when writing data to SFMTA "
					+ "API. Response text=\"{}\" URL={} json=\n{}",
					responseCode, responseStr, baseUrl, jsonStr);
		}

		// Done so disconnect just for the heck of it
		con.disconnect();
		
		// Return whether was successful
		return responseCode == 200;
	} catch (IOException e) {
		logger.error("Exception when writing data to SFMTA API: \"{}\" "
				+ "URL={} json=\n{}", 
				e.getMessage(), baseUrl, jsonStr);
		
		// Return that was unsuccessful
		return false;
	}
	
}
 
Example 15
Source File: GoogleElevationApi.java    From BackPackTrackII with GNU General Public License v3.0 4 votes vote down vote up
public static void getElevation(Location location, Context context) throws IOException, JSONException {
    // https://developers.google.com/maps/documentation/elevation/
    URL url = new URL("https://maps.googleapis.com/maps/api/elevation/json?locations=" +
            String.valueOf(location.getLatitude()) + "," +
            String.valueOf(location.getLongitude()) +
            "&key=AIzaSyAp0gtiT6AqaSUSlqwXSyoFCA6SCzMyr6w");
    Log.d(TAG, "url=" + url);
    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();

    urlConnection.setConnectTimeout(cTimeOutMs);
    urlConnection.setReadTimeout(cTimeOutMs);
    urlConnection.setRequestProperty("Accept", "application/json");

    // Set request type
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(false);
    urlConnection.setDoInput(true);

    try {
        // Check for errors
        int code = urlConnection.getResponseCode();
        if (code != HttpsURLConnection.HTTP_OK)
            throw new IOException("HTTP error " + urlConnection.getResponseCode());

        // Get response
        BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        StringBuilder json = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null)
            json.append(line);
        Log.d(TAG, json.toString());

        // Decode result
        JSONObject jroot = new JSONObject(json.toString());
        String status = jroot.getString("status");
        if ("OK".equals(status)) {
            JSONArray results = jroot.getJSONArray("results");
            if (results.length() > 0) {
                double elevation = results.getJSONObject(0).getDouble("elevation");
                location.setAltitude(elevation);
                Log.i(TAG, "Elevation " + location);
            } else
                throw new IOException("JSON no results");
        } else
            throw new IOException("JSON status " + status);
    } finally {
        urlConnection.disconnect();
    }
}
 
Example 16
Source File: RoomParametersFetcher.java    From Yahala-Messenger with MIT License 4 votes vote down vote up
private LinkedList<PeerConnection.IceServer> requestTurnServers(String url)
        throws IOException, JSONException {
    LinkedList<PeerConnection.IceServer> turnServers =
            new LinkedList<PeerConnection.IceServer>();
    Log.d(TAG, "Request TURN from: " + url);
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

        @Override
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }

    });
    HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
    //HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    CertificateFactory cf = null;
    SSLContext context = null;
    try {
 /* cf = CertificateFactory.getInstance("X.509");


  InputStream caInput = new BufferedInputStream( ApplicationLoader.applicationContext.getAssets().open("y2.crt"));
  Certificate ca = cf.generateCertificate(caInput);
  FileLog.e(TAG,"ca=" + ((X509Certificate) ca).getSubjectDN());//////////////

  String keyStoreType = KeyStore.getDefaultType();
  KeyStore keyStore = KeyStore.getInstance(keyStoreType);
  keyStore.load(null, null);
  keyStore.setCertificateEntry("ca", ca);

  TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  tmf.init(keyStore);
  //Create an SSLContext that uses our TrustManager
  context = SSLContext.getInstance("TLS");
  context.init(null, tmf.getTrustManagers(), new java.security.SecureRandom());
  SSLSocketFactory sslFactory = context.getSocketFactory();
  */
        connection.setSSLSocketFactory(new DummySSLSocketFactory());//new MySSLSocketFactory2(keyStore));
    } catch (Exception e) {
        e.printStackTrace();
    }

    HostnameVerifier hostnameVerifier = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            HostnameVerifier hv =
                    HttpsURLConnection.getDefaultHostnameVerifier();
            return true;//hv.verify("188.247.90.132", session);
        }
    };
    connection.setHostnameVerifier(hostnameVerifier);
    connection.setConnectTimeout(TURN_HTTP_TIMEOUT_MS);
    connection.setReadTimeout(TURN_HTTP_TIMEOUT_MS);
    int responseCode = connection.getResponseCode();
    if (responseCode != 200) {
        throw new IOException("Non-200 response when requesting TURN server from "
                + url + " : " + connection.getHeaderField(null));
    }
    InputStream responseStream = connection.getInputStream();
    String response = drainStream(responseStream);
    connection.disconnect();
    FileLog.d(TAG, "TURN response: " + response);
    JSONObject responseJSON = new JSONObject(response);
    String username = responseJSON.getString("username");
    String password = responseJSON.getString("password");
    JSONArray turnUris = responseJSON.getJSONArray("uris");
    for (int i = 0; i < turnUris.length(); i++) {
        String uri = turnUris.getString(i);
        turnServers.add(new PeerConnection.IceServer(uri, username, password));
    }
    return turnServers;
}
 
Example 17
Source File: MarkOrVerifyPin.java    From WhereAreTheEyes with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected Void doInBackground(MarkData... params) {
    Location l = params[0].loc;
    String username = params[0].username;
    Context context = params[0].context;
    Activity activity = params[0].activity;
    if( username.length() == 0 )
        return null;
    if( l == null ) {
        Log.d("Marking", "Location was null!");
        return null; // Location data isn't available yet!
    }
    try {
        List<AbstractMap.SimpleEntry> httpParams = new ArrayList<AbstractMap.SimpleEntry>();
        httpParams.add(new AbstractMap.SimpleEntry<>("username", username));
        httpParams.add(new AbstractMap.SimpleEntry<>("latitude", Double.valueOf(l.getLatitude()).toString()));
        httpParams.add(new AbstractMap.SimpleEntry<>("longitude", Double.valueOf(l.getLongitude()).toString()));

        // Vibrate once, let the user know we received the button tap
        Vibrate.pulse(context);

        URL url = new URL("https://" + Constants.DOMAIN + "/markPin");
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        try {

            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

            writer.write(getQuery(httpParams));
            writer.flush();
            writer.close();
            os.close();

            String response = "";
            int responseCode = conn.getResponseCode();
            if( responseCode == HttpsURLConnection.HTTP_OK ) {
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((line = br.readLine()) != null) {
                    response += line;
                }
            }

            handleResponse(response, context, activity);

            Log.d("Marking", "Marked new pin, got response: " + response);
        } finally {
            conn.disconnect();
        }
    } catch( Exception e ) {
        Log.e("MarkPin", "Error marking pin: " + e.getMessage());
        Log.e("MarkPin", Log.getStackTraceString(e));
    }
    return null;
}
 
Example 18
Source File: UnmarkPin.java    From WhereAreTheEyes with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected Void doInBackground(MarkData... params) {
    Location l = params[0].loc;
    String username = params[0].username;
    Context context = params[0].context;
    Activity activity = params[0].activity;
    if( username.length() == 0 )
        return null;
    if( l == null ) {
        Log.d("Unmarking", "Location was null!");
        return null; // Location data isn't available yet!
    }
    try {
        List<AbstractMap.SimpleEntry> httpParams = new ArrayList<AbstractMap.SimpleEntry>();
        httpParams.add(new AbstractMap.SimpleEntry<>("username", username));
        httpParams.add(new AbstractMap.SimpleEntry<>("latitude", Double.valueOf(l.getLatitude()).toString()));
        httpParams.add(new AbstractMap.SimpleEntry<>("longitude", Double.valueOf(l.getLongitude()).toString()));

        // Vibrate once, let the user know we received the button tap
        Vibrate.pulse(context);

        URL url = new URL("https://" + Constants.DOMAIN + "/unmarkPin");
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        try {

            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

            writer.write(getQuery(httpParams));
            writer.flush();
            writer.close();
            os.close();

            String response = "";
            int responseCode = conn.getResponseCode();
            if( responseCode == HttpsURLConnection.HTTP_OK ) {
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((line = br.readLine()) != null) {
                    response += line;
                }
            }

            handleResponse(response, context, activity);

            Log.d("Unmarking", "Unmarked pin, got response: " + response);
        } finally {
            conn.disconnect();
        }
    } catch( Exception e ) {
        Log.e("UnmarkPin", "Error unmarking pin: " + e.getMessage());
        Log.e("UnmarkPin", Log.getStackTraceString(e));
    }

    return null;
}
 
Example 19
Source File: StatisticManager.java    From Rumble with GNU General Public License v3.0 4 votes vote down vote up
public void onEventAsync(LinkLayerStarted event) {
    if(!event.linkLayerIdentifier.equals(WifiLinkLayerAdapter.LinkLayerIdentifier))
        return;

    if(RumblePreferences.UserOkWithSharingAnonymousData(RumbleApplication.getContext())
            && RumblePreferences.isTimeToSync(RumbleApplication.getContext())) {
        if(!NetUtil.isURLReachable("http://disruptedsystems.org/"))
            return;

        try {
            // generate the JSON file
            byte[] json = generateStatJSON().toString().getBytes();

            // configure SSL
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            InputStream caInput = new BufferedInputStream(RumbleApplication.getContext()
                    .getAssets().open("certs/disruptedsystemsCA.pem"));
            Certificate ca = cf.generateCertificate(caInput);

            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);

            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(keyStore);

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tmf.getTrustManagers(), null);

            URL url = new URL("https://data.disruptedsystems.org/post");
            HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection();
            urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());

            // then configure the header
            urlConnection.setInstanceFollowRedirects(true);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestProperty("charset", "utf-8");
            urlConnection.setRequestProperty("Content-Length", Integer.toString(json.length));
            urlConnection.setUseCaches(false);

            // connect and send the JSON
            urlConnection.setConnectTimeout(10 * 1000);
            urlConnection.connect();
            urlConnection.getOutputStream().write(json);
            if (urlConnection.getResponseCode() != 200)
                throw new IOException("request failed");

            // erase the database
            RumblePreferences.updateLastSync(RumbleApplication.getContext());
            cleanDatabase();
        } catch (Exception ex)
        {
            Log.e(TAG, "Failed to establish SSL connection to server: " + ex.toString());
        }
    }
}
 
Example 20
Source File: NamespaceOverrideMapper.java    From hawkular-metrics with Apache License 2.0 4 votes vote down vote up
private Map<String,String> getNamespaceMapping(Set<String> tenants) {
    Map<String,String> namespaceMap = new HashMap<>();

    if (tenants == null || tenants.isEmpty()) {
        return namespaceMap;
    }

    try {
        String path = "api/v1/namespaces";
        URL url = new URL(NamespaceHandler.KUBERNETES_MASTER_URL + "/" + path);

        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + token);

        // set to 0 which indicated an infinite timeout
        connection.setConnectTimeout(0);
        connection.setReadTimeout(0);

        connection.connect();
        int responseCode = connection.getResponseCode();

        if (responseCode == 200) {

            JsonFactory jsonFactory = new JsonFactory();
            jsonFactory.setCodec(new ObjectMapper());

            InputStream inputStream = connection.getInputStream();
            JsonParser jsonParser = jsonFactory.createParser(inputStream);

            JsonNode jsonNode = jsonParser.readValueAsTree();
            // When the connection is closed, the response is null
            if (jsonNode != null) {
                JsonNode items = jsonNode.get("items");
                if (items != null && items.isArray()) {
                    for (JsonNode project : items) {
                        JsonNode metaData = project.get("metadata");
                        String projectName = metaData.get("name").asText();
                        String projectID = metaData.get("uid").asText();

                        if (tenants.contains(projectName)) {
                            namespaceMap.put(projectID, projectName);
                        }
                    }
                }
            }

            jsonParser.close();
            inputStream.close();

        } else {
            log.error("Error getting metadata from the OpenShift Master (" + responseCode + "). This may mean the 'hawkular' user does not have permission to watch projects. Waiting 2 seconds and will try again.");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }


    } catch (IOException e) {
        log.error(e);
    }

    return namespaceMap;
}