Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.belladati.sdk.impl;
  
 import java.util.List;
 
 
 
 
 class BellaDatiClient implements Serializable {

The serialVersionUID
 
 	private static final long serialVersionUID = 9138881190417975299L;
 
 	private final String baseUrl;
 	private final boolean trustSelfSigned;
 
 	private final transient CloseableHttpClient client;
 
 	BellaDatiClient(String baseUrlboolean trustSelfSigned) {
 		this. = baseUrl.endsWith("/") ? baseUrl : (baseUrl + "/");
 		this. = trustSelfSigned;
 		this. = buildClient(trustSelfSigned);
 	}

Builds the HTTP client to connect to the server.

Parameters:
trustSelfSigned true if the client should accept self-signed certificates
Returns:
a new client instance
 
 	private CloseableHttpClient buildClient(boolean trustSelfSigned) {
 		try {
 			// if required, define custom SSL context allowing self-signed certs
 			SSLContext sslContext = !trustSelfSigned ? SSLContexts.createSystemDefault() : SSLContexts.custom()
 
 			// set timeouts for the HTTP client
 			int globalTimeout = readFromProperty("bdTimeout", 10000);
 			int connectTimeout = readFromProperty("bdConnectTimeout"globalTimeout);
 			int connectionRequestTimeout = readFromProperty("bdConnectionRequestTimeout"globalTimeout);
 			int socketTimeout = readFromProperty("bdSocketTimeout"globalTimeout);
 			RequestConfig requestConfig = RequestConfig.copy(.).setConnectTimeout(connectTimeout)
 				.setSocketTimeout(socketTimeout).setConnectionRequestTimeout(connectionRequestTimeout).build();
 
 			// configure caching
 			CacheConfig cacheConfig = CacheConfig.copy(.).setSharedCache(false).setMaxCacheEntries(1000)
 				.setMaxObjectSize(2 * 1024 * 1024).build();
 
 			// configure connection pooling
 				.<ConnectionSocketFactorycreate().register("http", PlainConnectionSocketFactory.getSocketFactory())
 				.register("https"new SSLConnectionSocketFactory(sslContext)).build());
 			int connectionLimit = readFromProperty("bdMaxConnections", 40);
			// there's only one server to connect to, so max per route matters
			connManager.setMaxTotal(connectionLimit);
			connManager.setDefaultMaxPerRoute(connectionLimit);
			// create the HTTP client
			return CachingHttpClientBuilder.create().setCacheConfig(cacheConfig).setDefaultRequestConfig(requestConfig)
				.setConnectionManager(connManager).build();
catch (GeneralSecurityException e) {
			throw new InternalConfigurationException("Failed to set up SSL context"e);
		}
	}
	private int readFromProperty(String propertyint defaultValue) {
		try {
			return Integer.parseInt(System.getProperty(property));
catch (NumberFormatException e) {
			return defaultValue;
		}
	}
	public byte[] post(String relativeUrlTokenHolder tokenHolder) {
		return post(relativeUrltokenHoldernullnull);
	}
	public byte[] post(String relativeUrlTokenHolder tokenHolderHttpParameters oauthParams) {
		return post(relativeUrltokenHolderoauthParamsnull);
	}
	public byte[] post(String relativeUrlTokenHolder tokenHolderList<? extends NameValuePairparameters) {
		return post(relativeUrltokenHoldernullparameters);
	}
	public byte[] post(String relativeUrlTokenHolder tokenHolderHttpParameters oauthParams,
		List<? extends NameValuePairparameters) {
		HttpPost post = new HttpPost( + relativeUrl);
		if (parameters != null) {
			try {
				post.setEntity(new UrlEncodedFormEntity(parameters"UTF-8"));
				throw new IllegalArgumentException("Invalid URL encoding"e);
			}
		}
		return doRequest(posttokenHolderoauthParams);
	}
	public byte[] postUpload(String relativeUrlTokenHolder tokenHolderString content) {
		HttpPost post = new HttpPost( + relativeUrl);
		try {
			StringEntity entity = new StringEntity(content"UTF-8");
			entity.setContentType("application/octet-stream");
			post.setEntity(entity);
			throw new IllegalArgumentException("Invalid URL encoding"e);
		}
		return doRequest(posttokenHolder);
	}
	public byte[] postData(String relativeUrlTokenHolder tokenHolderbyte[] content) {
		HttpPost post = new HttpPost( + relativeUrl);
		ByteArrayEntity entity = new ByteArrayEntity(content);
		entity.setContentType("application/octet-stream");
		post.setEntity(entity);
		return doRequest(posttokenHolder);
	}
	public TokenHolder postToken(String relativeUrlTokenHolder tokenHolder) {
		return postToken(relativeUrltokenHoldernullnull);
	}
	public TokenHolder postToken(String relativeUrlTokenHolder tokenHolderHttpParameters oauthParams) {
		return postToken(relativeUrltokenHolderoauthParamsnull);
	}
	public TokenHolder postToken(String relativeUrlTokenHolder tokenHolderList<? extends NameValuePairparameters) {
		return postToken(relativeUrltokenHoldernullparameters);
	}
	public TokenHolder postToken(String relativeUrlTokenHolder tokenHolderHttpParameters oauthParams,
		List<? extends NameValuePairparameters) {
		byte[] response = post(relativeUrltokenHolderoauthParamsparameters);
		try {
			HttpParameters responseParams = OAuth.decodeForm(new ByteArrayInputStream(response));
			String token = responseParams.getFirst(.);
			String tokenSecret = responseParams.getFirst(.);
			tokenHolder.setToken(tokentokenSecret);
			return tokenHolder;
catch (IOException e) {
			throw new IllegalArgumentException("Failed to load OAuth token from response"e);
		}
	}
	public byte[] get(String relativeUrlTokenHolder tokenHolder) {
		return doRequest(new HttpGet( + relativeUrl), tokenHolder);
	}
	public JsonNode getJson(String relativeUrlTokenHolder tokenHolder) {
		byte[] response = get(relativeUrltokenHolder);
		try {
			return new ObjectMapper().readTree(response);
catch (IOException e) {
			throw new InvalidJsonException("Could not parse JSON response, was " + new String(response), e);
		}
	}
	public String getBaseUrl() {
		return ;
	}
	private byte[] doRequest(HttpRequestBase requestTokenHolder tokenHolder) {
		return doRequest(requesttokenHoldernull);
	}
	private byte[] doRequest(HttpRequestBase requestTokenHolder tokenHolderHttpParameters oauthParams) {
		CloseableHttpResponse response = null;
		try {
			OAuthConsumer consumer = tokenHolder.createConsumer();
			consumer.setAdditionalParameters(oauthParams);
			consumer.sign(request);
			response = .execute(request);
			int statusCode = response.getStatusLine().getStatusCode();
			HttpEntity entity = response.getEntity();
			byte[] content = entity != null ? readBytes(entity.getContent()) : new byte[0];
			switch (statusCode) {
			case 200:
			case 204:
				// all is well, return
				return content;
				// there was some sort of error - throw the right exception
			case 400:
			case 401:
			case 403:
				throw buildException(statusCodecontenttokenHolder.hasToken());
			case 404:
				throw new NotFoundException(request.getRequestLine().getUri());
			case 500:
			default:
				throw new UnexpectedResponseException(statusCodenew String(content));
			}
catch (OAuthException e) {
			throw new InternalConfigurationException("Failed to create OAuth signature"e);
catch (IOException e) {
			throw new ConnectionException("Failed to connect to BellaDati"e);
finally {
			try {
				if (response != null) {
					response.close();
				}
catch (IOException e) {
				throw new ConnectionException("Failed to connect to BellaDati"e);
			}
		}
	}

Builds an exception based on the given content, assuming that it has been returned as an error from the server.

Parameters:
code response code returned by the server
content content returned by the server
hasToken true if the request was made using a request or access token
Returns:
an exception to throw for the given content
	private BellaDatiRuntimeException buildException(int codebyte[] contentboolean hasToken) {
		try {
			HttpParameters oauthParams = OAuth.decodeForm(new ByteArrayInputStream(content));
			if (oauthParams.containsKey("oauth_problem")) {
				String problem = oauthParams.getFirst("oauth_problem");
				if ("missing_consumer".equals(problem) || "invalid_consumer".equals(problem)) {
else if ("invalid_signature".equals(problem) || "signature_invalid".equals(problem)) {
else if ("domain_expired".equals(problem)) {
else if ("missing_token".equals(problem) || "invalid_token".equals(problem)) {
else if ("unauthorized_token".equals(problem)) {
else if ("token_expired".equals(problem)) {
else if ("x_auth_disabled".equals(problem)) {
else if ("piccolo_not_enabled".equals(problem)) {
else if ("missing_username".equals(problem) || "missing_password".equals(problem)
					|| "invalid_credentials".equals(problem) || "permission_denied".equals(problem)) {
else if ("account_locked".equals(problem) || "user_not_active".equals(problem)) {
else if ("domain_restricted".equals(problem)) {
else if ("timestamp_refused".equals(problem)) {
					String acceptable = oauthParams.getFirst("oauth_acceptable_timestamps");
					if (acceptable != null && acceptable.contains("-")) {
						return new InvalidTimestampException(Long.parseLong(acceptable.split("-")[0]), Long.parseLong(acceptable
							.split("-")[1]));
					}
				}
				return new AuthorizationException(.problem);
			}
			return new UnexpectedResponseException(codenew String(content));
catch (IOException e) {
			throw new UnexpectedResponseException(codenew String(content), e);
		}
	}
	private static byte[] readBytes(InputStream inthrows IOException {
		int len;
		byte[] buffer = new byte[128];
		while ((len = in.read(buffer, 0, buffer.length)) != -1) {
			buf.write(buffer, 0, len);
		}
		buf.flush();
		return buf.toByteArray();
	}

Deserialization. Sets up an HTTP client instance.
		try {
			Field client = getClass().getDeclaredField("client");
			client.setAccessible(true);
catch (NoSuchFieldException e) {
			throw new InternalConfigurationException("Failed to set client fields"e);
catch (IllegalAccessException e) {
			throw new InternalConfigurationException("Failed to set client fields"e);
catch (SecurityException e) {
			throw new InternalConfigurationException("Failed to set client fields"e);
catch (IllegalArgumentException e) {
			throw new InternalConfigurationException("Failed to set client fields"e);
		}
	}
New to GrepCode? Check out our FAQ X