Example usage for com.vaadin.server Page getCurrent

List of usage examples for com.vaadin.server Page getCurrent

Introduction

In this page you can find the example usage for com.vaadin.server Page getCurrent.

Prototype

public static Page getCurrent() 

Source Link

Document

Gets the Page to which the current uI belongs.

Usage

From source file:edu.kit.dama.ui.admin.login.B2AccessLoginComponent.java

License:Apache License

@Override
public void doLogin(VaadinRequest request) throws UnauthorizedAccessAttemptException {
    String clientId = DataManagerSettings.getSingleton().getStringProperty(B2ACCESS_CLIENT_ID_PROPERTY, null);
    String clientSecret = DataManagerSettings.getSingleton().getStringProperty(B2ACCESS_CLIENT_SECRET_PROPERTY,
            null);//from   w ww  .ja  v a  2  s. c o  m

    if (request == null) {
        //set auth_pending attribute in order to be able to finish authentication later
        VaadinSession.getCurrent().setAttribute("auth_pending", getLoginIdentifier());
        Page.getCurrent()
                .setLocation("https://unity.eudat-aai.fz-juelich.de:8443/oauth2-as/oauth2-authz?client_id="
                        + clientId + "&response_type=code&scope=/authenticate&redirect_uri="
                        + UIHelper.getWebAppUrl().toString());
    } else {
        //delete auth_pending attribute as we'll finish now or never
        VaadinSession.getCurrent().setAttribute("auth_pending", null);
        //obtain remaining information and do redirect
        //do actual login
        LOGGER.debug("Obtaining OAuth2 code from URL parameter.");
        String code = request.getParameter("code");

        MultivaluedMap formData = new MultivaluedMapImpl();
        formData.putSingle("client_id", clientId);
        formData.putSingle("client_secret", clientSecret);
        formData.putSingle("grant_type", "authorization_code");
        formData.putSingle("redirect_uri", UIHelper.getWebAppUrl().toString());
        formData.putSingle("code", code);

        ClientConfig config = new DefaultClientConfig();
        IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
        mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext());
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] { TRUST_MANAGER }, new SecureRandom());

            config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                    new HTTPSProperties(VERIFIER, ctx));
            Client client = Client.create(config);
            WebResource webResource = client
                    .resource("https://unity.eudat-aai.fz-juelich.de:8443/oauth2/token");
            webResource.addFilter(new HTTPBasicAuthFilter("KITDM", "0kudH2O."));

            LOGGER.debug("Obtaining access token.");
            ClientResponse response = webResource.header("Content-Type", "application/x-www-form-urlencoded")
                    .accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, formData);

            if (response.getStatus() == 200) {
                LOGGER.debug("Response status is HTTP 200. Parsing JSON response.");
                String responseData = response.getEntity(String.class);
                JSONObject responseObject = new JSONObject(responseData);
                String access_token = responseObject.getString("access_token");
                webResource = client.resource("https://unity.eudat-aai.fz-juelich.de:8443/oauth2/userinfo");
                LOGGER.debug("Accessing B2Access UserInfo at {}." + webResource.getURI());
                response = webResource.header("Content-Type", "application/x-www-form-urlencoded")
                        .accept(MediaType.APPLICATION_JSON).header("Authorization", "Bearer " + access_token)
                        .get(ClientResponse.class);

                if (response.getStatus() == 200) {
                    JSONObject userInfoResponse = new JSONObject(response.getEntity(String.class));
                    String userId = userInfoResponse.getString("sub");
                    UserData result = mdm.findSingleResult(
                            "Select u FROM UserData u WHERE u.distinguishedName=?1", new Object[] { userId },
                            UserData.class);
                    if (result != null) {
                        LOGGER.debug("User with distinguished name {} found. Logging in and redirecting user.",
                                userId);
                        UIHelper.login(new UserId(result.getDistinguishedName()),
                                new GroupId(Constants.USERS_GROUP_ID));
                    } else {
                        LOGGER.warn("No user found for ORCiD {}. Login denied.", userId);
                        throw new UnauthorizedAccessAttemptException(
                                "No user found for ORCiD '" + userId + "'.");
                    }
                } else {
                    //failed, not enough information to proceed!
                }
            } else {
                throw new HttpException("Failed to obtain access token from ORCiD service. Status is "
                        + response.getStatus() + ", response data is: " + response.getEntity(String.class));
            }

            //{"access_token":"84e8f8d0-1df6-43af-9456-6619ef514aed","token_type":"bearer","refresh_token":"2f5116b4-f046-4f69-99c5-097e6066a132","expires_in":631138518,"scope":"/authenticate","name":"Thomas Jejkal","orcid":"0000-0003-2804-688X"}
            //https://pub.orcid.org/v1.2/0000-0003-2804-688X/orcid-bio
        } catch (NoSuchAlgorithmException | KeyManagementException | HttpException ex) {
            LOGGER.error("Failed to access B2Access service.", ex);
            throw new UnauthorizedAccessAttemptException("Failed to login via B2Access.", ex);
        } finally {
            mdm.close();
        }

        String fromPage = (String) VaadinSession.getCurrent().getAttribute("from");
        if (fromPage != null) {
            VaadinSession.getCurrent().setAttribute("from", null);
            Page.getCurrent().setLocation(fromPage);
        } else {
            Page.getCurrent().setLocation(UIHelper.getWebAppUrl().toString());
        }
    }
}

