Search in sources :

Example 6 with Writer

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;
}
Also used : AuthorizationException(org.apache.hadoop.security.authorize.AuthorizationException) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) AuthenticationToken(org.apache.hadoop.security.authentication.server.AuthenticationToken) Token(org.apache.hadoop.security.token.Token) IOException(java.io.IOException) AbstractDelegationTokenIdentifier(org.apache.hadoop.security.token.delegation.AbstractDelegationTokenIdentifier) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Writer(java.io.Writer) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation)

Example 7 with Writer

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();
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) OutputStreamWriter(java.io.OutputStreamWriter) URL(java.net.URL) OutputStreamWriter(java.io.OutputStreamWriter) Writer(java.io.Writer)

Example 8 with Writer

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]);
}
Also used : FileWriter(java.io.FileWriter) Properties(java.util.Properties) File(java.io.File) FileWriter(java.io.FileWriter) Writer(java.io.Writer) Test(org.junit.Test)

Example 9 with Writer

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();
}
Also used : ServletContext(javax.servlet.ServletContext) Writer(java.io.Writer)

Example 10 with Writer

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();
        }
    };
}
Also used : StringWriter(java.io.StringWriter) StringWriterIOException(groovy.lang.StringWriterIOException) Writable(groovy.lang.Writable) StringWriterIOException(groovy.lang.StringWriterIOException) IOException(java.io.IOException) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Aggregations

Writer (java.io.Writer)1259 OutputStreamWriter (java.io.OutputStreamWriter)512 IOException (java.io.IOException)414 StringWriter (java.io.StringWriter)300 File (java.io.File)269 FileOutputStream (java.io.FileOutputStream)196 BufferedWriter (java.io.BufferedWriter)178 FileWriter (java.io.FileWriter)174 PrintWriter (java.io.PrintWriter)159 OutputStream (java.io.OutputStream)120 Test (org.junit.Test)109 InputStreamReader (java.io.InputStreamReader)71 ByteArrayOutputStream (java.io.ByteArrayOutputStream)64 BufferedReader (java.io.BufferedReader)62 Reader (java.io.Reader)62 HashMap (java.util.HashMap)59 Map (java.util.Map)59 ArrayList (java.util.ArrayList)58 InputStream (java.io.InputStream)54 Properties (java.util.Properties)39