コード例 #1
0
ファイル: RemoveUserAction.java プロジェクト: piyush76/EMS
  public ActionForward executeInContext(
      UserContext uc,
      ActionMapping mapping,
      ActionForm actionForm,
      HttpServletRequest request,
      HttpServletResponse response) {
    int uid = Integer.parseInt(request.getParameter(Constants.USER_ID_FULL));
    int custID = Integer.parseInt(request.getParameter(Constants.CUSTOMER_ID));
    IUserManager um = ManagementContainer.getInstance().getUserManager();

    UserAccount user = um.getUserAccount(custID, uid);

    if (user == null) {
      return mapping.findForward(FAILURE);
    }

    try {
      um.deleteEpaUser(user.getPrimaryEmail());
    } catch (Exception ex) {
      reportSingleError(
          request, ActionMessages.GLOBAL_MESSAGE, "error.epa.user.delete.error", ex.getMessage());
      return mapping.findForward(FAILURE);
    }

    IAuditManager auditManager = ManagementContainer.getInstance().getAuditManager();
    auditManager.saveAudit(
        IAuditManager.AuditCategory.EPA_MGMT,
        "Removed EPA user " + user.getDisplayName() + " ( " + user.getPrimaryEmail() + " )",
        "Remove EPA User Audit",
        null,
        uc.getCurrentUser().getPrimaryEmail());
    return mapping.findForward(SUCCESS);
  }
コード例 #2
0
  /** @param userPath */
  public static String formatUrl(String userPath) {

    ManagementContainer mc = ManagementContainer.getInstance();
    String prefix = mc.getClientSupportManager().getUrlPrefix();
    StringBuilder sb = new StringBuilder(80);
    sb.append(prefix);
    sb.append(userPath);
    return sb.toString();
  }
コード例 #3
0
ファイル: TopologyHandler.java プロジェクト: piyush76/EMS
  public static String saveTopologyData(Customer cust, TopologyData3 td) {
    String text = null;
    try {
      boolean needRollback = true;
      Connection c =
          ManagementContainer.getInstance().getDBConnection(ManagementContainer.POOL_NAME);
      try {
        TopologyStats ts = saveTopologyData(cust, td, c);
        if (td.getRunType() != DirectoryData.TYPE_MANUAL_NOCOMMIT) {
          c.commit();
          needRollback = false;
        }

        switch (td.getRunType()) {
          case DirectoryData.TYPE_MANUAL_FORCED:
            text =
                s_topologySuccessMessageForced.format(
                    new Object[] {
                      ts.getAdminGroupCount(), ts.getRoutingGroupCount(),
                      ts.getServerCount(), ts.getStoreCount()
                    });
            break;
          case DirectoryData.TYPE_MANUAL_NOCOMMIT:
            text =
                s_topologySuccessMessageNoCommit.format(
                    new Object[] {
                      ts.getAdminGroupCount(), ts.getRoutingGroupCount(),
                      ts.getServerCount(), ts.getStoreCount()
                    });
            break;
          default:
            text =
                s_topologySuccessMessage.format(
                    new Object[] {
                      ts.getAdminGroupCount(), ts.getRoutingGroupCount(),
                      ts.getServerCount(), ts.getStoreCount()
                    });
        }

        return text;
      } finally {
        if (needRollback) {
          c.rollback();
        }
        ManagementContainer.getInstance().safeReturnDBConnection(c, ManagementContainer.POOL_NAME);
        // report info **after** connection is closed
        if (s_logger.isDebugEnabled()) {
          s_logger.debug("saveTopologyData completed: " + text);
        }
      }
    } catch (Exception e) {
      s_logger.error("Exception while saving the topology data.", e);
      return "An error occurred while saving the topology data.";
    }
  }
コード例 #4
0
ファイル: TopologyHandler.java プロジェクト: piyush76/EMS
 /**
  * Log all policies that are using the set of removed topology objects
  *
  * @param operation Which operation are we performing wrt the topology object
  * @param topologyType The type of topology object to log against.
  * @param deletedNodes Collection of the id's of the Topology Nodes that were deleted.
  * @param constraintName The name of the constraint within a user set for the topology type
  *     specified in the topologyType property
  */
 protected void logPoliciesUsingRemovedTopologyObjs(
     final String operation,
     final String topologyType,
     final Collection<Integer> deletedNodes,
     final String constraintName) {
   ManagementContainer mc = ManagementContainer.getInstance();
   ITransactionManager pool;
   pool = mc.getPool(ManagementContainer.POOL_NAME);
   pool.executeWithConnection(
       new ConnectionExecuteFunction<Object>() {
         public Object execute(Connection c) throws SQLException {
           logPoliciesUsingRemovedTopologyObjs(
               operation, topologyType, deletedNodes, constraintName, c);
           return null;
         }
       });
 }