From source file:edu.kit.dama.ui.admin.login.B2AccessLoginComponent.java

License:Apache License

@Override
public void doRegistration(VaadinRequest request) throws UnauthorizedAccessAttemptException {
    String clientId = DataManagerSettings.getSingleton().getStringProperty(B2ACCESS_CLIENT_ID_PROPERTY, null);
    String clientSecret = DataManagerSettings.getSingleton().getStringProperty(B2ACCESS_CLIENT_SECRET_PROPERTY,
            null);/*from ww  w  . j  av  a  2 s .  c  o  m*/

    UserData result = new UserData();
    if (request == null) {
        VaadinSession.getCurrent().setAttribute("registration_pending", getLoginIdentifier());
        Page.getCurrent()
                .setLocation("https://unity.eudat-aai.fz-juelich.de:8443/oauth2-as/oauth2-authz?client_id="
                        + clientId + "&response_type=code&scope=write&redirect_uri="
                        + UIHelper.getWebAppUrl().toString());
    } else {
        //delete auth_pending attribute as we'll finish now or never
        VaadinSession.getCurrent().setAttribute("registration_pending", null);
        //obtain remaining information and do redirect
        //do actual login
        LOGGER.debug("Obtaining OAuth2 code from URL parameter.");
        String code = request.getParameter("code");

        MultivaluedMap formData = new MultivaluedMapImpl();
        formData.putSingle("client_id", clientId);
        formData.putSingle("client_secret", clientSecret);
        formData.putSingle("grant_type", "authorization_code");
        formData.putSingle("redirect_uri", UIHelper.getWebAppUrl().toString());
        formData.putSingle("code", code);

        ClientConfig config = new DefaultClientConfig();
        IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
        mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext());
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] { TRUST_MANAGER }, new SecureRandom());
            config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                    new HTTPSProperties(VERIFIER, ctx));
            Client client = Client.create(config);
            WebResource webResource = client
                    .resource("https://unity.eudat-aai.fz-juelich.de:8443/oauth2/token");
            webResource.addFilter(new HTTPBasicAuthFilter("KITDM", "0kudH2O."));

            LOGGER.debug("Obtaining access token.");
            ClientResponse response = webResource.header("Content-Type", "application/x-www-form-urlencoded")
                    .accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, formData);

            if (response.getStatus() == 200) {
                String responseData = response.getEntity(String.class);
                JSONObject responseObject = new JSONObject(responseData);
                String access_token = responseObject.getString("access_token");
                webResource = client.resource("https://unity.eudat-aai.fz-juelich.de:8443/oauth2/userinfo");

                LOGGER.debug("Accessing B2Access UserInfo at {}." + webResource.getURI());
                response = webResource.header("Content-Type", "application/x-www-form-urlencoded")
                        .accept(MediaType.APPLICATION_JSON).header("Authorization", "Bearer " + access_token)
                        .get(ClientResponse.class);

                if (response.getStatus() == 200) {
                    JSONObject userInfoResponse = new JSONObject(response.getEntity(String.class));
                    try {
                        String userId = userInfoResponse.getString("sub");
                        List<UserData> existingUsers = mdm.findResultList(
                                "Select u FROM UserData u WHERE u.distinguishedName=?1",
                                new Object[] { userId }, UserData.class);
                        if (!existingUsers.isEmpty()) {
                            //user for B2Access subject already exists...unable to continue
                            throw new UnauthorizedAccessAttemptException(
                                    "There is already a user registered for the obtained B2Access id '" + userId
                                            + "'.");
                        }
                        result.setDistinguishedName(userId);
                    } catch (JSONException ex) {
                        //failed, not enough information to proceed!
                    }
                } else {
                    //failed, not enough information to proceed!
                }
            } else {
                //failed, not enough information to proceed!
            }
        } catch (NoSuchAlgorithmException | KeyManagementException | JSONException ex) {
            LOGGER.error("Failed to collect information from B2Access service.", ex);
            throw new UnauthorizedAccessAttemptException("Failed to collect information from B2Access service.",
                    ex);
        } finally {
            mdm.close();
        }
        setup(AUTH_MODE.REGISTRATION, result);
    }
}

