com.company.project.core.connector.AadController.java Source code

Java tutorial

Introduction

Here is the source code for com.company.project.core.connector.AadController.java

Source

/*******************************************************************************
 * Copyright  Microsoft Open Technologies, Inc.
 * 
 * All Rights Reserved
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
 * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
 * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
 * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
 * 
 * See the Apache License, Version 2.0 for the specific language
 * governing permissions and limitations under the License.
 ******************************************************************************/
package com.company.project.core.connector;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;

import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.json.JSONArray;
import org.json.JSONObject;

import com.microsoft.aad.adal4j.AuthenticationResult;

@SuppressWarnings("serial")
@SlingServlet(paths = "/bin/onerm/testad")
public class AadController extends SlingSafeMethodsServlet {

    @Override
    protected void doGet(final SlingHttpServletRequest httpRequest, final SlingHttpServletResponse resp)
            throws ServletException, IOException {
        final Resource resource = httpRequest.getResource();
        resp.getOutputStream().println(resource.toString());
        resp.getOutputStream().println("This content is generated by the new SimpleServlet");

        HttpSession session = httpRequest.getSession();
        AuthenticationResult result = (AuthenticationResult) session
                .getAttribute(AuthHelper.PRINCIPAL_SESSION_NAME);
        if (result == null) {
            resp.getOutputStream().println("AuthenticationResult not found in session.");
        } else {
            String data;
            try {
                data = this.getUsernamesFromGraph(result.getAccessToken(),
                        session.getServletContext().getInitParameter("tenant"));
                // model.addAttribute("users", data);
                resp.getOutputStream().println("Data looks like: " + data);
            } catch (Exception e) {
                // model.addAttribute("error", e);
                //  return "/error";
            }
        }
        // return "/secure/aad";       
    }

    private String getUsernamesFromGraph(String accessToken, String tenant) throws Exception {
        URL url = new URL(
                String.format("https://graph.windows.net/%s/users?api-version=2013-04-05", tenant, accessToken));

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // Set the appropriate header fields in the request header.
        conn.setRequestProperty("api-version", "2013-04-05");
        conn.setRequestProperty("Authorization", accessToken);
        conn.setRequestProperty("Accept", "application/json;odata=minimalmetadata");
        String goodRespStr = HttpClientHelper.getResponseStringFromConn(conn, true);
        // logger.info("goodRespStr ->" + goodRespStr);
        int responseCode = conn.getResponseCode();
        JSONObject response = HttpClientHelper.processGoodRespStr(responseCode, goodRespStr);
        JSONArray users = new JSONArray();

        users = JSONHelper.fetchDirectoryObjectJSONArray(response);

        StringBuilder builder = new StringBuilder();
        User user = null;
        for (int i = 0; i < users.length(); i++) {
            JSONObject thisUserJSONObject = users.optJSONObject(i);
            user = new User();
            JSONHelper.convertJSONObjectToDirectoryObject(thisUserJSONObject, user);
            builder.append(user.getUserPrincipalName() + "<br/>");
        }
        return builder.toString();
    }
}