// NOTE: the finish() method above is not called if the user
 // doesn't browse back from the OAuth authentication page.
 // That's why we make cleanUpSession public so that others can clean up also.
 public void cleanUpSession(final VaadinSession session) {
   session.access(
       new Runnable() {
         @Override
         public void run() {
           session.removeRequestHandler(AuthCallbackRequestHandler.this);
         }
       });
 }
Esempio n. 2
0
  /**
   * Method for finding the error handler for the given connector. Uses connector hierarchy to find
   * a connector with an error handler. Falls back to the VaadinSession error handler if no
   * connector has specified an error handler.
   *
   * <p>Returns a {@link DefaultErrorHandler} if no error handler was found
   *
   * @param connector The target connector
   * @return An ErrorHandler for the connector
   */
  public static ErrorHandler findErrorHandler(ClientConnector connector) {
    if (connector != null) {
      ErrorHandler errorHandler = connector.getErrorHandler();
      if (errorHandler != null) {
        return errorHandler;
      }

      ClientConnector parent = connector.getParent();
      if (parent != null) {
        return findErrorHandler(parent);
      }

      /*
       * Reached UI and found no error handler. Try session which
       * typically has one.
       */
      UI ui = connector.getUI();
      if (ui != null) {
        errorHandler = findErrorHandler(ui.getSession());
        if (errorHandler != null) {
          return errorHandler;
        }
      }
    }

    /*
     * No connector known or the connector is not attached to a session. Try
     * the current session
     */
    if (VaadinSession.getCurrent() != null) {
      ErrorHandler errorHandler = VaadinSession.getCurrent().getErrorHandler();
      if (errorHandler != null) {
        return errorHandler;
      }
    }

    /*
     * We should never really get here as at least the session should have
     * an error handler. If for some reason it does not we use the default
     * error handler.
     */
    return new DefaultErrorHandler();
  }
Esempio n. 3
0
  /**
   * Adds a new browser level window to this application. Please note that UI doesn't have a name
   * that is used in the URL - to add a named window you should instead use {@link #addWindow(UI,
   * String)}
   *
   * @param uI the UI window to add to the application
   * @return returns the name that has been assigned to the window
   * @see #addWindow(UI, String)
   */
  public void addWindow(LegacyWindow uI) {
    if (uI.getName() == null) {
      String name = Integer.toString(namelessUIIndex++);
      uI.setName(name);
    }

    uI.setApplication(this);

    legacyUINames.put(uI.getName(), uI);
    uI.setSession(VaadinSession.getCurrent());
  }