From source file:edu.kit.dama.ui.admin.login.EmailPasswordLoginComponent.java

License:Apache License

@Override
public void doLogin(VaadinRequest request) throws UnauthorizedAccessAttemptException {
    if (!UIUtils7.validate(loginForm)) {
        throw new UnauthorizedAccessAttemptException("Login Failed. Please correct the error(s) above.");
    }//w w  w.j a  va2 s  . c om
    String userMail = email.getValue();
    String userPassword = password.getValue();

    if (userMail == null || password == null) {
        throw new UnauthorizedAccessAttemptException("Please provide username and password.");
    }

    IMetaDataManager manager = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
    manager.setAuthorizationContext(AuthorizationContext.factorySystemContext());
    try {
        LOGGER.debug("Getting access token for user {}", userMail);
        ServiceAccessToken token = ServiceAccessUtil.getAccessToken(manager, userMail,
                Constants.MAIN_LOGIN_SERVICE_ID);
        if (token == null) {
            throw new UnauthorizedAccessAttemptException(
                    "Login Failed. No login information found for email " + userMail + ".");
        } else {
            LOGGER.debug("Access token sucessfully obtained. Checking password.");
        }

        if (!userPassword.equals(token.getSecret())) {
            throw new UnauthorizedAccessAttemptException(
                    "Login Failed. Wrong password for email " + userMail + ".");
        } else {
            LOGGER.debug("Password is correct. Getting user information.");
            //login successful
            UserData template = new UserData();
            template.setDistinguishedName(token.getUserId());
            List<UserData> result = manager.find(template, template);
            if (result.isEmpty() || result.size() > 1) {
                throw new Exception("Invalid number of user entries (" + result.size() + ") found for userId "
                        + token.getUserId() + ". Please contact a system administrator.");
            }
            LOGGER.debug("User information obtained. Setting logged in user and updating main layout.");
            //do actual login
            UIHelper.login(new UserId(result.get(0).getDistinguishedName()),
                    new GroupId(Constants.USERS_GROUP_ID));
        }
    } catch (Exception ex) {
        LOGGER.error("Failed to access login database.", ex);
        throw new UnauthorizedAccessAttemptException(
                "Login failed due to an internal error. Please contact an administrator.");
    } finally {
        manager.close();
    }

    String fromPage = (String) VaadinSession.getCurrent().getAttribute("from");
    if (fromPage != null) {
        VaadinSession.getCurrent().setAttribute("from", null);
        Page.getCurrent().setLocation(fromPage);
    } else {
        Page.getCurrent().setLocation(UIHelper.getWebAppUrl().toString());
    }
}