コード例 #5
0
ファイル: RimInstall.java プロジェクト: piyush76/EMS
  static {
    String debugProp =
        ManagementContainer.getInstance().getConfiguration().getProperty("DevelopmentDebug");

    // There are cases where the assumptions for unix conflict with our windows development
    // environment.
    if ((debugProp != null) && debugProp.equalsIgnoreCase("true")) {
      m_devDebug = true;
    }
  }
コード例 #6
0
ファイル: TopologyHandler.java プロジェクト: piyush76/EMS
 /** Purge all topology objects that are marked as deleted and the purge time has passed */
 public static void purgeDeletedToplogyObjects() {
   ManagementContainer mc = ManagementContainer.getInstance();
   ITransactionManager pool;
   pool = mc.getPool(ManagementContainer.POOL_NAME);
   Set<Integer> custIds =
       pool.executeWithConnection(
           new ConnectionExecuteFunction<Set<Integer>>() {
             public Set<Integer> execute(Connection c) throws SQLException {
               return purgeDeletedToplogyObjects(c);
             }
           });
   // must run the following refresh queries after the transaction above is committed
   if (!CollectionsUtils.isNullOrEmpty(custIds)) {
     for (Integer custID : custIds) {
       ManagementContainer.getInstance()
           .getPolicyMetaManager()
           .notifyOfExternalPolicyChanges(custID);
     }
   }
 }
コード例 #7
0
  public boolean execute(CommandLine cmdLine) {
    ICustomerManager cm = m_container.getCustomerManager();
    List<String> domains = Collections.singletonList(ICustomerManager.EPA_CUSTOMER_DOMAIN);
    IIslandManager im = m_container.getIslandManager();
    int defaultIslandID = im.getDefaultIsland().getId();

    Customer cust =
        cm.createCustomer(
            ICustomerManager.EPA_CUSTOMER_NAME,
            "System", // fromAddress
            "System", // backendID
            "System", // templateID
            "System", // channel
            domains,
            "emsRootPW", // emsRootPassword
            false, // isPartialEnabled
            "System", // activeBrandKey
            "System", // externalID
            defaultIslandID,
            defaultIslandID,
            false);

    PasswordPolicy policy = new PasswordPolicy();
    policy.setUseStrongPasswords(true);
    cust.setPasswordPolicy(policy);
    cm.updateCustomers(Collections.singletonList(cust));

    IUserManager um = ManagementContainer.getInstance().getUserManager();
    UserAccount emsRoot = um.getUser("emsroot@" + ICustomerManager.EPA_CUSTOMER_DOMAIN);
    IAuthenticationManager am = ManagementContainer.getInstance().getAuthenticationManager();
    long seconds = 31556926; // Seconds in a year
    long time =
        System.currentTimeMillis() + (seconds * 100 * 1000L); // Lock the account for 100 years
    am.lockUserAccount(
        cust.getCustID(), emsRoot.getUserID(), "Locked from user details", "Unknown", time);

    return (cust != null);
  }
コード例 #8
0
  @BeforeMethod
  public void setUp() throws Exception {
    // do cleanup of other tests that may have started writers.
    // this is necessary in a non-forked test suite environment
    // where partition ids could collide
    Utils.finishBackupWriters();

    m_tmpDir = new File(System.getProperty("java.io.tmpdir"), "PartitionStoreStageTest");
    if (!m_tmpDir.exists()) {
      assertTrue("Failed to make the directories.", m_tmpDir.mkdirs());
    }

    // Add a dummy partition
    String server = "test";
    String storage = m_tmpDir + "/storage";

    File storageDir = new File(storage);
    if (!storageDir.exists()) {
      assertTrue("Failed to make the storage directory.", storageDir.mkdirs());
      if (!storageDir.exists()) {
        s_logger.warn("Storage Directory " + storage + " does not exist.");
      }
    }

    String mapped = m_tmpDir + "/mapped";

    File mappedDir = new File(mapped);
    if (!mappedDir.exists()) {
      assertTrue("Failed to make the mapped directories.", mappedDir.mkdirs());
      if (!mappedDir.exists()) {
        s_logger.warn("Storage Directory " + mapped + " does not exist.");
      }
    }

    if (m_part == null) {
      IPartitionManager pm = ManagementContainer.getInstance().getPartitionManager();
      m_part = pm.initializePartition(TEST_PID, server, storage, mapped);
    }
    Utils.startBackupWriters();
  }
