use of co.cask.cdap.security.authentication.client.AccessToken in project cdap by caskdata.
the class RESTClientTest method testPostForbidden.
@Test(expected = UnauthorizedException.class)
public void testPostForbidden() throws Exception {
URL url = getBaseURI().resolve("/api/testPostForbidden").toURL();
HttpRequest request = HttpRequest.post(url).build();
restClient.execute(request, new AccessToken("Unknown", 82000L, "Bearer"));
}
use of co.cask.cdap.security.authentication.client.AccessToken in project cdap by caskdata.
the class RESTClientTest method testGetSuccessWithAccessToken.
@Test
public void testGetSuccessWithAccessToken() throws Exception {
URL url = getBaseURI().resolve("/api/testGetAuth").toURL();
HttpRequest request = HttpRequest.get(url).build();
HttpResponse response = restClient.execute(request, new AccessToken(ACCESS_TOKEN, 82000L, "Bearer"));
verifyResponse(response, only(200), any(), only("Access token received: " + ACCESS_TOKEN));
}
use of co.cask.cdap.security.authentication.client.AccessToken in project cdap by caskdata.
the class StreamClient method getEvents.
/**
* Reads events from a stream
*
* @param streamId ID of the stream
* @param start Timestamp in milliseconds or now-xs format to start reading event from (inclusive)
* @param end Timestamp in milliseconds or now-xs format for the last event to read (exclusive)
* @param limit Maximum number of events to read
* @param callback Callback to invoke for each stream event read. If the callback function returns {@code false}
* upon invocation, it will stops the reading
* @throws IOException If fails to read from stream
* @throws StreamNotFoundException If the given stream does not exists
*/
public void getEvents(StreamId streamId, String start, String end, int limit, Function<? super StreamEvent, Boolean> callback) throws IOException, StreamNotFoundException, UnauthenticatedException {
long startTime = TimeMathParser.parseTime(start, TimeUnit.MILLISECONDS);
long endTime = TimeMathParser.parseTime(end, TimeUnit.MILLISECONDS);
URL url = config.resolveNamespacedURLV3(streamId.getParent(), String.format("streams/%s/events?start=%d&end=%d&limit=%d", streamId.getStream(), startTime, endTime, limit));
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
AccessToken accessToken = config.getAccessToken();
if (accessToken != null) {
urlConn.setRequestProperty(HttpHeaders.AUTHORIZATION, accessToken.getTokenType() + " " + accessToken.getValue());
}
if (urlConn instanceof HttpsURLConnection && !config.isVerifySSLCert()) {
try {
HttpRequests.disableCertCheck((HttpsURLConnection) urlConn);
} catch (Exception e) {
// TODO: Log "Got exception while disabling SSL certificate check for request.getURL()"
}
}
try {
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
throw new UnauthenticatedException("Unauthorized status code received from the server.");
}
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
throw new StreamNotFoundException(streamId);
}
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) {
return;
}
// The response is an array of stream event object
InputStream inputStream = urlConn.getInputStream();
JsonReader jsonReader = new JsonReader(new InputStreamReader(inputStream, Charsets.UTF_8));
jsonReader.beginArray();
while (jsonReader.peek() != JsonToken.END_ARRAY) {
Boolean result = callback.apply(GSON.<StreamEvent>fromJson(jsonReader, StreamEvent.class));
if (result == null || !result) {
break;
}
}
drain(inputStream);
// No need to close reader, the urlConn.disconnect in finally will close all underlying streams
} finally {
urlConn.disconnect();
}
}
use of co.cask.cdap.security.authentication.client.AccessToken in project cdap by caskdata.
the class UpgradeTool method getClientConfig.
private static ClientConfig getClientConfig(CommandLine commandLine) throws IOException {
String uriStr = commandLine.hasOption("u") ? commandLine.getOptionValue("u") : "localhost:11015";
if (!uriStr.contains("://")) {
uriStr = "http://" + uriStr;
}
URI uri = URI.create(uriStr);
String hostname = uri.getHost();
int port = uri.getPort();
boolean sslEnabled = "https".equals(uri.getScheme());
ConnectionConfig connectionConfig = ConnectionConfig.builder().setHostname(hostname).setPort(port).setSSLEnabled(sslEnabled).build();
int readTimeout = commandLine.hasOption("t") ? Integer.parseInt(commandLine.getOptionValue("t")) : DEFAULT_READ_TIMEOUT_MILLIS;
ClientConfig.Builder clientConfigBuilder = ClientConfig.builder().setDefaultReadTimeout(readTimeout).setConnectionConfig(connectionConfig);
if (commandLine.hasOption("a")) {
String tokenFilePath = commandLine.getOptionValue("a");
File tokenFile = new File(tokenFilePath);
if (!tokenFile.exists()) {
throw new IllegalArgumentException("Access token file " + tokenFilePath + " does not exist.");
}
if (!tokenFile.isFile()) {
throw new IllegalArgumentException("Access token file " + tokenFilePath + " is not a file.");
}
String tokenValue = new String(Files.readAllBytes(tokenFile.toPath()), StandardCharsets.UTF_8).trim();
AccessToken accessToken = new AccessToken(tokenValue, 82000L, "Bearer");
clientConfigBuilder.setAccessToken(accessToken);
}
return clientConfigBuilder.build();
}
use of co.cask.cdap.security.authentication.client.AccessToken in project cdap-ingest by caskdata.
the class RestStreamClientTest method testNotAuthorizedUnknownTokenSetTTL.
@Test
public void testNotAuthorizedUnknownTokenSetTTL() throws IOException {
AuthenticationClient authClient = Mockito.mock(AuthenticationClient.class);
AccessToken accessToken = Mockito.mock(AccessToken.class);
Mockito.when(authClient.getAccessToken()).thenReturn(accessToken);
Mockito.when(accessToken.getValue()).thenReturn("test");
Mockito.when(accessToken.getTokenType()).thenReturn("Bearer");
createClient(authClient);
try {
streamClient.setTTL(TestUtils.AUTH_STREAM_NAME, STREAM_TTL);
Assert.fail("Expected HttpFailureException");
} catch (HttpFailureException e) {
Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, e.getStatusCode());
}
}
Aggregations