From source file:edu.kit.dama.ui.admin.login.OrcidLoginComponent.java

License:Apache License

@Override
public void doLogin(VaadinRequest request) throws UnauthorizedAccessAttemptException {
    String clientId = DataManagerSettings.getSingleton().getStringProperty(ORCID_CLIENT_ID_PROPERTY, null);
    String clientSecret = DataManagerSettings.getSingleton().getStringProperty(ORCID_CLIENT_SECRET_PROPERTY,
            null);//  www.  j  av a2 s .  c o  m

    if (request == null) {
        //set auth_pending attribute in order to be able to finish authentication later
        VaadinSession.getCurrent().setAttribute("auth_pending", getLoginIdentifier());
        Page.getCurrent().setLocation("https://orcid.org/oauth/authorize?client_id=" + clientId
                + "&response_type=code&scope=/authenticate&redirect_uri=" + UIHelper.getWebAppUrl().toString());
    } else {
        //delete auth_pending attribute as we'll finish now or never
        VaadinSession.getCurrent().setAttribute("auth_pending", null);
        //obtain remaining information and do redirect
        //do actual login
        LOGGER.debug("Obtaining OAuth2 code from URL parameter.");
        String code = request.getParameter("code");

        MultivaluedMap formData = new MultivaluedMapImpl();
        formData.putSingle("client_id", clientId);
        formData.putSingle("client_secret", clientSecret);
        formData.putSingle("grant_type", "authorization_code");
        formData.putSingle("redirect_uri", UIHelper.getWebAppUrl().toString());
        formData.putSingle("code", code);

        ClientConfig config = new DefaultClientConfig();
        IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
        mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext());
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] { TRUST_MANAGER }, new SecureRandom());
            config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                    new HTTPSProperties(VERIFIER, ctx));
            Client client = Client.create(config);
            URI resourceUri = new URL("https://orcid.org/oauth/token").toURI();
            WebResource webResource = client.resource(resourceUri);

            LOGGER.debug("Requesting OAuth2 access token.");
            ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class,
                    formData);
            if (response.getStatus() == 200) {
                LOGGER.debug("Response status is HTTP 200. Parsing JSON response.");
                String responseData = response.getEntity(String.class);

                JSONObject responseObject = new JSONObject(responseData);
                String orcid = responseObject.getString("orcid");
                //   String accessToken = responseObject.getString("access_token");
                LOGGER.debug("Obtained ORCiD is {}.", orcid);

                ServiceAccessToken result = mdm.findSingleResult(
                        "Select t FROM ServiceAccessToken t WHERE t.tokenKey=?1",
                        new Object[] { CryptUtil.stringToSHA1(orcid) }, ServiceAccessToken.class);

                if (result != null) {
                    LOGGER.debug("User with id {} found. Logging in and redirecting user.", result.getUserId());
                    UIHelper.login(new UserId(result.getUserId()), new GroupId(Constants.USERS_GROUP_ID));
                } else {
                    LOGGER.warn("No user found for ORCiD {}. Login denied.", orcid);
                    throw new UnauthorizedAccessAttemptException(
                            "No login credential found for ORCiD '" + orcid + "'.");
                }
            } else {
                throw new HttpException("Failed to obtain access token from ORCiD service. Status is "
                        + response.getStatus() + ", response data is: " + response.getEntity(String.class));
            }

            //{"access_token":"84e8f8d0-1df6-43af-9456-6619ef514aed","token_type":"bearer","refresh_token":"2f5116b4-f046-4f69-99c5-097e6066a132","expires_in":631138518,"scope":"/authenticate","name":"Thomas Jejkal","orcid":"0000-0003-2804-688X"}
            //https://pub.orcid.org/v1.2/0000-0003-2804-688X/orcid-bio
        } catch (NoSuchAlgorithmException | KeyManagementException | MalformedURLException | URISyntaxException
                | HttpException ex) {
            LOGGER.error("Failed to access ORCiD service.", ex);
            throw new UnauthorizedAccessAttemptException("Failed to login via ORCiD.", ex);
        } finally {
            mdm.close();
        }

        String fromPage = (String) VaadinSession.getCurrent().getAttribute("from");
        if (fromPage != null) {
            VaadinSession.getCurrent().setAttribute("from", null);
            Page.getCurrent().setLocation(fromPage);
        } else {
            Page.getCurrent().setLocation(UIHelper.getWebAppUrl().toString());
        }
    }
}