コード例 #9
0
  @Test
  public void testBackupFailure() throws Exception {
    IPartitionManager pm = ManagementContainer.getInstance().getPartitionManager();

    m_part.setAccessibleRemotely(true);
    pm.updatePartition(m_part);
    m_part = pm.getPartition(TEST_PID);

    Customer cust =
        TestUtils.createActiveMailboxTestCustomer(Capabilities.ActiveMailboxSupport.ARCHIVE);
    try {
      MockMessageImporter mock = new MockMessageImporter(getClass().getSimpleName());
      PartitionStoreStage stg =
          new PartitionStoreStage(mock) {
            public void finish() {
              super.finish();
              ((StatComponent) m_importer.getStatComponent()).stop();
            }
          };
      MockStageController ctrl = new MockStageController("test");
      stg.setStageController(ctrl);

      assertEquals(0, mock.getNumFailedMessages());
      assertEquals(0, mock.getNumSucceededMessages());
      // Partition dummyPart = new Partition(10, "sdcvsdv");

      File backupSubDir = new File(m_part.getStorageDirectory(), Partition.BACKUP_SUBDIR);

      Pair<Partition, List<IMessageContext>> buffer =
          new Pair<Partition, List<IMessageContext>>(
              m_part, generateMockMessageContext(10000, 10, cust));

      stg.process(buffer);

      // Nothing should have failed
      assertEquals(0, mock.getNumFailedMessages());
      assertEquals(10, ctrl.getOutputCount());

      assertTrue(backupSubDir.exists());

      // Stop backup writers, delete backup directory and then make sure everything works when we
      // start back up
      Utils.finishBackupWriters();

      FileUtils.deleteDirectory(backupSubDir);

      assertFalse(backupSubDir.exists());
      Utils.startBackupWriters();

      ctrl.resetOutputCount();
      buffer =
          new Pair<Partition, List<IMessageContext>>(
              m_part, generateMockMessageContext(100000, 10, cust));

      stg.process(buffer);

      // Nothing should have failed
      assertEquals(0, mock.getNumFailedMessages());
      assertEquals(10, ctrl.getOutputCount());

      assertTrue(backupSubDir.exists());
      stg.finish();
    } finally {
      TestUtils.quietDeleteCustomer(cust);
    }
  }
