protected GoogleDriveSession buildGoogleDriveSession() throws IOException, PortalException {

    long userId = PrincipalThreadLocal.getUserId();

    User user = UserLocalServiceUtil.getUser(userId);

    if (user.isDefaultUser()) {
      throw new PrincipalException("User is not authenticated");
    }

    GoogleCredential.Builder builder = new GoogleCredential.Builder();

    String googleClientId = PrefsPropsUtil.getString(user.getCompanyId(), "google-client-id");
    String googleClientSecret =
        PrefsPropsUtil.getString(user.getCompanyId(), "google-client-secret");

    builder.setClientSecrets(googleClientId, googleClientSecret);

    JacksonFactory jsonFactory = new JacksonFactory();

    builder.setJsonFactory(jsonFactory);

    HttpTransport httpTransport = new NetHttpTransport();

    builder.setTransport(httpTransport);

    GoogleCredential googleCredential = builder.build();

    ExpandoBridge expandoBridge = user.getExpandoBridge();

    String googleAccessToken =
        GetterUtil.getString(expandoBridge.getAttribute("googleAccessToken", false));

    googleCredential.setAccessToken(googleAccessToken);

    String googleRefreshToken =
        GetterUtil.getString(expandoBridge.getAttribute("googleRefreshToken", false));

    googleCredential.setRefreshToken(googleRefreshToken);

    Drive.Builder driveBuilder = new Drive.Builder(httpTransport, jsonFactory, googleCredential);

    Drive drive = driveBuilder.build();

    Drive.About driveAbout = drive.about();

    Drive.About.Get driveAboutGet = driveAbout.get();

    About about = driveAboutGet.execute();

    return new GoogleDriveSession(drive, about.getRootFolderId());
  }
Exemplo n.º 2
0
  /**
   * Save CSV or XML file with the storage component
   *
   * @expects "GEMO portal wide params" in portal-ext.properties:
   *     gemo.storage.upload.url=http://?????????/service/storage/upload
   *     gemo.storage.search.query.url=http://?????????/service/storage/ search?query=
   * @param csvXmlFile the file
   * @return the url
   * @throws SystemException the system exception
   * @throws URISyntaxException the uRI syntax exception
   * @throws IOException
   * @throws PortalException
   */
  public static String uploadToStorage(UploadedFile csvXmlFile)
      throws SystemException, URISyntaxException, IOException, PortalException,
          NullPointerException {
    // grab props from constants
    final String storage_uri =
        PrefsPropsUtil.getString(PortalProperties.GEMO_STORAGE_URL, "http://localhost/storage");
    final String upload_uri =
        PrefsPropsUtil.getString(
            PortalProperties.GEMO_STORAGE_UPLOAD_URL, "http://localhost/storage/upload");
    final String upload_base64_uri =
        PrefsPropsUtil.getString(
            PortalProperties.GEMO_STORAGE_UPLOADBASE64_URL,
            "http://localhost:8080/storage/uploadbase64");
    final String query_uri =
        PrefsPropsUtil.getString(
            PortalProperties.GEMO_STORAGE_SEARCH_QUERY_URL,
            "http://localhost/storage/search?query=");

    final String tableName = NameUtils.UsersUsableUniqueNamefromFile(csvXmlFile);

    try {
      byte[] bytes = csvXmlFile.getBytes();
      String theBase64Bytes = Base64.encodeBytes(bytes);

      ResteasyClient client = new ResteasyClientBuilder().build();
      ResteasyWebTarget target = client.target(upload_base64_uri);

      MultipartFormDataOutput mdo = new MultipartFormDataOutput();
      mdo.addFormData("tableName", tableName, MediaType.TEXT_PLAIN_TYPE);
      mdo.addFormData("fileName", csvXmlFile.getName(), MediaType.TEXT_PLAIN_TYPE);
      mdo.addFormData("fileBase64", theBase64Bytes, MediaType.TEXT_PLAIN_TYPE.withCharset("utf-8"));

      GenericEntity<MultipartFormDataOutput> entity =
          new GenericEntity<MultipartFormDataOutput>(mdo) {};
      Response r = target.request().post(Entity.entity(entity, MediaType.MULTIPART_FORM_DATA_TYPE));
      String obj = r.readEntity(String.class);
      LOG.debug("Storage returned: " + obj);
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      // httpclient.getConnectionManager().shutdown();
    }
    return query_uri + "select * from " + tableName + " LIMIT 10";
  }
    protected void addTrigger(
        SchedulerEntry schedulerEntry, ServiceReference<SchedulerEntry> serviceReference) {

      String propertyKey = schedulerEntry.getPropertyKey();

      if (Validator.isNull(propertyKey)) {
        return;
      }

      long bundleId = GetterUtil.getLong(serviceReference.getProperty("bundle.id"), -1);

      String triggerValue = null;

      if (bundleId != 0) {
        Class<?> clazz = schedulerEntry.getClass();

        ClassLoader classloader = clazz.getClassLoader();

        triggerValue = getPluginPropertyValue(classloader, propertyKey);
      } else {
        triggerValue = PrefsPropsUtil.getString(propertyKey);
      }

      if (_log.isDebugEnabled()) {
        _log.debug("Scheduler property key " + propertyKey + " has trigger value " + triggerValue);
      }

      if (Validator.isNotNull(triggerValue)) {
        schedulerEntry.setTriggerValue(triggerValue);
      }
    }
  @Override
  public String getAuthSearchFilter(
      long ldapServerId, long companyId, String emailAddress, String screenName, String userId)
      throws Exception {

    String postfix = getPropertyPostfix(ldapServerId);

    String filter =
        PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_AUTH_SEARCH_FILTER + postfix);

    if (_log.isDebugEnabled()) {
      _log.debug("Search filter before transformation " + filter);
    }

    filter =
        StringUtil.replace(
            filter,
            new String[] {"@company_id@", "@email_address@", "@screen_name@", "@user_id@"},
            new String[] {String.valueOf(companyId), emailAddress, screenName, userId});

    LDAPUtil.validateFilter(filter);

    if (_log.isDebugEnabled()) {
      _log.debug("Search filter after transformation " + filter);
    }

    return filter;
  }