From source file:edu.kit.dama.ui.admin.login.OrcidLoginComponent.java

License:Apache License

@Override
public void doRegistration(VaadinRequest request) throws UnauthorizedAccessAttemptException {
    String clientId = DataManagerSettings.getSingleton().getStringProperty(ORCID_CLIENT_ID_PROPERTY, null);
    String clientSecret = DataManagerSettings.getSingleton().getStringProperty(ORCID_CLIENT_SECRET_PROPERTY,
            null);//from  w  ww. ja  v a 2s. co  m

    UserData result = new UserData();
    if (request == null) {
        VaadinSession.getCurrent().setAttribute("registration_pending", getLoginIdentifier());
        Page.getCurrent().setLocation("https://orcid.org/oauth/authorize?client_id=" + clientId
                + "&response_type=code&scope=/authenticate&redirect_uri=" + UIHelper.getWebAppUrl().toString());
    } else {
        //delete auth_pending attribute as we'll finish now or never
        VaadinSession.getCurrent().setAttribute("registration_pending", null);
        //obtain remaining information and do redirect
        //do actual login
        LOGGER.debug("Obtaining OAuth2 code from URL parameter.");
        String code = request.getParameter("code");

        MultivaluedMap formData = new MultivaluedMapImpl();
        formData.putSingle("client_id", clientId);
        formData.putSingle("client_secret", clientSecret);
        formData.putSingle("grant_type", "authorization_code");
        formData.putSingle("redirect_uri", UIHelper.getWebAppUrl().toString());
        formData.putSingle("code", code);

        ClientConfig config = new DefaultClientConfig();
        IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
        mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext());
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] { TRUST_MANAGER }, new SecureRandom());
            config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                    new HTTPSProperties(VERIFIER, ctx));
            Client client = Client.create(config);
            WebResource webResource = client.resource("https://orcid.org/oauth/token");
            LOGGER.debug("Obtaining access token.");
            ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class,
                    formData);

            if (response.getStatus() == 200) {
                String responseData = response.getEntity(String.class);
                JSONObject responseObject = new JSONObject(responseData);
                String orcid = responseObject.getString("orcid");
                List<UserData> existingUsers = mdm.findResultList(
                        "Select u FROM UserData u WHERE u.distinguishedName=?1", new Object[] { orcid },
                        UserData.class);
                if (!existingUsers.isEmpty()) {
                    //user for ORCiD already exists...unable to continue
                    throw new UnauthorizedAccessAttemptException(
                            "There is already a user registered for ORCiD " + orcid + ".");
                }

                LOGGER.debug("Requesting registration information for ORCiD {}.", orcid);
                result.setDistinguishedName(orcid);

                String access_token = responseObject.getString("access_token");
                //https://pub.orcid.org/v1.2/0000-0003-2804-688X/orcid-bio
                webResource = client.resource("https://pub.orcid.org/v1.2/" + orcid + "/orcid-bio");
                LOGGER.debug("Accessing ORCiD service at {}." + webResource.getURI());
                response = webResource.accept(MediaType.APPLICATION_JSON)
                        .header("Authentication", "Bearer " + access_token).get(ClientResponse.class);
                if (response.getStatus() == 200) {
                    JSONObject orcidResponse = new JSONObject(response.getEntity(String.class));
                    //Sample response with mail visible
                    //{"message-version":"1.2","orcid-profile":{"orcid":null,"orcid-id":null,"orcid-identifier":{"value":null,"uri":"http://orcid.org/0000-0003-2804-688X","path":"0000-0003-2804-688X","host":"orcid.org"},"orcid-deprecated":null,"orcid-preferences":{"locale":"EN"},"orcid-history":{"creation-method":"DIRECT","completion-date":null,"submission-date":{"value":1432891995500},"last-modified-date":{"value":1476705802439},"claimed":{"value":true},"source":null,"deactivation-date":null,"verified-email":{"value":true},"verified-primary-email":{"value":true},"visibility":null},"orcid-bio":{"personal-details":{"given-names":{"value":"Thomas","visibility":null},"family-name":{"value":"Jejkal","visibility":null},"credit-name":{"value":"Thomas Jejkal","visibility":"PUBLIC"},"other-names":null},"biography":null,"researcher-urls":null,"contact-details":{"email":[{"value":"thomas.jejkal@kit.edu","primary":true,"current":true,"verified":true,"visibility":"PUBLIC","source":"0000-0003-2804-688X","source-client-id":null}],"address":{"country":{"value":"DE","visibility":"PUBLIC"}}},"keywords":null,"external-identifiers":null,"delegation":null,"scope":null},"orcid-activities":null,"orcid-internal":null,"type":"USER","group-type":null,"client-type":null},"orcid-search-results":null,"error-desc":null}
                    //Sample response with mail invisible
                    //{"message-version":"1.2","orcid-profile":{"orcid":null,"orcid-id":null,"orcid-identifier":{"value":null,"uri":"http://orcid.org/0000-0003-2804-688X","path":"0000-0003-2804-688X","host":"orcid.org"},"orcid-deprecated":null,"orcid-preferences":{"locale":"EN"},"orcid-history":{"creation-method":"DIRECT","completion-date":null,"submission-date":{"value":1432891995500},"last-modified-date":{"value":1476705875890},"claimed":{"value":true},"source":null,"deactivation-date":null,"verified-email":{"value":true},"verified-primary-email":{"value":true},"visibility":null},"orcid-bio":{"personal-details":{"given-names":{"value":"Thomas","visibility":null},"family-name":{"value":"Jejkal","visibility":null},"credit-name":{"value":"Thomas Jejkal","visibility":"PUBLIC"},"other-names":null},"biography":null,"researcher-urls":null,"contact-details":{"email":[],"address":{"country":{"value":"DE","visibility":"PUBLIC"}}},"keywords":null,"external-identifiers":null,"delegation":null,"scope":null},"orcid-activities":null,"orcid-internal":null,"type":"USER","group-type":null,"client-type":null},"orcid-search-results":null,"error-desc":null}
                    try {
                        JSONObject orcidBio = orcidResponse.getJSONObject("orcid-profile")
                                .getJSONObject("orcid-bio");
                        try {
                            JSONObject personalDetails = orcidBio.getJSONObject("personal-details");
                            String lastName = personalDetails.getJSONObject("family-name").getString("value");
                            String firstName = personalDetails.getJSONObject("given-names").getString("value");
                            result.setFirstName(firstName);
                            result.setLastName(lastName);
                        } catch (JSONException ex) {
                            //failed to collect personal information
                            LOGGER.info(
                                    "No personal-details element found in ORCiD response entity. Skipping first and last name properties.");
                        }

                        try {
                            JSONObject contactDetails = orcidBio.getJSONObject("contact-details");
                            String email = contactDetails.getJSONArray("email").getJSONObject(0)
                                    .getString("value");
                            result.setEmail(email);
                        } catch (JSONException ex) {
                            //failed to collect email
                            LOGGER.info(
                                    "No contact-details element found in ORCiD response entity. Skipping email property.");
                        }
                    } catch (JSONException ex) {
                        //failed to collect email
                        LOGGER.info(
                                "No orcid-profile and/or orcid-bio elements found in ORCiD response entity. No properties can be obtained.");
                    }
                } else {
                    LOGGER.warn("Failed to obtain user profile from ORCiD service. Status is "
                            + response.getStatus() + ", response data is: " + response.getEntity(String.class));
                }
            } else {
                //unable to obtain ORCiD id...unable to continue 
                throw new UnauthorizedAccessAttemptException(
                        "Failed to obtain access token from ORCiD service. Status is " + response.getStatus()
                                + ", response data is: " + response.getEntity(String.class));
            }
            //{"access_token":"84e8f8d0-1df6-43af-9456-6619ef514aed","token_type":"bearer","refresh_token":"2f5116b4-f046-4f69-99c5-097e6066a132","expires_in":631138518,"scope":"/authenticate","name":"Thomas Jejkal","orcid":"0000-0003-2804-688X"}
        } catch (NoSuchAlgorithmException | KeyManagementException | JSONException ex) {
            LOGGER.error("Failed to collect information from ORCiD service.", ex);
            throw new UnauthorizedAccessAttemptException("Failed to collect information from ORCiD service.",
                    ex);
        } finally {
            mdm.close();
        }

        setup(AUTH_MODE.REGISTRATION, result);
    }
}