コード例 #10
0
  /**
   * Validates that the stage properly identifies when a SNAException has occured on a message
   * multiple times consecutively and properly fails the message
   *
   * @throws Exception on error
   */
  @Test
  public void testServiceNotAvailableExceptionHandling() throws Exception {
    MockMessageImporter mock = new MockMessageImporter(getClass().getSimpleName());
    PartitionStoreStage stg =
        new PartitionStoreStage(mock) {
          public void finish() {
            super.finish();
            ((StatComponent) m_importer.getStatComponent()).stop();
          }
        };
    stg.setStageController(new MockStageController("test"));

    final IPartitionProxy partitionProxy = createNiceMock(IPartitionProxy.class);

    assertEquals(0, mock.getNumFailedMessages());
    assertEquals(0, mock.getNumSucceededMessages());

    String path = m_tmpDir + "/storage";
    Partition dummyPart = null;
    try {

      int messageBufferSize = 10;
      Customer cust =
          TestUtils.createActiveMailboxTestCustomer(Capabilities.ActiveMailboxSupport.ARCHIVE);
      List<IMessageContext> msgs = generateMockMessageContext(100, messageBufferSize, cust);

      // force an exception on any call to storeMessages
      expect(partitionProxy.storeMessages(msgs))
          .andThrow(new IPartitionProxy.ServiceNotAvailableException(new Exception()))
          .anyTimes();
      replay(partitionProxy);

      PartitionManager pm =
          new PartitionManager(
              ManagementContainer.getInstance().getPool(ManagementContainer.AM_POOL_NAME)) {
            @Override
            public IPartitionProxy getContentProxy(int id) {
              return partitionProxy;
            }
          };
      PartitionManagerTest.preparePartitionManager(pm);
      stg.setPartitionManager(pm);
      dummyPart = pm.initializePartition(TEST_PID2, "localhost", path, null);
      s_logger.debug("Dummy Partition: " + dummyPart + " (type: " + dummyPart.getClass() + ")");
      Pair<Partition, List<IMessageContext>> buffer =
          new Pair<Partition, List<IMessageContext>>(dummyPart, msgs);

      for (int i = 0; i < stg.getErrorThreshold(); i++) {
        stg.process(buffer);
        assertEquals("Wrong number of failed messages.", 0, mock.getNumFailedMessages());
        assertEquals("Wrong number of succeeded messages.", 0, mock.getNumSucceededMessages());
      }

      stg.process(buffer);
      assertEquals(
          "Wrong number of failed messages", messageBufferSize, mock.getNumFailedMessages());
      assertEquals("Wrong number of succeeded messages", 0, mock.getNumSucceededMessages());

      // Test that errors must come from the same importer before they can fail a message
      mock = new MockMessageImporter(getClass().getSimpleName());
      MockMessageImporter mock2 = new MockMessageImporter(getClass().getSimpleName());
      PartitionStoreStage stg2 = new PartitionStoreStage(mock2);
      stg2.setPartitionManager(pm);
      stg2.setStageController(new MockStageController("test"));
      stg.finish();
      stg = new PartitionStoreStage(mock);
      stg.setStageController(new MockStageController("test"));
      stg.setPartitionManager(pm);

      buffer = new Pair<Partition, List<IMessageContext>>(dummyPart, msgs);

      // Send the message buffer through Threshold - 1 times using importer 1 and then 1 time with
      // importer 2 which should not result in failure
      // Then send the messages through importer 1 again Threshold times and verify it only fails
      // the messages once we have reached threshold
      for (int i = 0; i < stg.getErrorThreshold(); i++) {
        stg.process(buffer);
        assertEquals(0, mock.getNumFailedMessages());
        assertEquals(0, mock.getNumSucceededMessages());
      }

      stg2.process(buffer);
      assertEquals(0, mock2.getNumFailedMessages());
      assertEquals(0, mock2.getNumSucceededMessages());
      assertEquals(0, mock.getNumFailedMessages());
      assertEquals(0, mock.getNumSucceededMessages());
      for (int i = 0; i < stg.getErrorThreshold(); i++) {
        stg.process(buffer);
        assertEquals(0, mock.getNumFailedMessages());
        assertEquals(0, mock.getNumSucceededMessages());
      }

      stg.process(buffer);
      assertEquals(messageBufferSize, mock.getNumFailedMessages());
      assertEquals(0, mock.getNumSucceededMessages());

      // Now validate that age comes into play as well
      mock = new MockMessageImporter(getClass().getSimpleName());
      stg.finish();
      stg = new PartitionStoreStage(mock);
      stg.setStageController(new MockStageController("test"));
      stg.setErrorAgeThreshold(5000);
      stg.setPartitionManager(pm);
      buffer =
          new Pair<Partition, List<IMessageContext>>(
              m_part, generateMockMessageContext(1000, messageBufferSize, cust));

      for (int i = 0; i < stg.getErrorThreshold(); i++) {
        stg.process(buffer);
        assertEquals("Wrong number of failed messages", 0, mock.getNumFailedMessages());
        assertEquals("Wrong number of succeeded messages", 0, mock.getNumSucceededMessages());
      }

      // Thread.sleep( 6000 );
      stg.process(buffer);
      stg.finish();
      stg2.finish();
      assertEquals(0, mock.getNumFailedMessages());
      assertEquals(0, mock.getNumSucceededMessages());
    } finally {

    }
  }
