use of java.io.Writer in project hadoop by apache.
the class DelegationTokenAuthenticationHandler method managementOperation.
@Override
@SuppressWarnings("unchecked")
public boolean managementOperation(AuthenticationToken token, HttpServletRequest request, HttpServletResponse response) throws IOException, AuthenticationException {
boolean requestContinues = true;
String op = ServletUtils.getParameter(request, KerberosDelegationTokenAuthenticator.OP_PARAM);
op = (op != null) ? StringUtils.toUpperCase(op) : null;
if (isManagementOperation(request)) {
KerberosDelegationTokenAuthenticator.DelegationTokenOperation dtOp = KerberosDelegationTokenAuthenticator.DelegationTokenOperation.valueOf(op);
if (dtOp.getHttpMethod().equals(request.getMethod())) {
boolean doManagement;
if (dtOp.requiresKerberosCredentials() && token == null) {
// Don't authenticate via DT for DT ops.
token = authHandler.authenticate(request, response);
if (token == null) {
requestContinues = false;
doManagement = false;
} else {
doManagement = true;
}
} else {
doManagement = true;
}
if (doManagement) {
UserGroupInformation requestUgi = (token != null) ? UserGroupInformation.createRemoteUser(token.getUserName()) : null;
// Create the proxy user if doAsUser exists
String doAsUser = DelegationTokenAuthenticationFilter.getDoAs(request);
if (requestUgi != null && doAsUser != null) {
requestUgi = UserGroupInformation.createProxyUser(doAsUser, requestUgi);
try {
ProxyUsers.authorize(requestUgi, request.getRemoteAddr());
} catch (AuthorizationException ex) {
HttpExceptionUtils.createServletExceptionResponse(response, HttpServletResponse.SC_FORBIDDEN, ex);
return false;
}
}
Map map = null;
switch(dtOp) {
case GETDELEGATIONTOKEN:
if (requestUgi == null) {
throw new IllegalStateException("request UGI cannot be NULL");
}
String renewer = ServletUtils.getParameter(request, KerberosDelegationTokenAuthenticator.RENEWER_PARAM);
try {
Token<?> dToken = tokenManager.createToken(requestUgi, renewer);
map = delegationTokenToJSON(dToken);
} catch (IOException ex) {
throw new AuthenticationException(ex.toString(), ex);
}
break;
case RENEWDELEGATIONTOKEN:
if (requestUgi == null) {
throw new IllegalStateException("request UGI cannot be NULL");
}
String tokenToRenew = ServletUtils.getParameter(request, KerberosDelegationTokenAuthenticator.TOKEN_PARAM);
if (tokenToRenew == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, MessageFormat.format("Operation [{0}] requires the parameter [{1}]", dtOp, KerberosDelegationTokenAuthenticator.TOKEN_PARAM));
requestContinues = false;
} else {
Token<AbstractDelegationTokenIdentifier> dt = new Token();
try {
dt.decodeFromUrlString(tokenToRenew);
long expirationTime = tokenManager.renewToken(dt, requestUgi.getShortUserName());
map = new HashMap();
map.put("long", expirationTime);
} catch (IOException ex) {
throw new AuthenticationException(ex.toString(), ex);
}
}
break;
case CANCELDELEGATIONTOKEN:
String tokenToCancel = ServletUtils.getParameter(request, KerberosDelegationTokenAuthenticator.TOKEN_PARAM);
if (tokenToCancel == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, MessageFormat.format("Operation [{0}] requires the parameter [{1}]", dtOp, KerberosDelegationTokenAuthenticator.TOKEN_PARAM));
requestContinues = false;
} else {
Token<AbstractDelegationTokenIdentifier> dt = new Token();
try {
dt.decodeFromUrlString(tokenToCancel);
tokenManager.cancelToken(dt, (requestUgi != null) ? requestUgi.getShortUserName() : null);
} catch (IOException ex) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid delegation token, cannot cancel");
requestContinues = false;
}
}
break;
}
if (requestContinues) {
response.setStatus(HttpServletResponse.SC_OK);
if (map != null) {
response.setContentType(MediaType.APPLICATION_JSON);
Writer writer = response.getWriter();
ObjectMapper jsonMapper = new ObjectMapper(jsonFactory);
jsonMapper.writeValue(writer, map);
writer.write(ENTER);
writer.flush();
}
requestContinues = false;
}
}
} else {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, MessageFormat.format("Wrong HTTP method [{0}] for operation [{1}], it should be " + "[{2}]", request.getMethod(), dtOp, dtOp.getHttpMethod()));
requestContinues = false;
}
}
return requestContinues;
}
use of java.io.Writer in project hadoop by apache.
the class AuthenticatorTestCase method _testAuthentication.
protected void _testAuthentication(Authenticator authenticator, boolean doPost) throws Exception {
start();
try {
URL url = new URL(getBaseURL());
AuthenticatedURL.Token token = new AuthenticatedURL.Token();
Assert.assertFalse(token.isSet());
TestConnectionConfigurator connConf = new TestConnectionConfigurator();
AuthenticatedURL aUrl = new AuthenticatedURL(authenticator, connConf);
HttpURLConnection conn = aUrl.openConnection(url, token);
Assert.assertTrue(connConf.invoked);
String tokenStr = token.toString();
if (doPost) {
conn.setRequestMethod("POST");
conn.setDoOutput(true);
}
conn.connect();
if (doPost) {
Writer writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(POST);
writer.close();
}
Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
if (doPost) {
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String echo = reader.readLine();
Assert.assertEquals(POST, echo);
Assert.assertNull(reader.readLine());
}
aUrl = new AuthenticatedURL();
conn = aUrl.openConnection(url, token);
conn.connect();
Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
Assert.assertEquals(tokenStr, token.toString());
} finally {
stop();
}
}
use of java.io.Writer in project hadoop by apache.
the class TestFileSignerSecretProvider method testGetSecrets.
@Test
public void testGetSecrets() throws Exception {
File testDir = new File(System.getProperty("test.build.data", "target/test-dir"));
testDir.mkdirs();
String secretValue = "hadoop";
File secretFile = new File(testDir, "http-secret.txt");
Writer writer = new FileWriter(secretFile);
writer.write(secretValue);
writer.close();
FileSignerSecretProvider secretProvider = new FileSignerSecretProvider();
Properties secretProviderProps = new Properties();
secretProviderProps.setProperty(AuthenticationFilter.SIGNATURE_SECRET_FILE, secretFile.getAbsolutePath());
secretProvider.init(secretProviderProps, null, -1);
Assert.assertArrayEquals(secretValue.getBytes(), secretProvider.getCurrentSecret());
byte[][] allSecrets = secretProvider.getAllSecrets();
Assert.assertEquals(1, allSecrets.length);
Assert.assertArrayEquals(secretValue.getBytes(), allSecrets[0]);
}
use of java.io.Writer in project hadoop by apache.
the class ConfServlet method doGet.
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// If user is a static user and auth Type is null, that means
// there is a non-security environment and no need authorization,
// otherwise, do the authorization.
final ServletContext servletContext = getServletContext();
if (!HttpServer2.isStaticUserAndNoneAuthType(servletContext, request) && !HttpServer2.isInstrumentationAccessAllowed(servletContext, request, response)) {
return;
}
String format = parseAccecptHeader(request);
if (FORMAT_XML.equals(format)) {
response.setContentType("text/xml; charset=utf-8");
} else if (FORMAT_JSON.equals(format)) {
response.setContentType("application/json; charset=utf-8");
}
String name = request.getParameter("name");
Writer out = response.getWriter();
try {
writeResponse(getConfFromContext(), out, format, name);
} catch (BadFormatException bfe) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, bfe.getMessage());
} catch (IllegalArgumentException iae) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, iae.getMessage());
}
out.close();
}
use of java.io.Writer in project groovy by apache.
the class EncodingGroovyMethods method encodeHex.
/**
* Produces a Writable that writes the hex encoding of the byte[]. Calling
* toString() on this Writable returns the hex encoding as a String. The hex
* encoding includes two characters for each byte and all letters are lower case.
*
* @param data byte array to be encoded
* @return object which will write the hex encoding of the byte array
* @see Integer#toHexString(int)
*/
public static Writable encodeHex(final byte[] data) {
return new Writable() {
public Writer writeTo(Writer out) throws IOException {
for (int i = 0; i < data.length; i++) {
// convert byte into unsigned hex string
String hexString = Integer.toHexString(data[i] & 0xFF);
// add leading zero if the length of the string is one
if (hexString.length() < 2) {
out.write("0");
}
// write hex string to writer
out.write(hexString);
}
return out;
}
public String toString() {
StringWriter buffer = new StringWriter();
try {
writeTo(buffer);
} catch (IOException e) {
throw new StringWriterIOException(e);
}
return buffer.toString();
}
};
}
Aggregations