Exemplo n.º 5
0
  protected NtlmManager getNtlmManager(long companyId) {
    String domain =
        PrefsPropsUtil.getString(companyId, PropsKeys.NTLM_DOMAIN, _ntlmConfiguration.domain());
    String domainController =
        PrefsPropsUtil.getString(
            companyId, PropsKeys.NTLM_DOMAIN_CONTROLLER, _ntlmConfiguration.domainController());
    String domainControllerName =
        PrefsPropsUtil.getString(
            companyId,
            PropsKeys.NTLM_DOMAIN_CONTROLLER_NAME,
            _ntlmConfiguration.domainControllerName());
    String serviceAccount =
        PrefsPropsUtil.getString(
            companyId, PropsKeys.NTLM_SERVICE_ACCOUNT, _ntlmConfiguration.serviceAccount());
    String servicePassword =
        PrefsPropsUtil.getString(
            companyId, PropsKeys.NTLM_SERVICE_PASSWORD, _ntlmConfiguration.servicePassword());

    NtlmManager ntlmManager = _ntlmManagers.get(companyId);

    if (ntlmManager == null) {
      ntlmManager =
          new NtlmManager(
              _netlogonConnectionManager,
              domain,
              domainController,
              domainControllerName,
              serviceAccount,
              servicePassword);

      _ntlmManagers.put(companyId, ntlmManager);
    } else {
      if (!Validator.equals(ntlmManager.getDomain(), domain)
          || !Validator.equals(ntlmManager.getDomainController(), domainController)
          || !Validator.equals(ntlmManager.getDomainControllerName(), domainControllerName)
          || !Validator.equals(ntlmManager.getServiceAccount(), serviceAccount)
          || !Validator.equals(ntlmManager.getServicePassword(), servicePassword)) {

        ntlmManager.setConfiguration(
            domain, domainController, domainControllerName, serviceAccount, servicePassword);
      }
    }

    return ntlmManager;
  }
  @Override
  public Properties getContactMappings(long ldapServerId, long companyId) throws Exception {

    String postfix = getPropertyPostfix(ldapServerId);

    Properties contactMappings =
        PropertiesUtil.load(
            PrefsPropsUtil.getString(
                companyId, PropsKeys.LDAP_CONTACT_MAPPINGS + postfix, StringPool.BLANK));

    LogUtil.debug(_log, contactMappings);

    return contactMappings;
  }
  @Override
  public Properties getUserExpandoMappings(long ldapServerId, long companyId) throws Exception {

    String postfix = getPropertyPostfix(ldapServerId);

    Properties userExpandoMappings =
        PropertiesUtil.load(
            PrefsPropsUtil.getString(
                companyId, PropsKeys.LDAP_USER_CUSTOM_MAPPINGS + postfix, StringPool.BLANK));

    LogUtil.debug(_log, userExpandoMappings);

    return userExpandoMappings;
  }
  protected void sendEmail(
      String emailAddress, MemberRequest memberRequest, ThemeDisplay themeDisplay)
      throws Exception {

    long companyId = memberRequest.getCompanyId();

    Group group = groupLocalService.getGroup(memberRequest.getGroupId());

    User user = userLocalService.getUser(memberRequest.getUserId());

    User receiverUser = null;

    if (memberRequest.getReceiverUserId() > 0) {
      receiverUser = userLocalService.getUser(memberRequest.getReceiverUserId());
    }

    String fromName = PrefsPropsUtil.getString(companyId, "admin.email.from.name");
    String fromAddress = PrefsPropsUtil.getString(companyId, "admin.email.from.address");

    String toName = StringPool.BLANK;
    String toAddress = emailAddress;

    if (receiverUser != null) {
      toName = receiverUser.getFullName();
    }

    ClassLoader classLoader = getClass().getClassLoader();

    String subject =
        StringUtil.read(classLoader, "com/liferay/so/invitemembers/dependencies/subject.tmpl");

    String body = StringPool.BLANK;

    if (memberRequest.getReceiverUserId() > 0) {
      body =
          StringUtil.read(
              classLoader,
              "com/liferay/so/invitemembers/dependencies/" + "existing_user_body.tmpl");
    } else {
      body =
          StringUtil.read(
              classLoader, "com/liferay/so/invitemembers/dependencies/" + "new_user_body.tmpl");
    }

    String createAccountURL = getCreateAccountURL(memberRequest.getKey(), themeDisplay);
    String loginURL = getLoginURL(memberRequest.getKey(), themeDisplay);

    subject =
        StringUtil.replace(
            subject,
            new String[] {"[$MEMBER_REQUEST_GROUP$]", "[$MEMBER_REQUEST_USER$]"},
            new String[] {group.getDescriptiveName(), user.getFullName()});

    body =
        StringUtil.replace(
            body,
            new String[] {
              "[$ADMIN_ADDRESS$]",
              "[$ADMIN_NAME$]",
              "[$MEMBER_REQUEST_CREATE_ACCOUNT_URL$]",
              "[$MEMBER_REQUEST_GROUP$]",
              "[$MEMBER_REQUEST_LOGIN_URL$]",
              "[$MEMBER_REQUEST_USER$]"
            },
            new String[] {
              fromAddress,
              fromName,
              createAccountURL,
              group.getDescriptiveName(),
              loginURL,
              user.getFullName()
            });

    InternetAddress from = new InternetAddress(fromAddress, fromName);

    InternetAddress to = new InternetAddress(toAddress, toName);

    MailMessage mailMessage = new MailMessage(from, to, subject, body, true);

    MailServiceUtil.sendEmail(mailMessage);
  }
  protected void sendEmail(WallEntry wallEntry, ThemeDisplay themeDisplay) throws Exception {

    long companyId = wallEntry.getCompanyId();

    String portalURL = PortalUtil.getPortalURL(themeDisplay);
    String layoutURL = PortalUtil.getLayoutURL(themeDisplay);

    String wallEntryURL = portalURL + layoutURL;

    Group group = GroupLocalServiceUtil.getGroup(wallEntry.getGroupId());

    User user = userLocalService.getUserById(group.getClassPK());
    User wallEntryUser = userLocalService.getUserById(wallEntry.getUserId());

    String fromName = PrefsPropsUtil.getString(companyId, "admin.email.from.name");
    String fromAddress = PrefsPropsUtil.getString(companyId, "admin.email.from.address");

    String toName = user.getFullName();
    String toAddress = user.getEmailAddress();

    ClassLoader classLoader = getClass().getClassLoader();

    String subject =
        StringUtil.read(
            classLoader,
            "com/liferay/socialnetworking/wall/dependencies/" + "wall_entry_added_subject.tmpl");
    String body =
        StringUtil.read(
            classLoader,
            "com/liferay/socialnetworking/wall/dependencies/" + "wall_entry_added_body.tmpl");

    subject =
        StringUtil.replace(
            subject,
            new String[] {
              "[$FROM_ADDRESS$]",
              "[$FROM_NAME$]",
              "[$TO_ADDRESS$]",
              "[$TO_NAME$]",
              "[$WALL_ENTRY_URL$]",
              "[$WALL_ENTRY_USER_ADDRESS$]",
              "[$WALL_ENTRY_USER_NAME$]"
            },
            new String[] {
              fromAddress,
              fromName,
              toAddress,
              toName,
              wallEntryURL,
              wallEntryUser.getEmailAddress(),
              wallEntryUser.getFullName()
            });

    body =
        StringUtil.replace(
            body,
            new String[] {
              "[$FROM_ADDRESS$]",
              "[$FROM_NAME$]",
              "[$TO_ADDRESS$]",
              "[$TO_NAME$]",
              "[$WALL_ENTRY_URL$]",
              "[$WALL_ENTRY_USER_ADDRESS$]",
              "[$WALL_ENTRY_USER_NAME$]"
            },
            new String[] {
              fromAddress,
              fromName,
              toAddress,
              toName,
              wallEntryURL,
              wallEntryUser.getEmailAddress(),
              wallEntryUser.getFullName()
            });

    InternetAddress from = new InternetAddress(fromAddress, fromName);

    InternetAddress to = new InternetAddress(toAddress, toName);

    MailMessage mailMessage = new MailMessage(from, to, subject, body, true);

    MailServiceUtil.sendEmail(mailMessage);
  }
  protected void sendEmail(
      String emailAddress, MemberRequest memberRequest, ServiceContext serviceContext)
      throws Exception {

    long companyId = memberRequest.getCompanyId();

    Group group = groupLocalService.getGroup(memberRequest.getGroupId());

    User user = userLocalService.getUser(memberRequest.getUserId());

    User receiverUser = null;

    if (memberRequest.getReceiverUserId() > 0) {
      receiverUser = userLocalService.getUser(memberRequest.getReceiverUserId());
    }

    String fromName = PrefsPropsUtil.getString(companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
    String fromAddress = PrefsPropsUtil.getString(companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);

    String toName = StringPool.BLANK;
    String toAddress = emailAddress;

    if (receiverUser != null) {
      toName = receiverUser.getFullName();
    }

    String subject =
        StringUtil.read(getClassLoader(), "com/liferay/so/invitemembers/dependencies/subject.tmpl");

    String body = StringPool.BLANK;

    if (memberRequest.getReceiverUserId() > 0) {
      body =
          StringUtil.read(
              getClassLoader(),
              "com/liferay/so/invitemembers/dependencies/" + "existing_user_body.tmpl");
    } else {
      body =
          StringUtil.read(
              getClassLoader(),
              "com/liferay/so/invitemembers/dependencies/" + "new_user_body.tmpl");
    }

    subject =
        StringUtil.replace(
            subject,
            new String[] {"[$MEMBER_REQUEST_GROUP$]", "[$MEMBER_REQUEST_USER$]"},
            new String[] {
              group.getDescriptiveName(serviceContext.getLocale()), user.getFullName()
            });

    String createAccountURL = (String) serviceContext.getAttribute("createAccountURL");

    if (Validator.isNull(createAccountURL)) {
      createAccountURL = serviceContext.getPortalURL();
    }

    createAccountURL = HttpUtil.addParameter(createAccountURL, "key", memberRequest.getKey());

    String loginURL = (String) serviceContext.getAttribute("loginURL");

    if (Validator.isNull(loginURL)) {
      loginURL = serviceContext.getPortalURL();
    }

    loginURL = HttpUtil.addParameter(loginURL, "key", memberRequest.getKey());

    body =
        StringUtil.replace(
            body,
            new String[] {
              "[$ADMIN_ADDRESS$]",
              "[$ADMIN_NAME$]",
              "[$MEMBER_REQUEST_CREATE_ACCOUNT_URL$]",
              "[$MEMBER_REQUEST_GROUP$]",
              "[$MEMBER_REQUEST_LOGIN_URL$]",
              "[$MEMBER_REQUEST_USER$]"
            },
            new String[] {
              fromAddress,
              fromName,
              createAccountURL,
              group.getDescriptiveName(serviceContext.getLocale()),
              loginURL,
              user.getFullName()
            });

    InternetAddress from = new InternetAddress(fromAddress, fromName);

    InternetAddress to = new InternetAddress(toAddress, toName);

    MailMessage mailMessage = new MailMessage(from, to, subject, body, true);

    MailServiceUtil.sendEmail(mailMessage);
  }
  @AccessControlled(guestAccessEnabled = true)
  @Override
  public SyncContext getSyncContext() throws PortalException {
    try {
      User user = getGuestOrUser();

      SyncContext syncContext = new SyncContext();

      String authType =
          PrefsPropsUtil.getString(
              CompanyThreadLocal.getCompanyId(),
              PropsKeys.COMPANY_SECURITY_AUTH_TYPE,
              PropsUtil.get(PropsKeys.COMPANY_SECURITY_AUTH_TYPE));

      syncContext.setAuthType(authType);

      boolean oAuthEnabled =
          PrefsPropsUtil.getBoolean(
              user.getCompanyId(),
              PortletPropsKeys.SYNC_OAUTH_ENABLED,
              PortletPropsValues.SYNC_OAUTH_ENABLED);

      if (oAuthEnabled) {
        String oAuthConsumerKey =
            PrefsPropsUtil.getString(user.getCompanyId(), PortletPropsKeys.SYNC_OAUTH_CONSUMER_KEY);

        syncContext.setOAuthConsumerKey(oAuthConsumerKey);

        String oAuthConsumerSecret =
            PrefsPropsUtil.getString(
                user.getCompanyId(), PortletPropsKeys.SYNC_OAUTH_CONSUMER_SECRET);

        syncContext.setOAuthConsumerSecret(oAuthConsumerSecret);
      }

      syncContext.setOAuthEnabled(oAuthEnabled);

      PluginPackage syncWebPluginPackage = DeployManagerUtil.getInstalledPluginPackage("sync-web");

      syncContext.setPluginVersion(syncWebPluginPackage.getVersion());

      if (!user.isDefaultUser()) {
        syncContext.setPortalBuildNumber(ReleaseInfo.getBuildNumber());

        PluginPackage soPortletPluginPackage =
            DeployManagerUtil.getInstalledPluginPackage("so-portlet");

        syncContext.setPortletPreferencesMap(getPortletPreferencesMap());

        if (soPortletPluginPackage != null) {
          syncContext.setSocialOfficeInstalled(true);
        } else {
          syncContext.setSocialOfficeInstalled(false);
        }

        syncContext.setUser(user);
        syncContext.setUserSitesGroups(getUserSitesGroups());
      }

      return syncContext;
    } catch (PortalException pe) {
      throw new PortalException(SyncUtil.buildExceptionMessage(pe), pe);
    }
  }
Exemplo n.º 12
0
  protected GoogleAuthorizationCodeFlow getFlow(long companyId, long scopeGroupId)
      throws IOException, SystemException, PortalException {

    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();

    GoogleAuthorizationCodeFlow.Builder builder = null;

    List<String> scopes = null;

    if (DeployManagerUtil.isDeployed(_GOOGLE_DRIVE_CONTEXT)) {
      scopes = _SCOPES_DRIVE;
    } else {
      scopes = _SCOPES_LOGIN;
    }

    // Try to get Google Client ID and Client Secret for current Site settings

    String googleClientId =
        (String)
            GroupLocalServiceUtil.getGroup(scopeGroupId)
                .getExpandoBridge()
                .getAttribute(GOOGLE_SITE_CLIENT_ID, false);
    String googleClientSecret =
        (String)
            GroupLocalServiceUtil.getGroup(scopeGroupId)
                .getExpandoBridge()
                .getAttribute(GOOGLE_SITE_CLIENT_SECRET, false);

    // If they are not set, then try to get it from Portal settings

    if (Validator.isNull(googleClientId) || Validator.isNull(googleClientSecret)) {

      _log.debug(
          "Client ID and Client Secret was not set for Site, " + "getting from Portal Settings");

      googleClientId = PrefsPropsUtil.getString(companyId, "google.client.id");
      googleClientSecret = PrefsPropsUtil.getString(companyId, "google.client.secret");
    }

    // If they are not set both for Site and Portal settings, then
    // read it from client_secrets.json

    if (Validator.isNull(googleClientId) || Validator.isNull(googleClientSecret)) {

      _log.debug(
          "Client ID and Client Secret was not set for Portal, "
              + "reading JSON code from plugin resources");

      InputStream is = GoogleOAuth.class.getResourceAsStream(_CLIENT_SECRETS_LOCATION);

      GoogleClientSecrets clientSecrets =
          GoogleClientSecrets.load(jsonFactory, new InputStreamReader(is));

      builder =
          new GoogleAuthorizationCodeFlow.Builder(
              httpTransport, jsonFactory, clientSecrets, scopes);
    } else {
      builder =
          new GoogleAuthorizationCodeFlow.Builder(
              httpTransport, jsonFactory, googleClientId, googleClientSecret, scopes);
    }

    String accessType = "online";

    if (DeployManagerUtil.isDeployed(_GOOGLE_DRIVE_CONTEXT)) {
      accessType = "offline";
    }

    builder.setAccessType(accessType);
    builder.setApprovalPrompt("auto");

    return builder.build();
  }