コード例 #11
0
  @Test
  public void testFailureTracking() throws Exception {
    final IPartitionProxy partitionProxy = createNiceMock(IPartitionProxy.class);
    final IPartitionProxy partitionProxy2 = createNiceMock(IPartitionProxy.class);
    long msgId = 2L;
    IFailureTrackingManager failMgr = ManagementContainer.getInstance().getFailureTrackingManager();
    StorageImporter importer = new MockStorageImporter();
    Customer customer = TestUtils.createTestCustomer();
    try {
      PartitionStoreStage stage = new PartitionStoreStage(importer);
      Pipeline pipeline =
          PipelineBuilder.start(
                  ManagementContainer.getInstance().getConfiguration(),
                  MessageImporter.PIPELINE_CONFIG_SECTION)
              .singleton("store-stage", stage)
              .get();
      File envelopeFile =
          File.createTempFile(
              "PartitionStoreTest", "test", ManagementContainer.getInstance().getNfsRoot());
      IMessageContext msgCtx = new MessageContext(envelopeFile, null);
      msgCtx.setCustomer(customer);
      msgCtx.setIndexMessage(true);
      msgCtx.setInternalId(msgId);
      msgCtx.setPartition(m_part);
      msgCtx.setPartitionID(m_part.getId());
      Collection<IMessageContext> msgs = Collections.singletonList(msgCtx);
      Collection<IMessageContext> emptyResult = Collections.emptyList();

      expect(partitionProxy.storeMessages(msgs)).andReturn(emptyResult).anyTimes();
      replay(partitionProxy);

      PartitionManager pm =
          new PartitionManager(
              ManagementContainer.getInstance().getPool(ManagementContainer.AM_POOL_NAME)) {
            @Override
            public IPartitionProxy getContentProxy(int id) {
              return partitionProxy;
            }
          };
      PartitionManagerTest.preparePartitionManager(pm);
      stage.setPartitionManager(pm);

      FailureRecord failureRecord =
          FailureTrackingHelper.buildFailureRecord(msgCtx, FailureCategory.STORAGE, null, null);
      failureRecord.setStoredOnPartition(false);
      failMgr.insertMessageFailure(failureRecord);
      msgCtx.setInternalFailureId(msgId);
      pipeline.process(
          new Pair<Partition, List<IMessageContext>>(m_part, Collections.singletonList(msgCtx)));
      failureRecord = failMgr.getFailureRecord(msgId);
      assertTrue("Should find stored on partition to be true", failureRecord.isStoredOnPartition());
      Map<String, String> props = msgCtx.readEnvelope();
      assertTrue(
          "envelope should contain failure ID",
          props.containsKey(ParseEnvelopeStage.INTERNAL_MESSAGE_FAILURE_ID));
      assertEquals(
          "message ID in envelope should match permanent ID",
          String.valueOf(msgId),
          props.get(ParseEnvelopeStage.INTERNAL_MESSAGE_FAILURE_ID));

      // confirm that transient ID gets set back to real ID of message
      // remove the existing failure record
      failMgr.removeFailure(msgId);
      // change the ID
      msgCtx.setInternalFailureId(msgId + 1);
      msgCtx.setInternalId(msgId + 1);
      // insert the new failure record
      failureRecord =
          FailureTrackingHelper.buildFailureRecord(msgCtx, FailureCategory.STORAGE, null, null);
      failMgr.insertMessageFailure(failureRecord);
      // old record should be gone
      failureRecord = failMgr.getFailureRecord(msgId);
      assertNull("Should no longer find the failure record with permanent ID", failureRecord);
      // check that the new record can be fetched
      failureRecord = failMgr.getFailureRecord(msgId + 1);
      assertNotNull("Should find transient ID failure record", failureRecord);
      msgCtx.appendToEnvelope(ParseEnvelopeStage.INTERNAL_MESSAGE_FAILURE_ID, msgId + 1);
      props = msgCtx.readEnvelope();
      assertTrue(
          "envelope should contain failure ID",
          props.containsKey(ParseEnvelopeStage.INTERNAL_MESSAGE_FAILURE_ID));
      assertEquals(
          "message ID in envelope should match permanent ID",
          String.valueOf(msgId + 1),
          props.get(ParseEnvelopeStage.INTERNAL_MESSAGE_FAILURE_ID));

      // now assign back the permanent ID and process through the pipeline
      msgCtx.setInternalId(msgId);
      pipeline.process(
          new Pair<Partition, List<IMessageContext>>(m_part, Collections.singletonList(msgCtx)));

      failureRecord = failMgr.getFailureRecord(msgId + 1);
      assertNull("Should not find any record based on transient message ID", failureRecord);
      failureRecord = failMgr.getFailureRecord(msgId);
      assertNotNull("Should find failure record for permanent ID", failureRecord);
      assertTrue("Should find stored on partition to be true", failureRecord.isStoredOnPartition());
      // envelope should now reflect permanent ID
      props = msgCtx.readEnvelope();
      assertTrue(
          "envelope should contain failure ID",
          props.containsKey(ParseEnvelopeStage.INTERNAL_MESSAGE_FAILURE_ID));
      assertEquals(
          "message ID in envelope should match permanent ID",
          String.valueOf(msgId),
          props.get(ParseEnvelopeStage.INTERNAL_MESSAGE_FAILURE_ID));

      // confirm that state does not change on failure
      // force an exception on any call to storeMessages
      pm =
          new PartitionManager(
              ManagementContainer.getInstance().getPool(ManagementContainer.AM_POOL_NAME)) {
            @Override
            public IPartitionProxy getContentProxy(int id) {
              return partitionProxy2;
            }
          };
      PartitionManagerTest.preparePartitionManager(pm);
      stage.setPartitionManager(pm);

      expect(partitionProxy2.storeMessages(msgs))
          .andThrow(new IPartitionProxy.ServiceNotAvailableException(new Exception()))
          .anyTimes();
      replay(partitionProxy2);
      failureRecord.setStoredOnPartition(false);
      failMgr.insertMessageFailure(failureRecord);
      pipeline.process(
          new Pair<Partition, List<IMessageContext>>(m_part, Collections.singletonList(msgCtx)));
      failureRecord = failMgr.getFailureRecord(msgId);
      assertNotNull("Should find the failure record for message", failureRecord);
      assertFalse(
          "Should find stored on partition to be true", failureRecord.isStoredOnPartition());
    } finally {
      importer.stop();
      TestUtils.quietDeleteCustomer(customer);
    }
  }