Esempio n. 4
0
  @Override
  public boolean handleConnectorRequest(VaadinRequest request, VaadinResponse response, String path)
      throws IOException {
    DownloadStream stream = null;
    String[] parts = path.split("/", 2);
    String key = parts[0];

    VaadinSession session = getSession();
    session.lock();
    try {
      ConnectorResource resource = (ConnectorResource) getResource(key);
      if (resource == null) {
        return false;
      }
      stream = resource.getStream();
    } finally {
      session.unlock();
    }
    stream.writeResponse(request, response);
    return true;
  }
  @Override
  public boolean handleRequest(
      VaadinSession session, VaadinRequest request, VaadinResponse response) throws IOException {
    String pathInfo = request.getPathInfo();
    if (pathInfo == null) {
      return false;
    }

    Matcher matcher = pattern.matcher(pathInfo);
    if (!matcher.matches()) {
      return false;
    }

    String uiid = matcher.group(1);
    String type = matcher.group(3);
    String key = matcher.group(2);

    if (key == null) {
      return error(request, response, pathInfo + " is not a valid global resource path");
    }

    UI ui = session.getUIById(Integer.parseInt(uiid));
    if (ui == null) {
      return error(request, response, "No UI found for id  " + uiid);
    }
    UI.setCurrent(ui);

    ConnectorResource resource;
    if (LEGACY_TYPE.equals(type)) {
      resource = legacyResources.get(key);
    } else {
      return error(
          request,
          response,
          "Unknown global resource type " + type + " in requested path " + pathInfo);
    }

    if (resource == null) {
      return error(request, response, "Global resource " + key + " not found");
    }

    DownloadStream stream = resource.getStream();
    if (stream == null) {
      return error(request, response, "Resource " + resource + " didn't produce any stream.");
    }

    stream.writeResponse(request, response);
    return true;
  }
 private void saveUser(String oauthId, String name, String email, String picUrl) {
   User user =
       UserBean.builder()
           .oauthIdentifier(oauthId)
           .firstName(name)
           .picUrl(picUrl)
           .lastName("")
           .email(email)
           .role("user")
           .build();
   try {
     UserVertex userVertex = (UserVertex) new UserVertex(user).saveOrUpdateInNewTX();
     user = userVertex.model();
     VaadinSession.getCurrent().setAttribute(User.class.getName(), user);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
 @Test
 public void threadLocalsAfterSessionDestroy() {
   final AtomicBoolean detachCalled = new AtomicBoolean(false);
   ui.addDetachListener(
       new DetachListener() {
         @Override
         public void detach(DetachEvent event) {
           detachCalled.set(true);
           Assert.assertEquals(ui, UI.getCurrent());
           Assert.assertEquals(ui.getPage(), Page.getCurrent());
           Assert.assertEquals(session, VaadinSession.getCurrent());
           Assert.assertEquals(mockService, VaadinService.getCurrent());
           Assert.assertEquals(mockServlet, VaadinServlet.getCurrent());
         }
       });
   CurrentInstance.clearAll();
   session.close();
   mockService.cleanupSession(session);
   Assert.assertTrue(detachCalled.get());
 }
  @Test
  public void threadLocalsAfterUnderlyingSessionTimeout() {

    final AtomicBoolean detachCalled = new AtomicBoolean(false);
    ui.addDetachListener(
        new DetachListener() {
          @Override
          public void detach(DetachEvent event) {
            detachCalled.set(true);
            Assert.assertEquals(ui, UI.getCurrent());
            Assert.assertEquals(ui.getPage(), Page.getCurrent());
            Assert.assertEquals(session, VaadinSession.getCurrent());
            Assert.assertEquals(mockService, VaadinService.getCurrent());
            Assert.assertEquals(mockServlet, VaadinServlet.getCurrent());
          }
        });

    session.valueUnbound(EasyMock.createMock(HttpSessionBindingEvent.class));
    Assert.assertTrue(detachCalled.get());
  }
Esempio n. 9
0
 /**
  * Method for finding the error handler for the given session.
  *
  * @param connector The target connector
  * @return An ErrorHandler for the session or null if none was found
  */
 public static ErrorHandler findErrorHandler(VaadinSession session) {
   if (session == null) {
     return null;
   }
   return session.getErrorHandler();
 }
  @Before
  public void setup() {
    mockServlet =
        new VaadinServlet() {
          @Override
          public String getServletName() {
            return "mockServlet";
          };
        };

    mockService =
        new VaadinServletService(mockServlet, EasyMock.createMock(DeploymentConfiguration.class));

    mockHttpSession = EasyMock.createMock(HttpSession.class);
    mockWrappedSession =
        new WrappedHttpSession(mockHttpSession) {
          final ReentrantLock lock = new ReentrantLock();

          @Override
          public Object getAttribute(String name) {
            if ("mockServlet.lock".equals(name)) {
              return lock;
            }
            return super.getAttribute(name);
          }
        };

    session = new VaadinSession(mockService);
    session.storeInSession(mockService, mockWrappedSession);

    ui =
        new UI() {
          Page page =
              new Page(this) {
                @Override
                public void init(VaadinRequest request) {}
              };

          @Override
          protected void init(VaadinRequest request) {}

          @Override
          public Page getPage() {
            return page;
          }
        };
    vaadinRequest =
        new VaadinServletRequest(EasyMock.createMock(HttpServletRequest.class), mockService) {
          @Override
          public String getParameter(String name) {
            if ("theme".equals(name)) {
              return null;
            }

            return super.getParameter(name);
          }
        };

    ui.doInit(vaadinRequest, session.getNextUIid());

    ui.setSession(session);
    session.addUI(ui);
  }
Esempio n. 11
0
 public void doInit(URL url) {
   this.url = url;
   VaadinSession.getCurrent().setErrorHandler(this);
   init();
 }
Esempio n. 12
0
 public VaadinSession getContext() {
   return VaadinSession.getCurrent();
 }
  @Override
  public boolean handleRequest(
      VaadinSession session, VaadinRequest request, VaadinResponse response) throws IOException {

    if (data.isCallbackForMe(request)) {

      String verifier = request.getParameter(data.getVerifierParameterName());
      if (verifier != null) {
        // Got verifier!
        data.setVerifier(requestToken, new Verifier(verifier));
        finish(session, response);

        Token t = data.getAccessToken();

        OAuthRequest r = new OAuthRequest(Verb.GET, data.getRequestLink());
        data.signRequest(t, r);
        Response resp = r.send();

        FacebookAnswer answer = new Gson().fromJson(resp.getBody(), FacebookAnswer.class);

        String name = answer.name;
        String picUrl = answer.picture.data.url;
        String oauthId = "facebook" + answer.id;
        saveUser(oauthId, name, "", picUrl);

        VaadinSession.getCurrent().removeRequestHandler(this);
        ((VaadinServletResponse) response)
            .getHttpServletResponse()
            .sendRedirect(data.getRedirectUrl());

        return true;
      }

      // No verifier in the parameters. That's most likely because the user
      // denied the OAuth.

      // TODO: current error message reporting (below) is not very useful

      String error = null;
      for (String errorName : data.getErrorParameterNames()) {
        error = request.getParameter(errorName);
        if (error != null) {
          break;
        }
      }

      String errorMessage;
      if (error == null) {
        errorMessage = "OAuth failed.";
      } else {
        errorMessage = "OAuth denied: " + error;
      }

      data.setDenied(errorMessage);
      finish(session, response);
    } else if (request.getParameter("code") != null) {
      String code = request.getParameter("code");
      Verifier v = new Verifier(code);
      Token t = googleService.getAccessToken(null, v);

      OAuthRequest r = new OAuthRequest(Verb.GET, "https://www.googleapis.com/plus/v1/people/me");
      googleService.signRequest(t, r);
      Response resp = r.send();

      GooglePlusAnswer answer = new Gson().fromJson(resp.getBody(), GooglePlusAnswer.class);

      String name =
          (answer.displayName != null && !answer.displayName.equals(""))
              ? answer.displayName
              : answer.emails[0].value.substring(0, answer.emails[0].value.indexOf("@"));
      String picUrl = answer.image.url;
      String oauthId = "google" + answer.id;
      saveUser(oauthId, name, answer.emails[0].value, picUrl);

      VaadinSession.getCurrent().removeRequestHandler(this);
      ((VaadinServletResponse) response)
          .getHttpServletResponse()
          .sendRedirect(data.getRedirectUrl());
      return true;
    }
    return false;
  }