Package org.fluxtream.core.connectors

Examples of org.fluxtream.core.connectors.Connector


        settingsService.persistConnectorSettings(updateInfo.apiKey.getId(), synchedSettings, defaultSettings);
    }

  private void handleUpdateResult(final UpdateInfo updateInfo, UpdateResult updateResult) {
        guestService.setApiKeyToSynching(updateInfo.apiKey.getId(), false);
        final Connector connector = updateInfo.apiKey.getConnector();
        String statusName = updateInfo.apiKey.getConnector().statusNotificationName();
        long guestId=updateInfo.apiKey.getGuestId();
        Notification notification = null;
        switch (updateResult.getType()) {
    case DUPLICATE_UPDATE:
      duplicateUpdate();
      break;
        case AUTH_REVOKED:
            String message = "Your " + connector.prettyName() + " Authorization Token has been revoked.";
            if (updateResult.getAuthRevokedException().isDataCleanupRequested()) {
                guestService.removeApiKey(task.apiKeyId);
                message += "<br>With the revocation info we received, there was an indication that you wanted your " +
                           "data to be permanently deleted from our servers. Consequently we just permanently removed your " +
                            connector.getPrettyName() + " connector and all its associated data.";
            }
            notificationsService.addNamedNotification(updateInfo.getGuestId(), Notification.Type.WARNING,
                                                      connector.statusNotificationName(), message);
            UpdateWorkerTask.AuditTrailEntry failed = new UpdateWorkerTask.AuditTrailEntry(new Date(), updateResult.getType().toString(), "abort");
            abort(updateInfo.apiKey, failed, updateResult.reason);
            break;
        case NEEDS_REAUTH:
            notificationsService.addNamedNotification(updateInfo.getGuestId(), Notification.Type.WARNING,
                                                      connector.statusNotificationName(),
                                                      "Heads Up. Your " + connector.prettyName() + " Authorization Token has expired.<br>" +
                                                      "Please head to <a href=\"javascript:App.manageConnectors()\">Manage Connectors</a>,<br>" +
                                                      "scroll to the " + connector.prettyName() + " section, and renew your tokens (look for the <i class=\"icon-resize-small icon-large\"></i> icon)");
            failed = new UpdateWorkerTask.AuditTrailEntry(new Date(), updateResult.getType().toString(), "abort");
            failed.stackTrace = updateResult.stackTrace;
            abort(updateInfo.apiKey, failed, updateResult.reason);
            break;
    case HAS_REACHED_RATE_LIMIT:
            final UpdateWorkerTask.AuditTrailEntry rateLimit = new UpdateWorkerTask.AuditTrailEntry(new Date(), updateResult.getType().toString(), "long reschedule");
            rateLimit.stackTrace = updateResult.stackTrace;
            // do this only if a notification is visible for that connector at this time
            notification = notificationsService.getNamedNotification(guestId,statusName);
            if (notification!=null && notification.deleted==false) {
                notificationsService.addNamedNotification(guestId, Notification.Type.INFO,
                                                          statusName,
                                                          "<i class=\"icon-time\" style=\"margin-right:7px\"/>Import of your " + updateInfo.apiKey.getConnector().getPrettyName() + " data is delayed due to API rate limitations. Please, be patient.");
            }
      rescheduleAccordingToQuotaSpecifications(updateInfo, rateLimit);
      break;
    case UPDATE_SUCCEEDED:
            // Check for existing status notification
            notification = notificationsService.getNamedNotification(guestId,statusName);
            if (notification!=null && notification.deleted==false) {
                // This is either an initial history update or there's an existing visible status notification.
                // Update the notification to show the update succeeded.
                notificationsService.addNamedNotification(guestId, Notification.Type.INFO,
                                                          statusName,
                                                          "<i class=\"icon-ok\" style=\"margin-right:7px\"/>Your " + updateInfo.apiKey.getConnector().getPrettyName() + " data was successfully imported.  " +
                                                          "See <a href=\"javascript:App.manageConnectors()\">Manage Connectors</a> dialog for details.");
            }
      success(updateInfo.apiKey);
      break;
    case UPDATE_FAILED:
        case UPDATE_FAILED_PERMANENTLY:
            failed = new UpdateWorkerTask.AuditTrailEntry(new Date(), updateResult.getType().toString(), "abort");
            failed.stackTrace = updateResult.stackTrace;
            connectorUpdateService.addAuditTrail(task.getId(), failed);
            final UpdateWorkerTask.AuditTrailEntry retry = new UpdateWorkerTask.AuditTrailEntry(new Date(), updateResult.getType().toString(), "retry");
            retry.stackTrace = updateResult.stackTrace;
            // Consider this a transient failure and retry if the failure type was not permanent
            // and the current status of the connector instance is not already STATUS_PERMANENT_FAILURE.
            //
            if(updateResult.getType()==UpdateResult.ResultType.UPDATE_FAILED &&
               updateInfo.apiKey.getStatus()!=ApiKey.Status.STATUS_PERMANENT_FAILURE) {
                retry(updateInfo, retry);
            }
            else {
                // This was a permanent failure, so we should set status to permanent failure and
                // we should not retry
                abort(updateInfo.apiKey, failed, updateResult.reason);
            }
            if (updateInfo.getUpdateType()== UpdateInfo.UpdateType.INITIAL_HISTORY_UPDATE)
                notificationsService.addNamedNotification(updateInfo.apiKey.getGuestId(), Notification.Type.ERROR,
                                                          connector.statusNotificationName(),
                                                          "<i class=\"icon-remove-sign\" style=\"color:red;margin-right:7px\"/>There was a problem while importing your " + connector.getPrettyName() + " data. We will try again later.  " +
                                                          "See <a href=\"javascript:App.manageConnectors()\">Manage Connectors</a> dialog for details."
                );
      break;
    case NO_RESULT:
      abort(updateInfo.apiKey, null, updateResult.reason);
View Full Code Here


    }

    @Override
    public <T extends AbstractFacet> List<T> filterFacets(final long viewerId, final long apiKeyId, final List<T> facets) {
        final ApiKey apiKey = guestService.getApiKey(apiKeyId);
        final Connector connector = apiKey.getConnector();
        final boolean ownFacets = viewerId == apiKey.getGuestId();
        final boolean supportsFiltering = connector.supportsFiltering();
        if (ownFacets ||!supportsFiltering)
            return facets;
        else {
            // retrieve SharedConnector instance;
            SharedConnector sharedConnector = getSharedConnector(apiKeyId, viewerId);
            if (sharedConnector!=null) {
                final SharedConnectorFilter sharedConnectorFilter;
                try {
                    sharedConnectorFilter = beanFactory.getBean(connector.sharedConnectorFilterClass());
                    return sharedConnectorFilter.filterFacets(sharedConnector, facets);
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
View Full Code Here

        Map<String, TimeInterval> photoChannelTimeRanges = new HashMap<String, TimeInterval>();

        List<ApiKey> userKeys = guestService.getApiKeys(guestId);
        for (ApiKey apiKey : userKeys) {
            Connector connector = null;
            if (apiKey != null) {
                connector = apiKey.getConnector();
            }
            if (connector != null && connector.getName() != null &&
                (coachee == null || coachee.hasAccessToConnector(connector.getName())) && connector.hasImageObjectType()) {
                // Check the object types, if any, to find the image object type(s)
                ObjectType[] objectTypes = apiKey.getConnector().objectTypes();
                if (objectTypes == null) {
                    final String channelName = constructChannelName(connector, null);
                    final TimeInterval timeInterval = constructTimeIntervalFromOldestAndNewestFacets(apiKey, null);
View Full Code Here

        SortedSet<Photo> photos = new TreeSet<Photo>();

        if (ALL_DEVICES_NAME.equals(connectorPrettyName)) {
            List<ApiKey> userKeys = guestService.getApiKeys(guestId);
            for (ApiKey apiKey : userKeys) {
                Connector connector = null;
                if (apiKey != null && apiKey.getConnector() != null) {
                    connector = apiKey.getConnector();
                }
                if (connector != null && connector.hasImageObjectType()) {
                    final ObjectType[] objectTypes = connector.objectTypes();
                    if (objectTypes != null) {
                        for (ObjectType objectType : objectTypes) {
                            if (objectType.isImageType()) {
                                List<AbstractFacet> facets = facetFinderStrategy.find(apiKey, objectType, tagFilter);
                                photos.addAll(convertFacetsToPhotos(apiKey, timeInterval, facets, connector, objectType));
                            }
                        }
                    }
                }
            }
        }
        else {
            final ApiKey apiKey = findConnectorApiKeyByPrettyName(guestId, connectorPrettyName);
            if (apiKey != null && apiKey.getConnector() != null) {
                final Connector connector = apiKey.getConnector();
                final ObjectType desiredObjectType = findObjectTypeByName(connector, objectTypeName);

                if (desiredObjectType == null) {
                    final Map<ObjectType, List<AbstractFacet>> facetsByObjectType = facetFinderStrategy.find(apiKey, tagFilter);
                    if ((facetsByObjectType != null) && (!facetsByObjectType.isEmpty())) {
View Full Code Here

    /** Returns the Connector having the given pretty name.  Returns <code>null</code> if no such connector exists. */
    private ApiKey findConnectorApiKeyByPrettyName(final long guestId, final String connectorPrettyName) {
        List<ApiKey> userKeys = guestService.getApiKeys(guestId);
        for (ApiKey key : userKeys) {
            if (key != null) {
                final Connector connector = key.getConnector();
                if (connector != null && ((connector.prettyName() != null && connector.prettyName().equals(connectorPrettyName)) || (connector.getName().equals(connectorPrettyName)))) {
                    return key;
                }
            }
        }

View Full Code Here

        JSONArray connectorsArray = new JSONArray();
        boolean missingKeys=false;

        for (int i = 0; i < connectors.size(); i++) {
            final ConnectorInfo connectorInfo = connectors.get(i);
            final Connector api = connectorInfo.getApi();
            if (api == null) {
                StringBuilder sb = new StringBuilder("module=SystemServiceImpl component=connectorStore action=checkConnectorInstanceKeys ")
                        .append("message=\"null connector for " + connectorInfo.getName() + "\"");
                logger.warn(sb.toString());
                continue;
            }
            if(connectorInfo.enabled==false) {
                StringBuilder sb = new StringBuilder("module=SystemServiceImpl component=connectorStore action=checkConnectorInstanceKeys ")
                        .append("message=\"skipping connector instance keys check for disabled connector" + connectorInfo.getName() + "\"");
                logger.info(sb.toString());
                continue;
            }
            String[] apiKeyAttributeKeys = connectorInfo.getApiKeyAttributesKeys();
            if(apiKeyAttributeKeys==null) {
                StringBuilder sb = new StringBuilder("module=SystemServiceImpl component=connectorStore action=checkConnectorInstanceKeys ")
                        .append("message=\"skipping connector instance keys check for connector" + connectorInfo.getName() + "; does not use keys\"");
                logger.info(sb.toString());
                continue;
            }
            // This connector type is enabled, find all the instance keys for this connector type
            List<ApiKey> apiKeys = JPAUtils.find(em, ApiKey.class, "apiKeys.all.byApi", api.value());
            for(ApiKey apiKey: apiKeys) {
                StringBuilder sb = new StringBuilder("module=SystemServiceImpl component=connectorStore action=checkConnectorInstanceKeys apiKeyId=" + apiKey.getId())
                                .append(" message=\"checking connector instance keys for connector" + connectorInfo.getName() + "\"");

                logger.info(sb.toString());

                // Iterate over the apiKeyAttributeKeys to check if each is present
                for(String apiKeyAttributeKey: apiKeyAttributeKeys) {
                    String apiKeyAttributeValue = guestService.getApiKeyAttribute(apiKey, apiKeyAttributeKey);
                    if(apiKeyAttributeValue==null) {
                        missingKeys=true;
                        String msg = "**** Missing key \"" + apiKeyAttributeKey + "\" for apiKeyId=" + apiKey.getId() + " api=" + api.value()
                                ;
                        StringBuilder sb2 = new StringBuilder("module=SystemServiceImpl component=connectorStore action=checkConnectorInstanceKeys apiKeyId=" + apiKey.getId())
          .append(" message=\"").append(msg).append("\"");
                        logger.info(sb2.toString());
                        System.out.println(msg);
View Full Code Here

public class ViewsHelper<T> {
 
  public static List<ConnectorModel> toConnectorModels(List<ApiKey> keys) {
    List<ConnectorModel> vos = new ArrayList<ConnectorModel>();
    for (ApiKey key : keys) {
      Connector connector = key.getConnector();
      if (connector!=null) {
        vos.add(ViewsHelper.connectorModel(connector));     
      }
    }
    return vos;
View Full Code Here

 
  @RequestMapping(value = "/swapToken")
  public ModelAndView upgradeToken(HttpServletRequest request) throws IOException, UnexpectedHttpResponseCodeException {

        String scope = (String) request.getSession().getAttribute("oauth2Scope");
        Connector scopedApi = systemService.getApiFromGoogleScope(scope);

        Guest guest = AuthHelper.getGuest();

        String errorParameter = request.getParameter("error");
        if (errorParameter!=null) {
            notificationsService.addNamedNotification(guest.getId(), Notification.Type.WARNING,
                                                      scopedApi.statusNotificationName(),
                                                      "There was a problem importing your " + scopedApi.prettyName() + " data: " + errorParameter);
            return new ModelAndView("redirect:/app/");
        }

    String swapTokenUrl = "https://accounts.google.com/o/oauth2/token";
    String code = request.getParameter("code");
    String redirectUri = ControllerSupport.getLocationBase(request, env) + "google/oauth2/swapToken";
   
    Map<String,String> params = new HashMap<String,String>();
    params.put("code", code);
    params.put("client_id", env.get("google.client.id"));
    params.put("client_secret", env.get("google.client.secret"));
    params.put("redirect_uri", redirectUri);
    params.put("grant_type", "authorization_code");

      // Get the google branding info.  Default to fluxtream if not set, but can override in
      // oauth.properties by setting the default google.client.brandName parameter
      String brandName = env.get("google.client.brandName");
      if(brandName == null) {
         // Not set in oauth.properties file, default to "Fluxtream"
         brandName="Fluxtream";
      }

      // Try to renew the token.  On failure leave token=null
      JSONObject token = null;

      try {
         String fetched = HttpUtils.fetch(swapTokenUrl, params);
         token = JSONObject.fromObject(fetched);
      } catch(Throwable e) {
         token = null;
      }

        ApiKey apiKey;
        final boolean isRenewToken = request.getSession().getAttribute(APIKEYID_ATTRIBUTE) != null;
        if (isRenewToken) {
            String apiKeyId = (String)request.getSession().getAttribute(APIKEYID_ATTRIBUTE);
            apiKey = guestService.getApiKey(Long.valueOf(apiKeyId));
            if (apiKey==null) {
                Exception e = new Exception();
                String stackTrace = ExceptionUtils.getStackTrace(e);
                String errorMessage = "no apiKey with id '%s'... It looks like you are trying to renew the tokens of a non-existing Connector (/ApiKey)";
                return errorController.handleError(500, errorMessage, stackTrace);
            }

            if (token == null || !token.has("refresh_token")) {
                String message = (new StringBuilder("<p>We couldn't get your oauth2 refresh token.  "))
                        .append("Something went wrong.</p>")
                        .append("<p>You'll have to surf to your ")
                        .append("<a target='_new'  href='https://accounts.google.com/b/0/IssuedAuthSubTokens'>token mgmt page at Google</a> ")
                        .append("and hit \"Revoke Access\" next to \"").append(brandName).append(" — ").append(getGooglePrettyName(scopedApi)).append("\"</p>")
                      .append("<p>Then please, head to <a href=\"javascript:App.manageConnectors()\">Manage Connectors</a> ")
                      .append("and renew your tokens (look for the <i class=\"icon-resize-small icon-large\"></i> icon)</p>")
                        .append("<p>We apologize for the inconvenience</p>").toString();

                notificationsService.addNamedNotification(guest.getId(),
                                                     Notification.Type.ERROR,
                                                     apiKey.getConnector().statusNotificationName(),
                                                     message);
                // Record permanent failure since this connector won't work again until
                // it is reauthenticated
                guestService.setApiKeyStatus(apiKey.getId(), ApiKey.Status.STATUS_PERMANENT_FAILURE, null, ApiKey.PermanentFailReason.NEEDS_REAUTH);
                return new ModelAndView("redirect:/app");
            }

            // Remove oauth1 keys if upgrading from previous connector version.
            // Remember whether or not we're upgrading from previous connector version.
            // If so, do a full history update.  Otherwise don't force a full
            // history update and allow the update to be whatever it normally would be
            boolean upgradeFromOauth1 = false;

            if (guestService.getApiKeyAttribute(apiKey, "googleConsumerKey")!=null) {
                guestService.removeApiKeyAttribute(apiKey.getId(), "googleConsumerKey");
                upgradeFromOauth1 = true;
            }
            if (guestService.getApiKeyAttribute(apiKey, "googleConsumerSecret")!=null) {
                guestService.removeApiKeyAttribute(apiKey.getId(), "googleConsumerSecret");
                upgradeFromOauth1 = true;
            }

            // If upgradeFromOauth1 reset the connector to force a full reimport on google calendar,
            // otherwise just do a normal update
            if (apiKey.getConnector().getName().equals("google_calendar")) {
                connectorUpdateService.flushUpdateWorkerTasks(apiKey, upgradeFromOauth1);
            }

        } else {
            apiKey = guestService.createApiKey(guest.getId(), scopedApi);
        }

        // We need to store google.client.id and google.client.secret with the
        // apiKeyAttributes in either the case of original creation of the key
        // or token renewal.  createApiKey actually handles the former case, but
        // not the latter.  Do it in all cases here.
        guestService.setApiKeyAttribute(apiKey, "google.client.id", env.get("google.client.id"));
        guestService.setApiKeyAttribute(apiKey, "google.client.secret", env.get("google.client.secret"));

        final String refresh_token = token.getString("refresh_token");

        guestService.setApiKeyAttribute(apiKey,
        "accessToken", token.getString("access_token"));
    guestService.setApiKeyAttribute(apiKey,
        "tokenExpires", String.valueOf(System.currentTimeMillis() + (token.getLong("expires_in")*1000)));
        guestService.setApiKeyAttribute(apiKey,
        "refreshToken", refresh_token);
        final String encodedRefreshToken = URLEncoder.encode(refresh_token, "UTF-8");
        guestService.setApiKeyAttribute(apiKey,
                                        "refreshTokenRemoveURL",
                                        "https://accounts.google.com/o/oauth2/revoke?token="
                                        + encodedRefreshToken);

        // Record this connector as having status up
        guestService.setApiKeyStatus(apiKey.getId(), ApiKey.Status.STATUS_UP, null, null);
        // Schedule an update for this connector
        connectorUpdateService.updateConnector(apiKey, false);

        if (isRenewToken) {
            request.getSession().removeAttribute(APIKEYID_ATTRIBUTE);
            return new ModelAndView("redirect:/app/tokenRenewed/"+scopedApi.getName());
        }
        return new ModelAndView("redirect:/app/from/"+scopedApi.getName());
    }
View Full Code Here

            throw new RuntimeException("Unexpected number of parameters: " + parameters.length);
        int api = Integer.valueOf(parameters[0]);
        int objectType = Integer.valueOf(parameters[1]);
        long facetId = Long.valueOf(parameters[2]);
        final AbstractFacetVO<AbstractFacet> facet = apiDataService.getFacet(api, objectType, facetId);
        final Connector connector = Connector.fromValue(facet.api);
        String facetName = String.format("%s.%s", connector.getName(), ObjectType.getObjectType(connector, facet.objectType));
        ModelAndView mav = new ModelAndView("openGraph/" + facetName);
        mav.addObject("facet", facet);
        mav.addObject("metadataService", metadataService);
        return mav;
    }
View Full Code Here

        return home(request, response);
    }

    @RequestMapping(value = "/app/tokenRenewed/{connectorName}")
    public String tokenRenewed(@PathVariable("connectorName") String connectorName) {
        final Connector connector = Connector.getConnector(connectorName);
        String message = "You have successfully renewed your "
                         + connector.prettyName()
                         + " authentication tokens. We will now update your data.";
        return welcomeBack(connectorName, message);
    }
View Full Code Here

TOP

Related Classes of org.fluxtream.core.connectors.Connector

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.