コード例 #12
0
ファイル: RimInstall.java プロジェクト: piyush76/EMS
  // Override the execute function because there will not be an ACTIVATION ID
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm actionForm,
      HttpServletRequest request,
      HttpServletResponse response)
      throws IOException {

    // If the userName parameter is not present don't bother validating the backend. This is to
    // support older clients that do not pass the userName parameter.
    String userName = request.getParameter(EMS_RIM_PARAM_USER_NAME);
    String userPin = request.getParameter(EMS_RIM_PARAM_USER_PIN);

    if (!StringUtils.isNullOrEmptyIgnoreWS(userName)) {
      IDomainXrefManager dxm = ManagementContainer.getInstance().getDomainXrefManager();
      String backend = request.getParameter(EMS_RIM_PARAM_BACKEND_LOCATION);
      if (StringUtils.isNullOrEmptyIgnoreWS(backend)) {
        backend = IDomainXrefManager.Location.NONE.toString();
      }
      dxm.getUserBackend(userName, DomainXrefManager.getLocationFromString(backend));
      if (StringUtils.isNullOrEmptyIgnoreWS(backend)) {

        LogMessageGen lmg = new LogMessageGen();
        lmg.setSubject("Cannot determine backend for user");
        lmg.param(LoggingConsts.USERNAME, userName);
        lmg.param(LoggingConsts.PIN, userPin);
        m_logCategory.warn(lmg.toString());
        return null;
      }
      if (!isLocalBackend(backend)) {
        // We are on the wrong backend. Redirect.
        // Note that Global URL isn't supported for old agents.
        // Pre-pancit agents don't have requisite logic for handling the
        // redirects.  So, this code is somewhat moot.
        response.setHeader(EMS_RIM_BACKEND_HEADER, backend);
        response.setHeader(EMS_RIM_ERROR_CODE_HEADER, HTTP_STATUS_REDIRECT);
        response.sendError(HttpServletResponse.SC_MOVED_TEMPORARILY, "Redirect to backend");
        return null;
      }
    } // has username

    IDeviceManager deviceManager = ManagementContainer.getInstance().getDeviceManager();

    if (!validatePin(userPin, null)) {
      return null;
    }

    // Preload the user and device to prevent multiple loads later.
    Device device = getDevice(userPin, null);
    if (device == null) {
      return null;
    }

    if (!assertLegacyApiUseAllowed(device)) {
      return null;
    }

    UserAccount user = getUser(null, device);
    if (user == null) {
      return null;
    }

    String currVersion = device.getAgentVersion();
    currVersion = currVersion == null ? "" : currVersion;
    String agentVersion = request.getParameter(EMS_RIM_PARAM_AGENT_VERSIN);

    // If currVersion is empty it means an agent was never installed.
    // EMSDEV-4679
    if (!"".equals(currVersion)
        && (!Device.usesOldRimBackendApi(agentVersion)
            || !Device.usesOldRimBackendApi(currVersion))) {

      // This helps close a security hole.
      // The 'outlook' BB API has stronger authentication.
      // The old service would allow clients to get in w/o a valid
      // auth-token.

      // This service returns the 'activation-id' with no other authentication
      // than a valid pin.  That activation-id may then be used to access
      // GetRimMailAction.
      // We need to prevent this.  This is the only service that sends
      // activation-id's.  The other way id-s are delivered to old agents is via
      // push messages.  We don't send old-style push messages to new agents.

      LogMessageGen lmg = new LogMessageGen();
      lmg.setSubject("Mixing legacy/current agent APIs not permitted");
      lmg.param(LoggingConsts.PIN, userPin);
      lmg.param(LoggingConsts.USER_ID, device.getUserId());
      lmg.param("attemptedVersion", agentVersion);
      lmg.param("currVersion", currVersion);
      m_logCategory.warn(lmg.toString());
      return null;
    }

    // 'phone' isn't known by agents 6.1 and earlier so just send a blank.
    deviceManager.setAgentVersionForInit(device.getPin(), agentVersion, "");

    // The executeAction method must set any header to be returned in the response
    return executeAction(mapping, actionForm, request, response, user, device);
  }