From source file:edu.kit.dama.ui.admin.utils.UIComponentTools.java

License:Apache License

/**
 * Show a notification with caption <i>caption</i>, message <i>message</i>
 * of type <i>pType</i> for/*  w ww .  j  ava  2  s  .  c  o m*/
 * <i>delay</i> at top_center position.
 *
 * @param caption The caption.
 * @param message The message.
 * @param delay The delay (ms) until the nofication disappears.
 * @param pType The notification type.
 * @param pPosition The notification position.
 */
private static void showNotification(String caption, String message, int delay, Notification.Type pType,
        Position position) {
    Notification notification = new Notification(caption, message, pType);
    notification.setPosition(position);
    notification.setDelayMsec(delay);
    notification.setHtmlContentAllowed(true);
    notification.show(Page.getCurrent());
}

From source file:edu.kit.dama.ui.admin.utils.UIHelper.java

License:Apache License

public static void logout(String destination) {
    VaadinSession.getCurrent().close();
    Page.getCurrent().setLocation(destination);
}

From source file:edu.kit.dama.ui.admin.wizard.FirstStartWizard.java

License:Apache License

private void buildMainLayout() {
    stepLayout = new VerticalLayout();

    back.setEnabled(false);//from  w ww. j a  v  a2s  . c om
    stepLayout.addComponent(stepList[currentStep]);
    stepLayout.setComponentAlignment(stepList[currentStep], Alignment.TOP_RIGHT);
    stepLayout.setSpacing(false);
    stepLayout.setMargin(false);
    stepLayout.setWidth("100%");
    stepLayout.setHeight("500px");

    final VerticalLayout stepLabels = new VerticalLayout();
    for (WizardStep step : stepList) {
        Label stepLabel = new Label(step.getStepName());
        stepLabel.setWidth("250px");
        stepLabels.addComponent(stepLabel);
        stepLabels.setComponentAlignment(stepLabel, Alignment.TOP_LEFT);
    }

    //make introduction label bold
    stepLabels.getComponent(0).addStyleName("myboldcaption");

    Label spacer = new Label();
    stepLabels.addComponent(spacer);
    stepLabels.setExpandRatio(spacer, 1.0f);
    stepLabels.setWidth("275px");
    stepLabels.setHeight("550px");
    stepLabels.setSpacing(true);

    UIUtils7.GridLayoutBuilder builder = new UIUtils7.GridLayoutBuilder(2, 2);

    HorizontalLayout buttonLayout = new HorizontalLayout(back, next);
    buttonLayout.setSizeFull();
    buttonLayout.setComponentAlignment(back, Alignment.BOTTOM_RIGHT);
    buttonLayout.setComponentAlignment(next, Alignment.BOTTOM_RIGHT);
    buttonLayout.setExpandRatio(back, 1.0f);

    next.addClickListener((event) -> {
        if ("Go To Login".equals(next.getCaption())) {
            Page.getCurrent().reload();
        } else if ("Finish".equals(next.getCaption())) {
            //do finish
            WizardPersistHelper helper = new WizardPersistHelper();
            if (helper.persist(properties)) {
                UIUtils7.showInformation("Success",
                        "All information have been successfully stored into the database. For details, please refer to the log output above.\n"
                                + "You may now dismiss this message and click 'Go To Login' in order to access the login page.\n"
                                + "From there you can to login using your administrator account or create a personalized user account.",
                        3000);
                back.setVisible(false);
                next.setCaption("Go To Login");
            } else {
                UIUtils7.showError("Failed to store collected information in database.\n"
                        + "Please refer to the log output above.");
            }
            ((WizardSummary) stepList[currentStep]).setSummary(helper.getMessages());
        } else {
            if (currentStep + 1 <= stepList.length - 1) {
                if (stepList[currentStep].validate()) {
                    stepList[currentStep].collectProperties(properties);
                    currentStep++;
                    stepLayout.replaceComponent(stepList[currentStep - 1], stepList[currentStep]);
                    Label currentLabel = (Label) stepLabels.getComponent(currentStep);
                    Label prevLabel = (Label) stepLabels.getComponent(currentStep - 1);
                    currentLabel.addStyleName("myboldcaption");
                    prevLabel.removeStyleName("myboldcaption");

                    if (stepList[currentStep] instanceof WizardSummary) {
                        StringBuilder summary = new StringBuilder();
                        for (WizardStep step : stepList) {
                            summary.append(step.getSummary()).append("\n");
                        }
                        ((WizardSummary) stepList[currentStep]).setSummary(summary.toString());
                    }
                }
            }

            if (currentStep == stepList.length - 1) {
                //finish
                next.setCaption("Finish");
            } else {
                next.setCaption("Next");
            }

            back.setEnabled(true);
        }
    });

    back.addClickListener((event) -> {
        if (currentStep - 1 >= 0) {
            stepList[currentStep].collectProperties(properties);
            currentStep--;
            stepLayout.replaceComponent(stepList[currentStep + 1], stepList[currentStep]);
            Label currentLabel = (Label) stepLabels.getComponent(currentStep);
            Label prevLabel = (Label) stepLabels.getComponent(currentStep + 1);
            currentLabel.addStyleName("myboldcaption");
            prevLabel.removeStyleName("myboldcaption");
        }
        next.setEnabled(true);
        back.setEnabled(currentStep > 0);
        next.setCaption("Next");
    });

    builder.addComponent(stepLabels, Alignment.TOP_LEFT, 0, 0, 1, 2);
    builder.addComponent(stepLayout, Alignment.TOP_LEFT, 1, 0, 1, 1);
    builder.addComponent(buttonLayout, Alignment.BOTTOM_LEFT, 1, 1, 1, 1);

    mainLayout = builder.getLayout();
    mainLayout.setMargin(true);
    mainLayout.setSizeFull();

    // mainLayout.setColumnExpandRatio(0, .3f);
    mainLayout.setColumnExpandRatio(1, 1f);
    mainLayout.setRowExpandRatio(0, .95f);
    mainLayout.setRowExpandRatio(1, .05f);
}

From source file:edu.kit.dama.ui.commons.AbstractApplication.java

License:Apache License

/**
 * Show a notification to the user. This notification is a tray notification
 * provided by Vaadin, shown in the lower right of the main window.
 *
 * @param caption A custom caption./*w  ww.j a v a  2  s .com*/
 * @param message The message to show.
 */
@Override
public void showNotification(String caption, String message) {
    if (caption == null) {
        caption = "Notification";
    }
    new Notification(caption, message, Type.TRAY_NOTIFICATION).show(Page.getCurrent());
}

From source file:edu.kit.dama.ui.commons.AbstractApplication.java

License:Apache License

/**
 * Show a notification to the user. This notification is a warning
 * notification provided by Vaadin, shown in the middle of the main window.
 *
 * @param caption A custom caption./* w  w  w  .java  2s .c om*/
 * @param message The message to show.
 */
public void showWarning(String caption, String message) {
    if (caption == null) {
        caption = "Warning";
    }
    new Notification(caption, message, Type.WARNING_MESSAGE).show(Page.getCurrent());
}