コード例 #13
0
ファイル: RimInstall.java プロジェクト: piyush76/EMS
 private boolean isLocalBackend(String backend) {
   IConfiguration cm = ManagementContainer.getInstance().getConfiguration();
   String localBackend = cm.getProperty("default.backend.hostname");
   return EqualityUtils.nullsOrEqual(localBackend, backend);
 }
コード例 #14
0
ファイル: RimInstall.java プロジェクト: piyush76/EMS
  // Use this to set headers that are required on all responses.
  protected void setResponseHeaders(
      ActionForm actionForm, HttpServletResponse response, UserAccount user, Device device)
      throws IOException {

    // The url is static across all devices in a customer.
    ICustomerManager customerManager = ManagementContainer.getInstance().getCustomerManager();
    Customer cust = customerManager.getCustomer(user.getCustomerID());
    IRimManager rimManager = ManagementContainer.getInstance().getRimManager();
    String cappUrl = cust.getCappUrl();
    if (m_devDebug) { // Our dev boxes use http and specifcy a port, this conflicts with the https
      // assumption of getCappUrl()
      cappUrl = "http://turbodog.austin.messageone.com:8080/";
    }

    URL url = null;
    try {
      url = new URL(cappUrl);
    } catch (MalformedURLException e) {

      LogMessageGen lmg = new LogMessageGen();
      lmg.setSubject("Bad URL");
      lmg.param(LoggingConsts.URL, cappUrl);
      lmg.param(LoggingConsts.USER_ID, device.getUserId());
      lmg.param(LoggingConsts.CUSTOMER_ID, device.getCustomerId());
      lmg.param(LoggingConsts.PIN, device.getPin());

      // This would come from the customer config, so it's bad.
      m_logCategory.error(lmg.toString(), e);
      response.setHeader(SUCCESS, "false");
      return;
    }
    int deviceCheckin =
        cust.getCapabilities().getIntCapability(Capabilities.CAP_RIM_DEVICE_PERIODIC_CHECKIN, 30);

    response.setHeader("rim-access-url-protocol", url.getProtocol());
    response.setHeader("rim-access-url-hostname", url.getHost());
    if (url.getPort() > 0) {
      response.setHeader("rim-access-url-port", Integer.toString(url.getPort()));
    }

    response.setHeader(EMS_RIM_DISPLAY_NAME, device.getDisplayName());
    response.setHeader("get-mail-path", "wfe/getRimMail.do");
    response.setHeader("send-mail-path", "wfe/sendRimMail.do");
    response.setHeader("get-display-name-path", "wfe/rimGetDisplayName.do");
    response.setHeader("checkin-path", "wfe/rimCheckin.do");

    response.setHeader("periodic-checkin", Integer.toString(deviceCheckin));

    CustomerState state = user.getUserState();
    String stateString = "ready";
    if (CustomerState.ACTIVE.equals(state) || CustomerState.TEST.equals(state)) {
      stateString = "active";

      String activationId = rimManager.getActivationId(device.getPin());
      if (StringUtils.isEmptyOrNull(activationId)) {
        // EMSDEV-4722
        // If an old agent is installed during activation, the dat_rim_user_connection_status
        // won't exist and thus no activation ID.  If needed, create one on the fly.
        // Incidently, this will fix most of the problems we've had with activationId's
        // disappearing for various reasons.
        LogMessageGen.log(
                "Old agent activationId not found; will create one on the fly", m_logCategory)
            .param(LoggingConsts.PIN, device.getPin())
            .param(LoggingConsts.USER_ID, device.getUserId())
            .info();

        activationId = rimManager.activateOldAgent(device.getPin(), device.getCustomerId());

        // Try again.
        if (StringUtils.isEmptyOrNull(activationId)) {

          LogMessageGen.log("Unable to create activationId for old agent", m_logCategory)
              .param(LoggingConsts.PIN, device.getPin())
              .param(LoggingConsts.USER_ID, device.getUserId())
              .error();
        }
      } // no activationId

      response.setHeader("activation-id", activationId);
    } // active.
    response.setHeader("application-state", stateString);

    response.setHeader(SUCCESS, "true");
  }
コード例 #15
0
ファイル: TopologyHandler.java プロジェクト: piyush76/EMS
  private static void deleteTopologyData(
      Connection c, int sourceID, Collection groupIDs, Collection serverIDs, Collection storeIDs)
      throws SQLException {
    PreparedStatement ps = null;
    int purgeInterval =
        ManagementContainer.getInstance()
            .getConfiguration()
            .getIntProperty(PURGE_DAY_INTERVAL_PROP, DEFAULT_PURGE_DAY_INTERVAL);
    List<Integer> deletedStores = null;
    List<Integer> deletedServers = null;
    List<Integer> deletedSites = null;

    try {
      // First determine what stores to delete
      String strQuery =
          "select store_id from dat_customer_stores where exists ( "
              + "  select * from dat_customer_servers svr "
              + "    where svr.server_id = dat_customer_stores.server_id and "
              + "      exists ( "
              + "        select * from dat_customer_sites s "
              + "        where s.site_id = svr.admin_group_id and source_id = ? "
              + "      ) "
              + "  ) and "
              + "  store_id not in "
              + QueryUtils.literal(storeIDs)
              + " and is_deleted = false";
      ps = c.prepareStatement(strQuery);

      ps.setInt(1, sourceID);
      ResultSet rs = ps.executeQuery();
      // Convert the result set to a list of store id's to be deleted
      while (rs.next()) {
        if (deletedStores == null) deletedStores = new ArrayList<Integer>();

        deletedStores.add(rs.getInt(1));
      }

      ps.close();

      if (deletedStores != null) // Check to see if we have anything to delete
      {
        strQuery =
            "update dat_customer_stores set is_deleted = true, purge_time = current_timestamp + '"
                + purgeInterval
                + " days'::interval"
                + "    where store_id in "
                + QueryUtils.literal(deletedStores);
        ps = c.prepareStatement(strQuery);
        ps.executeUpdate();
        ps.close();

        // Log what we marked for deletion
        logPoliciesUsingRemovedTopologyObjs(
            "Marking as deleted", "store", deletedStores, IUserManager.PROP_STORE_ID, c);
      }

      ps = null;

      // delete the servers
      // First determine what servers to delete
      strQuery =
          "select server_id from dat_customer_servers "
              + "where "
              + "  exists ( "
              + "    select * from dat_customer_sites s "
              + "    where s.site_id = dat_customer_servers.admin_group_id and source_id = ? "
              + "  ) and "
              + "  server_id not in "
              + QueryUtils.literal(serverIDs)
              + " and is_deleted = false";
      ps = c.prepareStatement(strQuery);

      ps.setInt(1, sourceID);
      rs = ps.executeQuery();
      // Convert the result set to a list of server id's to be deleted
      while (rs.next()) {
        if (deletedServers == null) deletedServers = new ArrayList<Integer>();

        deletedServers.add(rs.getInt(1));
      }

      ps.close();

      if (deletedServers != null) // Check to see if we have anything to delete
      {
        strQuery =
            "update dat_customer_servers set is_deleted = true, purge_time = current_timestamp + '"
                + purgeInterval
                + " days'::interval"
                + "    where server_id in "
                + QueryUtils.literal(deletedServers);
        ps = c.prepareStatement(strQuery);
        ps.executeUpdate();
        ps.close();

        // Log what we marked for deletion
        logPoliciesUsingRemovedTopologyObjs(
            "Marking as deleted", "server", deletedServers, IUserManager.PROP_SERVER_ID, c);
      }

      ps = null;

      // delete the sites
      // First determine what sites to delete
      strQuery =
          "select site_id from dat_customer_sites "
              + "where "
              + "  source_id = ? and is_deleted = false and "
              + "  site_id not in "
              + QueryUtils.literal(groupIDs);
      ps = c.prepareStatement(strQuery);

      ps.setInt(1, sourceID);
      rs = ps.executeQuery();
      // Convert the result set to a list of site id's to be deleted
      while (rs.next()) {
        if (deletedSites == null) deletedSites = new ArrayList<Integer>();

        deletedSites.add(rs.getInt(1));
      }

      ps.close();

      if (deletedSites != null) // Check to see if we have anything to delete
      {
        strQuery =
            "update dat_customer_sites set is_deleted = true, purge_time = current_timestamp + '"
                + purgeInterval
                + " days'::interval"
                + "    where site_id in "
                + QueryUtils.literal(deletedSites);
        ps = c.prepareStatement(strQuery);
        ps.executeUpdate();
        ps.close();

        // Log what we marked for deletion
        logPoliciesUsingRemovedTopologyObjs(
            "Marking as deleted", "site", deletedSites, IUserManager.PROP_ROUTING_GROUP_ID, c);
      }

      ps = null;
    } finally {
      if (ps != null) {
        ps.close();
      }
    }
  }