/**
   * This test will tell the launch to set some arguments for the program. We will then check that
   * the program has the same arguments.
   */
  @Test
  public void testSettingArguments() throws Throwable {
    setLaunchAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS, "1 2 3\n4 5 6");
    doLaunch();

    MIStoppedEvent stoppedEvent = getInitialStoppedEvent();

    // Check that argc is correct
    final IExpressionDMContext argcDmc =
        SyncUtil.createExpression(stoppedEvent.getDMContext(), "argc");
    Query<FormattedValueDMData> query =
        new Query<FormattedValueDMData>() {
          @Override
          protected void execute(DataRequestMonitor<FormattedValueDMData> rm) {
            fExpService.getFormattedExpressionValue(
                fExpService.getFormattedValueContext(argcDmc, MIExpressions.DETAILS_FORMAT), rm);
          }
        };
    try {
      fExpService.getExecutor().execute(query);
      FormattedValueDMData value = query.get(500, TimeUnit.MILLISECONDS);

      // Argc should be 7: the program name and the six arguments
      assertTrue(
          "Expected 7 but got " + value.getFormattedValue(),
          value.getFormattedValue().trim().equals("7"));
    } catch (InterruptedException e) {
      fail(e.getMessage());
    } catch (ExecutionException e) {
      fail(e.getCause().getMessage());
    } catch (TimeoutException e) {
      fail(e.getMessage());
    }

    // Check that argv is also correct.  For simplicity we only check the last argument
    final IExpressionDMContext argvDmc =
        SyncUtil.createExpression(stoppedEvent.getDMContext(), "argv[argc-1]");
    Query<FormattedValueDMData> query2 =
        new Query<FormattedValueDMData>() {
          @Override
          protected void execute(DataRequestMonitor<FormattedValueDMData> rm) {
            fExpService.getFormattedExpressionValue(
                fExpService.getFormattedValueContext(argvDmc, MIExpressions.DETAILS_FORMAT), rm);
          }
        };
    try {
      fExpService.getExecutor().execute(query2);
      FormattedValueDMData value = query2.get(500, TimeUnit.MILLISECONDS);
      assertTrue(
          "Expected \"6\" but got " + value.getFormattedValue(),
          value.getFormattedValue().trim().endsWith("\"6\""));
    } catch (InterruptedException e) {
      fail(e.getMessage());
    } catch (ExecutionException e) {
      fail(e.getCause().getMessage());
    } catch (TimeoutException e) {
      fail(e.getMessage());
    }
  }
Пример #2
0
  public void schedule() throws Exception {
    try {
      final int incompleteTaskNum =
          scheduledRequests.leafTaskNum() + scheduledRequests.nonLeafTaskNum();
      if (incompleteTaskNum == 0) {
        needWakeup.set(true);
        // all task is done or tasks is not scheduled
        synchronized (schedulingThread) {
          schedulingThread.wait(1000);
        }
      } else {
        LinkedList<TaskRequestEvent> taskRequests = createTaskRequest(incompleteTaskNum);

        if (taskRequests.size() == 0) {
          synchronized (schedulingThread) {
            schedulingThread.wait(schedulerDelay);
          }
        } else {
          if (LOG.isDebugEnabled()) {
            LOG.debug("Get " + taskRequests.size() + " taskRequestEvents ");
          }

          if (isLeaf) {
            scheduledRequests.assignToLeafTasks(taskRequests);
          } else {
            scheduledRequests.assignToNonLeafTasks(taskRequests);
          }
        }
      }
    } catch (TimeoutException e) {
      LOG.error(e.getMessage());
    }
  }
  /**
   * This test will tell the launch to clear the environment variables. We will then check that the
   * variable $HOME cannot be found by the program.
   */
  @Test
  public void testClearingEnvironment() throws Throwable {
    setLaunchAttribute(ILaunchManager.ATTR_APPEND_ENVIRONMENT_VARIABLES, false);
    doLaunch();

    SyncUtil.runToLocation("envTest");
    MIStoppedEvent stoppedEvent = SyncUtil.step(2, StepType.STEP_OVER);

    // The program has stored the content of $HOME into a variable called 'home'.
    // Let's verify this variable is 0x0 which means $HOME does not exist.
    final IExpressionDMContext exprDmc =
        SyncUtil.createExpression(stoppedEvent.getDMContext(), "home");
    Query<FormattedValueDMData> query =
        new Query<FormattedValueDMData>() {
          @Override
          protected void execute(DataRequestMonitor<FormattedValueDMData> rm) {
            fExpService.getFormattedExpressionValue(
                fExpService.getFormattedValueContext(exprDmc, MIExpressions.DETAILS_FORMAT), rm);
          }
        };
    try {
      fExpService.getExecutor().execute(query);
      FormattedValueDMData value = query.get(500, TimeUnit.MILLISECONDS);
      assertTrue(
          "Expected 0x0 but got " + value.getFormattedValue(),
          value.getFormattedValue().equals("0x0"));
    } catch (InterruptedException e) {
      fail(e.getMessage());
    } catch (ExecutionException e) {
      fail(e.getCause().getMessage());
    } catch (TimeoutException e) {
      fail(e.getMessage());
    }
  }
  @Parameters("browser")
  @Test
  public void RMO_TC384_PricingSummaryExpandedOverlap_QA_Test(@Optional("FF") String BrowserType)
      throws Exception {

    try {
      this.gc.log.logSetup(this);
      this.gc.log.logInfo("/////Execution Started/////");

      gc.browser.BrowserCloseAllBrowsersBeforeRun();
      gc.browser.BrowserGetBrowserType(BrowserType);
      gc.browser.BrowserGet(Global.BaseUrlRMO_QA);
      gc.browser.BrowserWaitForPageToLoad();

      gc.rmo.RMO_Login(Global.RMOLoginUsername, Global.RMOLoginPassword);
      Thread.sleep(Global.Max_Wait);

      gc.rmo.RMOPricing_ClickProperty_QA(Global.RMO_PropertyName2);
      gc.browser.BrowserWaitForPageToLoad();
      gc.browser.BrowserClick("RMOPropertyPage_PropertiesLink_QA");
      gc.browser.BrowserWaitForPageToLoad();

      gc.rmo.RMOPricing_SelectFutureWeek();

      // UpdateDateStartDate();
      // UpdateDateEndDate();
      gc.rmo.RMOPricing_UpdateDate();
      gc.rmo.RMOPricing_SelectBAR();

      // gc.browser.BrowserClick("RMOAddNewPricing_Override_xp2btn");
      gc.browser.js.executeScript(
          "arguments[0].scrollIntoView(true);",
          gc.browser.driver.findElement(
              By.cssSelector(
                  "form[data-room-master='1BF'] div.data-table__row div.data-table__row-title")));
      gc.browser
          .driver
          .findElement(
              By.cssSelector(
                  "div.room-master-pricing div.summary-edit__data form[data-room-master='1BF'] div.xpu-section div.data-table__submit button.btn.blue-button span.blue-button__icon"))
          .click();

      gc.rmo.RMOPricing_UpdateRoomUpchargeXP2(Global.XP_Upcharge_Positive);
      gc.browser.BrowserClick("RMOAddNewPricing_CreatePricingBtn");
      gc.browser.BrowserWaitForElementPresent("RMOAddNewPricing_ConfimationAlert", 10);
      gc.browser.BrowserVerifyText("You have successfully created a Pricing Strategy for");

    } catch (ParserConfigurationException e) {
      this.gc.log.logException(e.getMessage());
      Assert.assertTrue(false, "Exception occured.... Failing the script...!!");
    } catch (IOException e) {
      this.gc.log.logException(e.getMessage());
      Assert.assertTrue(false, "Exception occured.... Failing the script...!!");
    } catch (TimeoutException e) {
      this.gc.log.logException(e.getMessage());
      Assert.assertTrue(false, "Exception occured.... Failing the script...!!");
    } finally {
      gc.generic.Env_Teardown();
    }
  }
  /**
   * This test will tell the launch to set the working directory to data/launch/bin/ and will verify
   * that we can find the file LaunchConfigurationAndRestartTestApp.cpp. This will confirm that GDB
   * has been properly configured with the working dir.
   */
  @Test
  public void testSettingWorkingDirectory() throws Throwable {
    IPath path = new Path(fFullProgramPath);
    String dir = path.removeLastSegments(4).toPortableString() + "/" + EXEC_PATH;
    setLaunchAttribute(ICDTLaunchConfigurationConstants.ATTR_WORKING_DIRECTORY, dir);
    setLaunchAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, dir + EXEC_NAME);

    doLaunch();

    Query<MIInfo> query =
        new Query<MIInfo>() {
          @Override
          protected void execute(DataRequestMonitor<MIInfo> rm) {
            fGdbControl.queueCommand(
                fGdbControl
                    .getCommandFactory()
                    .createMIFileExecFile(fGdbControl.getContext(), EXEC_NAME),
                rm);
          }
        };
    try {
      fExpService.getExecutor().execute(query);
      query.get(500, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
      fail(e.getMessage());
    } catch (ExecutionException e) {
      fail(e.getCause().getMessage());
    } catch (TimeoutException e) {
      fail(e.getMessage());
    }
  }
  @Parameters("browser")
  @Test
  public void ReviewPastWeek_Upcharges(@Optional("FF") String BrowserType) {
    try {
      this.gc.log.logSetup(this);
      this.gc.log.logInfo("/////Execution Started/////");
      gc.browser.BrowserCloseAllBrowser();

      gc.browser.BrowserGetBrowserType(BrowserType);
      gc.browser.BrowserGet(Global.BaseUrlRMO);
      Thread.sleep(5000);

      gc.rmo.RMO_Login(Global.RMOLoginUsername, Global.RMOLoginPassword);
      Thread.sleep(5000);

      gc.rmo.RMOPricing_ClickProperty(Global.RMO_PropertyName1);
      gc.browser.BrowserWaitForPageToLoad();

      /* To Verify Number of days displayed in Calendar */
      int DayCount = gc.generic.findElements("RMOPropertyPricing_WeekDays").size();
      Assert.assertTrue(DayCount == 35, "The calendar have a default view of 35 days");
      gc.browser.BrowserWaitForPageToLoad();

      /* To select the past week */
      gc.rmo.RMOPricing_SelectPastWeek();

      Assert.assertTrue(
          IsWebElementReadOnly("RMOPropertyPricing_Calendar_PastWeek_StartDate"),
          "The WebElement is read only & cannot be edited.");

      /* To verify that each day in past week have BAR Value*/
      Assert.assertTrue(
          GetPastRoomUpchargeValues(),
          "Valid Upcharge values for all room type masters along with their child rooms displayed for each day");

      Assert.assertTrue(
          GetPastPersonUpchargeValues(),
          " Valid Upcharge values for all room type masters along with their child rooms displayed for each day");

      gc.browser.BrowserCloseAllBrowser();

    } catch (ParserConfigurationException e) {
      this.gc.log.logException(e.getMessage());
      Assert.assertTrue(false, "Exception occured.... FAiling the script...!!");
    } catch (SAXException e) {
      this.gc.log.logException(e.getMessage());
      Assert.assertTrue(false, "Exception occured.... FAiling the script...!!");
    } catch (IOException e) {
      this.gc.log.logException(e.getMessage());
      Assert.assertTrue(false, "Exception occured.... FAiling the script...!!");
    } catch (TimeoutException e) {
      this.gc.log.logException(e.getMessage());
      Assert.assertTrue(false, "Exception occured.... FAiling the script...!!");
    } catch (Exception e) {
      this.gc.log.logException(e.getMessage());
      Assert.assertTrue(false, "Exception occured.... Failing the script...!!");
    }
  }
 public boolean afterInsert(final Object key, final Object value, final Object version)
     throws CacheException {
   try {
     return put(key, value, version, null);
   } catch (TimeoutException e) {
     LOG.log(Level.FINEST, e.getMessage());
   }
   return false;
 }
  @Parameters("browser")
  @Test
  public void RMO_AddNewPricing_DefaultPerPersonUpcharge_QA_Test(@Optional("FF") String BrowserType)
      throws Exception {

    try {
      this.gc.log.logSetup(this);
      this.gc.log.logInfo("/////Execution Started/////");
      gc.browser.BrowserCloseAllBrowser();

      gc.browser.BrowserGetBrowserType(BrowserType);
      gc.browser.BrowserGet(Global.BaseUrlRMO_QA);
      gc.browser.BrowserWaitForPageToLoad();

      gc.rmo.RMO_Login(Global.RMOLoginUsername, Global.RMOLoginPassword);
      Thread.sleep(10000);

      gc.rmo.RMOPricing_ClickProperty_QA(Global.RMO_PropertyName2);
      gc.browser.BrowserWaitForPageToLoad();
      gc.browser.BrowserClick("RMOPropertyPage_PropertiesLink_QA");
      gc.browser.BrowserWaitForPageToLoad();

      gc.browser.BrowserClick("RMOPropertyPage_AddNewPricingButton");
      gc.browser.BrowserWaitForPageToLoad();
      gc.rmo.RMOPricing_SelectDate();
      gc.rmo.RMOPricing_SelectBAR();
      gc.browser.BrowserClick("RMOAddNewPricing_Override_xp2btn");
      gc.rmo.RMOPricing_UpdatePersonUpchargeXP2(Global.XP_Upcharge_Positive);
      gc.browser.BrowserClick("RMOAddNewPricing_Override_RUbtn");
      gc.rmo.RMOPricing_UpdateRoomUpchargeXP2(Global.XP_Upcharge_Positive);
      gc.browser.BrowserClick("RMOAddNewPricing_CreatePricingBtn");
      gc.browser.BrowserWaitForElementPresent(
          "RMOPropertyPricing_PricingConfirmationMessage_QA", 5);
      Thread.sleep(10000);
      Assert.assertTrue(
          gc.browser.BrowserGetTextFromElement("RMOPropertyPricing_PricingConfirmationMessage_QA")
              .contains("You have successfully created a Pricing Strategy"),
          "Confirmation Message dilog is dispalyed");
      /*gc.browser.BrowserVerifyText("You have successfully created a Pricing Strategy for");*/
      gc.browser.BrowserClick("RMOAddNewPricing_Alert_DoneBtn");

      gc.browser.BrowserCloseAllBrowser();

    } catch (ParserConfigurationException e) {
      this.gc.log.logException(e.getMessage());
      Assert.assertTrue(false, "Exception occured.... Failing the script...!!");
    } catch (IOException e) {
      this.gc.log.logException(e.getMessage());
      Assert.assertTrue(false, "Exception occured.... Failing the script...!!");
    } catch (TimeoutException e) {
      this.gc.log.logException(e.getMessage());
      Assert.assertTrue(false, "Exception occured.... Failing the script...!!");
    } finally {
      gc.generic.Env_Teardown();
    }
  }
Пример #9
0
 @Test
 public void testCheckConnection() {
   try {
     assertTrue(PlintRobot.getInstance().checkConnection());
   } catch (LintException e) {
     assertFalse(e.getMessage(), true);
   } catch (TimeoutException e) {
     assertFalse(e.getMessage(), true);
   }
 }
Пример #10
0
  public static void main(String[] args) {
    Casher casher = new Casher();

    System.out.println("Ordering pizzas at a casher counter.");
    Pizza p1 = casher.order();
    Pizza p2 = casher.order();
    Pizza p3 = casher.order();

    System.out.println(
        "Doing something, reading newspapers, magazines, etc., "
            + "until pizzas are ready to pick up...");
    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
    }

    System.out.println("Let's see if pizzas are ready to pick up...");
    if (p1.isReady())
      try {
        System.out.println(p1.getPizza());
      } catch (TimeoutException e) {
        System.out.println(e.getMessage());
        ;
      }
    if (p2.isReady())
      try {
        System.out.println(p2.getPizza());
      } catch (TimeoutException e) {
        System.out.println(e.getMessage());
        ;
      }
    if (p3.isReady())
      try {
        System.out.println(p3.getPizza());
      } catch (TimeoutException e) {
        System.out.println(e.getMessage());
        ;
      }
  }
Пример #11
0
 public boolean putFromLoad(
     final Object key,
     final Object value,
     final long txTimestamp,
     final Object version,
     final boolean minimalPutOverride)
     throws CacheException {
   try {
     return put(key, value, version, null);
   } catch (TimeoutException e) {
     LOG.log(Level.FINEST, e.getMessage());
   }
   return false;
 }
 public V txGet(long timeout, TimeUnit unit) throws ElasticSearchException {
   try {
     return get(timeout, unit);
   } catch (TimeoutException e) {
     throw new ElasticSearchTimeoutException(e.getMessage());
   } catch (InterruptedException e) {
     throw new ElasticSearchInterruptedException(e.getMessage());
   } catch (ExecutionException e) {
     if (e.getCause() instanceof ElasticSearchException) {
       throw (ElasticSearchException) e.getCause();
     } else {
       throw new TransportException("Failed execution", e);
     }
   }
 }
  @Parameters("browser")
  @Test
  public void RMO_TC384_PricingSummaryExpandedOverlap_QA_Test(@Optional("FF") String BrowserType)
      throws Exception {

    try {
      this.gc.log.logSetup(this);
      this.gc.log.logInfo("/////Execution Started/////");

      gc.browser.BrowserCloseAllBrowsersBeforeRun();
      gc.browser.BrowserGetBrowserType(BrowserType);
      gc.browser.BrowserGet(Global.BaseUrlRMO_QA);
      gc.browser.BrowserWaitForPageToLoad();

      gc.rmo.RMO_Login(Global.RMOLoginUsername, Global.RMOLoginPassword);
      Thread.sleep(10000);

      gc.rmo.RMOPricing_ClickProperty_QA(Global.RMO_PropertyName2);
      gc.browser.BrowserWaitForPageToLoad();
      gc.browser.BrowserClick("RMOPropertyPage_PropertiesLink_QA");
      gc.browser.BrowserWaitForPageToLoad();

      gc.rmo.RMOPricing_SelectFutureWeek();

      // UpdateDateStartDate();
      // UpdateDateEndDate();
      gc.rmo.RMOPricing_UpdateDate();
      gc.rmo.RMOPricing_SelectBAR();

      gc.browser.BrowserClick("RMOAddNewPricing_Override_xp2btn");
      gc.rmo.RMOPricing_UpdateRoomUpchargeXP2(Global.XP_Upcharge_Positive);
      gc.browser.BrowserClick("RMOAddNewPricing_CreatePricingBtn");
      gc.browser.BrowserWaitForElementPresent("RMOAddNewPricing_ConfimationAlert", 5);
      gc.browser.BrowserVerifyText("You have successfully created a Pricing Strategy for");

    } catch (ParserConfigurationException e) {
      this.gc.log.logException(e.getMessage());
      Assert.assertTrue(false, "Exception occured.... Failing the script...!!");
    } catch (IOException e) {
      this.gc.log.logException(e.getMessage());
      Assert.assertTrue(false, "Exception occured.... Failing the script...!!");
    } catch (TimeoutException e) {
      this.gc.log.logException(e.getMessage());
      Assert.assertTrue(false, "Exception occured.... Failing the script...!!");
    } finally {
      gc.generic.Env_Teardown();
    }
  }
 private void stopManagementMachines() {
   try {
     provisioning.stopManagementMachines();
   } catch (final CloudProvisioningException e) {
     // log a warning, don't throw an exception on this failure
     logger.warning(
         "Failed to clean management machines after provisioning failure, reported error: "
             + e.getMessage());
   } catch (final TimeoutException e) {
     // log a warning, don't throw an exception on this failure
     logger.warning(
         "Failed to clean management machines after provisioning failure, the operation timed out ("
             + e.getMessage()
             + ")");
   }
 }
Пример #15
0
 /**
  * {@inheritDoc}
  *
  * <p>Called after <code>com.hazelcast.hibernate.access.ReadWriteAccessDelegate.lockItem()</code>
  */
 public boolean afterUpdate(
     final Object key,
     final Object value,
     final Object currentVersion,
     final Object previousVersion,
     final SoftLock lock)
     throws CacheException {
   try {
     return put(key, value, currentVersion, previousVersion);
   } catch (TimeoutException e) {
     LOG.log(Level.FINEST, e.getMessage());
   } finally {
     unlockItem(key, lock);
   }
   return false;
 }
  @Parameters("browser")
  @Test
  public void RMO_TC811_WeeklySummary_ModifyPastWeek_Test(@Optional("FF") String BrowserType) {
    try {
      this.gc.log.logSetup(this);
      this.gc.log.logInfo("//////Execution Statrted///////");
      gc.browser.BrowserCloseAllBrowser();
      gc.browser.BrowserGetBrowserType(BrowserType);
      gc.browser.BrowserGet(Global.BaseUrlRMO);
      Thread.sleep(Global.Mid_Wait);

      gc.rmo.RMO_Login(Global.RMOLoginUsername, Global.RMOLoginPassword);
      Thread.sleep(Global.Mid_Wait);

      gc.rmo.RMOPricing_ClickProperty(Global.RMO_PropertyName1);
      gc.browser.BrowserWaitForPageToLoad();

      /* To Verify Number of days displayed in Calendar */
      int DayCount = gc.generic.findElements("RMOPropertyPricing_WeekDays").size();
      Assert.assertTrue(DayCount == 35, "The calendar should have a default view of 35 days");
      gc.browser.BrowserWaitForPageToLoad();

      gc.rmo.RMOPricing_SelectPastWeek();

      Assert.assertTrue(
          IsWebElementReadOnly("RMOPropertyPricing_Calendar_PastWeek_StartDate"),
          "The WebElement is read only & cannot be edited.");

    } catch (ParserConfigurationException e) {
      this.gc.log.logException(e.getMessage());
      Assert.assertTrue(false, "Exception occured.... FAiling the script...!!");
    } catch (SAXException e) {
      this.gc.log.logException(e.getMessage());
      Assert.assertTrue(false, "Exception occured.... FAiling the script...!!");
    } catch (IOException e) {
      this.gc.log.logException(e.getMessage());
      Assert.assertTrue(false, "Exception occured.... FAiling the script...!!");
    } catch (TimeoutException e) {
      this.gc.log.logException(e.getMessage());
      Assert.assertTrue(false, "Exception occured.... FAiling the script...!!");
    } catch (Exception e) {
      this.gc.log.logException(e.getMessage());
      Assert.assertTrue(false, "Exception occured.... Failing the script...!!");
    } finally {
      gc.generic.Env_Teardown();
    }
  }
 /**
  * Starts the {@link LiveReloadServer} which is responsable for the embedded web/websocket/proxy
  * server configuration and lifecycle
  *
  * @param serverBehaviour
  * @throws CoreException
  * @throws TimeoutException
  * @throws InterruptedException
  */
 public void startServer() throws CoreException {
   try {
     // set the server status to "Starting"
     setServerStarting();
     // now, let's init and start the embedded jetty server from the
     // server attributes
     final IServer server = getServer();
     // retrieve the websocket port, use the default value if it was missing
     websocketPort =
         server.getAttribute(
             LiveReloadLaunchConfiguration.WEBSOCKET_PORT,
             LiveReloadLaunchConfiguration.DEFAULT_WEBSOCKET_PORT);
     // fix the new default behaviour: proxy is now always enabled
     if (!isProxyEnabled()) {
       setProxyEnabled(true);
     }
     final boolean allowRemoteConnections = isRemoteConnectionsAllowed();
     final boolean enableScriptInjection = isScriptInjectionEnabled();
     this.liveReloadServer =
         new LiveReloadServer(
             server.getName(),
             server.getHost(),
             websocketPort,
             true,
             allowRemoteConnections,
             enableScriptInjection);
     this.liveReloadServerRunnable = JettyServerRunner.start(liveReloadServer);
     if (!this.liveReloadServerRunnable.isSuccessfullyStarted()) {
       setServerStopped();
     } else {
       // listen to file changes in the workspace
       addWorkspaceResourceChangeListener();
       // listen to server lifecycles
       addServerLifeCycleListener();
       // set the server status to "Started"
       setServerStarted();
     }
   } catch (TimeoutException e) {
     setServerStopped();
     throw new CoreException(
         new Status(IStatus.ERROR, JBossLiveReloadCoreActivator.PLUGIN_ID, e.getMessage(), e));
   }
 }
Пример #18
0
  /**
   * Obtain the UUID of some relatively underutilized data service.
   *
   * <p>FIXME The LBS should interpret the excludedServiceUUID as the source service UUID and then
   * provide a list of those services having an LBS computed service score which is significantly
   * lower than the score for this service. Changing this will break some unit tests (for the LBS
   * behavior).
   */
  private UUID getMoveTarget(
      final UUID sourceServiceUUID, final ILoadBalancerService loadBalancerService) {

    try {

      // request under utilized data service UUIDs (RMI).
      final UUID[] uuids =
          loadBalancerService.getUnderUtilizedDataServices( //
              0, // minCount - no lower bound.
              1, // maxCount - no upper bound.
              sourceServiceUUID // exclude this data service.
              );

      if (uuids != null && uuids.length > 0) {

        // Found a move target.
        return uuids[0];
      }

      // No move target.
      return null;

    } catch (TimeoutException t) {

      log.warn(t.getMessage());

      return null;

    } catch (InterruptedException t) {

      log.warn(t.getMessage());

      return null;

    } catch (Throwable t) {

      log.error("Could not obtain target service UUIDs: ", t);

      return null;
    }
  }
Пример #19
0
 /* keep grabbing commands, acquiring locks, until everything is executed */
 public void run() {
   try {
     while (true) {
       while (mSleep) Thread.sleep(200);
       String next = grabCommand();
       if (next != null) {
         processCommand(next);
         Thread.sleep(50);
       } else Thread.sleep(200);
     }
   } catch (InterruptedException e) {
     Logger.warning("interrupted");
   } catch (TimeoutException e) {
     Logger.error("Session timed out: " + e.getMessage());
   } catch (RPCClient.MSFException e) {
     System.errorLogging(e);
   } catch (IOException e) {
     System.errorLogging(e);
   } finally {
     stopSession();
   }
 }
    @Test
    public void testWaitForState() throws Throwable {
      ExampleService exampleService = new ExampleService();
      final ExampleService.ExampleServiceState exampleServiceState =
          new ExampleService.ExampleServiceState();
      exampleServiceState.name = UUID.randomUUID().toString();

      Operation post = host.startServiceSynchronously(exampleService, exampleServiceState);
      assertThat(post.getStatusCode(), is(200));

      try {
        host.waitForState(
            ExampleService.ExampleServiceState.class,
            new Predicate<ExampleService.ExampleServiceState>() {
              @Override
              public boolean test(ExampleService.ExampleServiceState state) {
                return false;
              }
            });

        Assert.fail("this state transition should not have succeeded");
      } catch (TimeoutException e) {
        assertThat(
            e.getMessage(), is(equalToIgnoringCase("timeout waiting for state transition.")));
      }

      try {
        host.waitForState(
            ExampleService.ExampleServiceState.class,
            new Predicate<ExampleService.ExampleServiceState>() {
              @Override
              public boolean test(ExampleService.ExampleServiceState state) {
                return state.name.equals(exampleServiceState.name);
              }
            });
      } catch (RuntimeException runtimeException) {
        Assert.fail("failed to detect state transition");
      }
    }
Пример #21
0
 private SubscriberInfo registeMessageType(FetchRequest req) {
   SubscriberInfo info = this.topicSubcriberRegistry.get(req.getTopic());
   if (info == null) {
     log.warn("query topic's[" + req.getTopic() + "] subscriberInfo is null.");
     return null;
   }
   Set<String> messageTypeList = info.getMessageTypes();
   MessageTypeCommand mtCmd =
       new MessageTypeCommand(
           this.consumerConfig.getVersion(),
           this.consumerConfig.getGroup(),
           req.getTopic(),
           OpaqueGenerator.getNextOpaque(),
           messageTypeList,
           MetaMessageSessionFactory.startTime);
   try {
     ResponseCommand response =
         this.remotingClient.invokeToGroup(
             req.getBroker().getZKString(),
             mtCmd,
             this.consumerConfig.getFetchTimeoutInMills(),
             TimeUnit.MILLISECONDS);
     if (response instanceof BooleanCommand) {
       BooleanCommand bc = (BooleanCommand) response;
       if (bc.getCode() == HttpStatus.Success) {
         return info;
       } else {
         return null;
       }
     }
   } catch (InterruptedException e) {
     log.error("registe message type interrupted," + e.getMessage(), e.getCause());
   } catch (TimeoutException e) {
     log.error("registe message type timeout," + e.getMessage(), e.getCause());
   } catch (NotifyRemotingException e) {
     log.error("registe message type failed, " + e.getMessage(), e.getCause());
   }
   return null;
 }
Пример #22
0
  /**
   * returns recent version of given dependency (from internal versions cache)
   *
   * @param partialPath the path of dependency
   * @return recent version
   */
  public static String recentVersion(final String partialPath) {
    if (!VERSIONS_CACHE.containsKey(partialPath)) {
      final FutureTask<String> futureTask = RecentVersionCallable.createFutureTask(partialPath);
      final FutureTask<String> prevFutureTask = VERSIONS_CACHE.putIfAbsent(partialPath, futureTask);

      if (prevFutureTask == null) {
        futureTask.run();
      }
    }

    try {
      return VERSIONS_CACHE.get(partialPath).get(5000, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
      LOG.error("can't collect recent version of {}; {}", partialPath, e.getMessage());
    } catch (ExecutionException e) {
      LOG.error("can't collect recent version of {}; {}", partialPath, e.getMessage());
    } catch (TimeoutException e) {
      LOG.error("can't collect recent version of {}; {}", partialPath, e.getMessage());
    }

    throw new IllegalArgumentException("there is no webjars dependency for: " + partialPath);
  }
Пример #23
0
  public void close(boolean force) {
    try {
      if (LOGGER.isInfoEnabled()) LOGGER.info("Closing the producer");

      if (!force) {
        if (LOGGER.isInfoEnabled()) LOGGER.info("Waiting for the producer");
        productor.get(Conf.getTimeToWait(), TimeUnit.SECONDS);
      }

    } catch (InterruptedException ie) {
      if (LOGGER.isTraceEnabled()) LOGGER.trace(ie.getMessage(), ie);
    } catch (ExecutionException ee) {
      if (LOGGER.isTraceEnabled()) LOGGER.trace(ee.getMessage(), ee);
    } catch (TimeoutException te) {
      if (LOGGER.isTraceEnabled()) LOGGER.trace(te.getMessage(), te);
    } finally {
      // be sure the thread ends
      productor.cancel(true);

      if (handleExecutor) executor.shutdownNow();
    }
    if (LOGGER.isInfoEnabled()) LOGGER.info("Producer is successfully closed");
  }
  /**
   * This test will tell the launch to set some arguments for the program. We will then check that
   * the program has the same arguments. See bug 381804
   */
  @Test
  public void testSettingArgumentsWithSymbols() throws Throwable {
    // Set a argument with double quotes and spaces, which should be considered a single argument
    String argumentToPreserveSpaces = "--c=\"c < s: 'a' t: 'b'>\"";
    String argumentUsedByGDB = "\"--c=c < s: 'a' t: 'b'>\"";

    setLaunchAttribute(
        ICDTLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS, argumentToPreserveSpaces);
    doLaunch();

    MIStoppedEvent stoppedEvent = getInitialStoppedEvent();

    // Check that argc is correct
    final IExpressionDMContext argcDmc =
        SyncUtil.createExpression(stoppedEvent.getDMContext(), "argc");
    Query<FormattedValueDMData> query =
        new Query<FormattedValueDMData>() {
          @Override
          protected void execute(DataRequestMonitor<FormattedValueDMData> rm) {
            fExpService.getFormattedExpressionValue(
                fExpService.getFormattedValueContext(argcDmc, MIExpressions.DETAILS_FORMAT), rm);
          }
        };
    try {
      fExpService.getExecutor().execute(query);
      FormattedValueDMData value = query.get(500, TimeUnit.MILLISECONDS);

      // Argc should be 2: the program name and the one arguments
      assertTrue(
          "Expected 2 but got " + value.getFormattedValue(),
          value.getFormattedValue().trim().equals("2"));
    } catch (InterruptedException e) {
      fail(e.getMessage());
    } catch (ExecutionException e) {
      fail(e.getCause().getMessage());
    } catch (TimeoutException e) {
      fail(e.getMessage());
    }

    // Check that argv is also correct.
    final IExpressionDMContext argvDmc =
        SyncUtil.createExpression(stoppedEvent.getDMContext(), "argv[argc-1]");
    Query<FormattedValueDMData> query2 =
        new Query<FormattedValueDMData>() {
          @Override
          protected void execute(DataRequestMonitor<FormattedValueDMData> rm) {
            fExpService.getFormattedExpressionValue(
                fExpService.getFormattedValueContext(argvDmc, MIExpressions.DETAILS_FORMAT), rm);
          }
        };
    try {
      fExpService.getExecutor().execute(query2);
      FormattedValueDMData value = query2.get(500, TimeUnit.MILLISECONDS);
      assertTrue(
          "Expected \"" + argumentUsedByGDB + "\" but got " + value.getFormattedValue(),
          value.getFormattedValue().trim().endsWith(argumentUsedByGDB));
    } catch (InterruptedException e) {
      fail(e.getMessage());
    } catch (ExecutionException e) {
      fail(e.getCause().getMessage());
    } catch (TimeoutException e) {
      fail(e.getMessage());
    }
  }
 private Channel getChannel(ChannelCachingConnectionProxy connection, boolean transactional) {
   if (this.channelCheckoutTimeout > 0) {
     Semaphore checkoutPermits = this.checkoutPermits.get(connection);
     if (checkoutPermits != null) {
       try {
         if (!checkoutPermits.tryAcquire(this.channelCheckoutTimeout, TimeUnit.MILLISECONDS)) {
           throw new AmqpTimeoutException("No available channels");
         }
       } catch (InterruptedException e) {
         Thread.currentThread().interrupt();
         throw new AmqpTimeoutException("Interrupted while acquiring a channel", e);
       }
     }
   }
   LinkedList<ChannelProxy> channelList;
   if (this.cacheMode == CacheMode.CHANNEL) {
     channelList =
         transactional ? this.cachedChannelsTransactional : this.cachedChannelsNonTransactional;
   } else {
     channelList =
         transactional
             ? this.openConnectionTransactionalChannels.get(connection)
             : this.openConnectionNonTransactionalChannels.get(connection);
   }
   if (channelList == null) {
     channelList = new LinkedList<ChannelProxy>();
     if (transactional) {
       this.openConnectionTransactionalChannels.put(connection, channelList);
     } else {
       this.openConnectionNonTransactionalChannels.put(connection, channelList);
     }
   }
   ChannelProxy channel = null;
   if (connection.isOpen()) {
     synchronized (channelList) {
       while (!channelList.isEmpty()) {
         channel = channelList.removeFirst();
         if (logger.isTraceEnabled()) {
           logger.trace(channel + " retrieved from cache");
         }
         if (channel.isOpen()) {
           break;
         } else {
           try {
             Channel target = channel.getTargetChannel();
             if (target != null) {
               target.close(); // to remove it from auto-recovery if so configured
             }
           } catch (AlreadyClosedException e) {
             if (logger.isTraceEnabled()) {
               logger.trace(channel + " is already closed");
             }
           } catch (IOException e) {
             if (logger.isDebugEnabled()) {
               logger.debug("Unexpected Exception closing channel " + e.getMessage());
             }
           } catch (TimeoutException e) {
             if (logger.isWarnEnabled()) {
               logger.warn("TimeoutException closing channel " + e.getMessage());
             }
           }
           channel = null;
         }
       }
     }
     if (channel != null) {
       if (logger.isTraceEnabled()) {
         logger.trace("Found cached Rabbit Channel: " + channel.toString());
       }
     }
   }
   if (channel == null) {
     channel = getCachedChannelProxy(connection, channelList, transactional);
   }
   return channel;
 }
Пример #26
0
  @Override
  public Result[] call(int timeout) throws IOException {
    // If the active replica callable was closed somewhere, invoke the RPC to
    // really close it. In the case of regular scanners, this applies. We make couple
    // of RPCs to a RegionServer, and when that region is exhausted, we set
    // the closed flag. Then an RPC is required to actually close the scanner.
    if (currentScannerCallable != null && currentScannerCallable.closed) {
      // For closing we target that exact scanner (and not do replica fallback like in
      // the case of normal reads)
      if (LOG.isTraceEnabled()) {
        LOG.trace("Closing scanner id=" + currentScannerCallable.scannerId);
      }
      Result[] r = currentScannerCallable.call(timeout);
      currentScannerCallable = null;
      return r;
    }
    // We need to do the following:
    // 1. When a scan goes out to a certain replica (default or not), we need to
    //   continue to hit that until there is a failure. So store the last successfully invoked
    //   replica
    // 2. We should close the "losing" scanners (scanners other than the ones we hear back
    //   from first)
    //
    RegionLocations rl =
        RpcRetryingCallerWithReadReplicas.getRegionLocations(
            true,
            RegionReplicaUtil.DEFAULT_REPLICA_ID,
            cConnection,
            tableName,
            currentScannerCallable.getRow());

    // allocate a boundedcompletion pool of some multiple of number of replicas.
    // We want to accomodate some RPCs for redundant replica scans (but are still in progress)
    ResultBoundedCompletionService<Pair<Result[], ScannerCallable>> cs =
        new ResultBoundedCompletionService<Pair<Result[], ScannerCallable>>(
            RpcRetryingCallerFactory.instantiate(ScannerCallableWithReplicas.this.conf),
            pool,
            rl.size() * 5);

    AtomicBoolean done = new AtomicBoolean(false);
    replicaSwitched.set(false);
    // submit call for the primary replica.
    addCallsForCurrentReplica(cs, rl);

    try {
      // wait for the timeout to see whether the primary responds back
      Future<Pair<Result[], ScannerCallable>> f =
          cs.poll(timeBeforeReplicas, TimeUnit.MICROSECONDS); // Yes, microseconds
      if (f != null) {
        Pair<Result[], ScannerCallable> r = f.get(timeout, TimeUnit.MILLISECONDS);
        if (r != null && r.getSecond() != null) {
          updateCurrentlyServingReplica(r.getSecond(), r.getFirst(), done, pool);
        }
        return r == null ? null : r.getFirst(); // great we got a response
      }
    } catch (ExecutionException e) {
      RpcRetryingCallerWithReadReplicas.throwEnrichedException(e, retries);
    } catch (CancellationException e) {
      throw new InterruptedIOException(e.getMessage());
    } catch (InterruptedException e) {
      throw new InterruptedIOException(e.getMessage());
    } catch (TimeoutException e) {
      throw new InterruptedIOException(e.getMessage());
    }

    // submit call for the all of the secondaries at once
    // TODO: this may be an overkill for large region replication
    addCallsForOtherReplicas(cs, rl, 0, rl.size() - 1);

    try {
      Future<Pair<Result[], ScannerCallable>> f = cs.poll(timeout, TimeUnit.MILLISECONDS);
      if (f != null) {
        Pair<Result[], ScannerCallable> r = f.get(timeout, TimeUnit.MILLISECONDS);
        if (r != null && r.getSecond() != null) {
          updateCurrentlyServingReplica(r.getSecond(), r.getFirst(), done, pool);
        }
        return r == null ? null : r.getFirst(); // great we got an answer
      }
    } catch (ExecutionException e) {
      RpcRetryingCallerWithReadReplicas.throwEnrichedException(e, retries);
    } catch (CancellationException e) {
      throw new InterruptedIOException(e.getMessage());
    } catch (InterruptedException e) {
      throw new InterruptedIOException(e.getMessage());
    } catch (TimeoutException e) {
      throw new InterruptedIOException(e.getMessage());
    } finally {
      // We get there because we were interrupted or because one or more of the
      // calls succeeded or failed. In all case, we stop all our tasks.
      cs.cancelAll();
    }
    return null; // unreachable
  }
Пример #27
0
  /**
   * Executes an operation and enforces a retrypolicy to handle any potential errors
   *
   * @param <CLIENT_TYPE> The type of the service client
   * @param <PARENT_TYPE> The type of the parent object, i.e. CloudBlobContainer for
   *     downloadAttributes etc.
   * @param <RESULT_TYPE> The type of the expected result
   * @param client the service client associated with the request
   * @param parentObject the parent object
   * @param task the StorageRequest to execute
   * @param policyFactory the factory used to generate a new retry policy instance
   * @param opContext an object used to track the execution of the operation
   * @return the result of the operation
   * @throws StorageException an exception representing any error which occurred during the
   *     operation.
   */
  public static <CLIENT_TYPE, PARENT_TYPE, RESULT_TYPE> RESULT_TYPE executeWithRetry(
      final CLIENT_TYPE client,
      final PARENT_TYPE parentObject,
      final StorageRequest<CLIENT_TYPE, PARENT_TYPE, RESULT_TYPE> task,
      final RetryPolicyFactory policyFactory,
      final OperationContext opContext)
      throws StorageException {

    RetryPolicy policy = null;

    if (policyFactory == null) {
      policy = new RetryNoRetry();
    } else {
      policy = policyFactory.createInstance(opContext);

      // if the returned policy is null, set to not retry
      if (policy == null) {
        policy = new RetryNoRetry();
      }
    }

    int currentRetryCount = 0;
    StorageException translatedException = null;
    HttpURLConnection request = null;
    final long startTime = new Date().getTime();

    while (true) {
      try {
        // 1-4: setup the request
        request = setupStorageRequest(client, parentObject, task, currentRetryCount, opContext);

        Logger.info(
            opContext,
            LogConstants.START_REQUEST,
            request.getURL(),
            request.getRequestProperty(Constants.HeaderConstants.DATE));

        // 5. Potentially upload data
        if (task.getSendStream() != null) {
          Logger.info(opContext, LogConstants.UPLOAD);
          final StreamMd5AndLength descriptor =
              Utility.writeToOutputStream(
                  task.getSendStream(),
                  request.getOutputStream(),
                  task.getLength(),
                  false /* rewindStream */,
                  false /* calculate MD5 */,
                  opContext,
                  task.getRequestOptions());

          task.validateStreamWrite(descriptor);
          Logger.info(opContext, LogConstants.UPLOADDONE);
        }

        // 6. Process the request - Get response
        RequestResult currResult = task.getResult();
        currResult.setStartDate(new Date());

        Logger.info(opContext, LogConstants.GET_RESPONSE);

        currResult.setStatusCode(request.getResponseCode());
        currResult.setStatusMessage(request.getResponseMessage());

        currResult.setStopDate(new Date());
        currResult.setServiceRequestID(BaseResponse.getRequestId(request));
        currResult.setEtag(BaseResponse.getEtag(request));
        currResult.setRequestDate(BaseResponse.getDate(request));
        currResult.setContentMD5(BaseResponse.getContentMD5(request));

        // 7. Fire ResponseReceived Event
        ExecutionEngine.fireResponseReceivedEvent(opContext, request, task.getResult());

        Logger.info(
            opContext,
            LogConstants.RESPONSE_RECEIVED,
            currResult.getStatusCode(),
            currResult.getServiceRequestID(),
            currResult.getContentMD5(),
            currResult.getEtag());

        // 8. Pre-process response to check if there was an exception. Do Response parsing (headers
        // etc).
        Logger.info(opContext, LogConstants.PRE_PROCESS);
        RESULT_TYPE result = task.preProcessResponse(parentObject, client, opContext);
        Logger.info(opContext, LogConstants.PRE_PROCESS_DONE);

        if (!task.isNonExceptionedRetryableFailure()) {

          // 9. Post-process response. Read stream from server.
          Logger.info(opContext, LogConstants.POST_PROCESS);
          result = task.postProcessResponse(request, parentObject, client, opContext, result);
          Logger.info(opContext, LogConstants.POST_PROCESS_DONE);

          // Success return result and drain the input stream.
          if ((task.getResult().getStatusCode() >= 200)
              && (task.getResult().getStatusCode() < 300)) {
            if (request != null) {
              InputStream inStream = request.getInputStream();
              // At this point, we already have a result / exception to return to the user.
              // This is just an optimization to improve socket reuse.
              try {
                Utility.writeToOutputStream(
                    inStream, null, -1, false, false, null, task.getRequestOptions());
              } catch (final IOException ex) {
              } catch (StorageException e) {
              } finally {
                inStream.close();
              }
            }
          }
          Logger.info(opContext, LogConstants.COMPLETE);

          return result;
        } else {
          Logger.warn(opContext, LogConstants.UNEXPECTED_RESULT_OR_EXCEPTION);
          // The task may have already parsed an exception.
          translatedException = task.materializeException(task.getConnection(), opContext);
          task.getResult().setException(translatedException);

          // throw on non retryable status codes: 501, 505, blob type mismatch
          if (task.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_IMPLEMENTED
              || task.getResult().getStatusCode() == HttpURLConnection.HTTP_VERSION
              || translatedException
                  .getErrorCode()
                  .equals(StorageErrorCodeStrings.INVALID_BLOB_TYPE)) {
            throw translatedException;
          }
        }
      } catch (final TimeoutException e) {
        // Retryable
        Logger.warn(
            opContext, LogConstants.RETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());
        translatedException =
            StorageException.translateException(task.getConnection(), e, opContext);
        task.getResult().setException(translatedException);
      } catch (final SocketTimeoutException e) {
        // Retryable
        Logger.warn(
            opContext, LogConstants.RETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());
        translatedException =
            new StorageException(
                StorageErrorCodeStrings.OPERATION_TIMED_OUT,
                "The operation did not complete in the specified time.",
                -1,
                null,
                e);
        task.getResult().setException(translatedException);
      } catch (final IOException e) {
        // Non Retryable if the inner exception is actually an TimeoutException, otherwise Retryable
        if (e.getCause() instanceof TimeoutException) {
          translatedException =
              new StorageException(
                  StorageErrorCodeStrings.OPERATION_TIMED_OUT,
                  SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION,
                  Constants.HeaderConstants.HTTP_UNUSED_306,
                  null,
                  (Exception) e.getCause());
          task.getResult().setException(translatedException);
          Logger.error(
              opContext,
              LogConstants.UNRETRYABLE_EXCEPTION,
              e.getCause().getClass().getName(),
              e.getCause().getMessage());
          throw translatedException;
        } else {
          Logger.warn(
              opContext, LogConstants.RETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());
          translatedException =
              StorageException.translateException(task.getConnection(), e, opContext);
          task.getResult().setException(translatedException);
        }
      } catch (final InvalidKeyException e) {
        // Non Retryable, just throw
        translatedException =
            StorageException.translateException(task.getConnection(), e, opContext);
        task.getResult().setException(translatedException);
        Logger.error(
            opContext, LogConstants.UNRETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());
        throw translatedException;
      } catch (final URISyntaxException e) {
        // Non Retryable, just throw
        translatedException =
            StorageException.translateException(task.getConnection(), e, opContext);
        task.getResult().setException(translatedException);
        Logger.error(
            opContext, LogConstants.UNRETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());
        throw translatedException;
      } catch (final TableServiceException e) {
        task.getResult().setStatusCode(e.getHttpStatusCode());
        task.getResult().setStatusMessage(e.getMessage());
        task.getResult().setException(e);

        if (!e.isRetryable()) {
          Logger.error(
              opContext,
              LogConstants.UNRETRYABLE_EXCEPTION,
              e.getClass().getName(),
              e.getMessage());
          throw e;
        } else {
          Logger.warn(
              opContext, LogConstants.RETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());
          translatedException = e;
        }
      } catch (final StorageException e) {
        // Non Retryable, just throw
        // do not translate StorageException
        task.getResult().setException(e);
        Logger.error(
            opContext, LogConstants.UNRETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());
        throw e;
      } catch (final Exception e) {
        // Non Retryable, just throw
        translatedException =
            StorageException.translateException(task.getConnection(), e, opContext);
        task.getResult().setException(translatedException);
        Logger.error(
            opContext, LogConstants.UNRETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());
        throw translatedException;
      } finally {
        opContext.setClientTimeInMs(new Date().getTime() - startTime);

        // 10. Fire RequestCompleted Event
        if (task.isSent()) {
          ExecutionEngine.fireRequestCompletedEvent(opContext, request, task.getResult());
        }
      }

      // Evaluate Retry Policy
      Logger.info(
          opContext,
          LogConstants.RETRY_CHECK,
          currentRetryCount,
          task.getResult().getStatusCode(),
          translatedException == null ? null : translatedException.getMessage());

      task.setCurrentLocation(getNextLocation(task.getCurrentLocation(), task.getLocationMode()));
      Logger.info(
          opContext, LogConstants.NEXT_LOCATION, task.getCurrentLocation(), task.getLocationMode());

      RetryContext retryContext =
          new RetryContext(
              currentRetryCount++,
              task.getResult(),
              task.getCurrentLocation(),
              task.getLocationMode());

      RetryInfo retryInfo = policy.evaluate(retryContext, opContext);

      if (retryInfo == null) {
        // policy does not allow for retry
        Logger.error(
            opContext,
            LogConstants.DO_NOT_RETRY_POLICY,
            translatedException == null ? null : translatedException.getMessage());
        throw translatedException;
      } else if (Utility.validateMaxExecutionTimeout(
          task.getRequestOptions().getOperationExpiryTimeInMs(), retryInfo.getRetryInterval())) {
        // maximum execution time would be exceeded by current time plus retry interval delay
        TimeoutException timeoutException =
            new TimeoutException(SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION);
        translatedException =
            new StorageException(
                StorageErrorCodeStrings.OPERATION_TIMED_OUT,
                SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION,
                Constants.HeaderConstants.HTTP_UNUSED_306,
                null,
                timeoutException);

        task.initialize(opContext);
        task.getResult().setException(translatedException);

        Logger.error(
            opContext,
            LogConstants.DO_NOT_RETRY_TIMEOUT,
            translatedException == null ? null : translatedException.getMessage());

        throw translatedException;
      } else {
        // attempt to retry
        task.setCurrentLocation(retryInfo.getTargetLocation());
        task.setLocationMode(retryInfo.getUpdatedLocationMode());
        Logger.info(
            opContext, LogConstants.RETRY_INFO, task.getCurrentLocation(), task.getLocationMode());

        try {
          ExecutionEngine.fireRetryingEvent(
              opContext, task.getConnection(), task.getResult(), retryContext);

          Logger.info(opContext, LogConstants.RETRY_DELAY, retryInfo.getRetryInterval());
          Thread.sleep(retryInfo.getRetryInterval());
        } catch (final InterruptedException e) {
          // Restore the interrupted status
          Thread.currentThread().interrupt();
        }
      }
    }
  }
  /**
   * This test will tell the launch to set a new environment variable LAUNCHTEST. We will then check
   * that this new variable can be read by the program.
   */
  @Test
  public void testSettingEnvironment() throws Throwable {
    setLaunchAttribute(ILaunchManager.ATTR_APPEND_ENVIRONMENT_VARIABLES, true);

    Map<String, String> map = new HashMap<String, String>(1);
    map.put("LAUNCHTEST", "IS SET");
    setLaunchAttribute(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES, map);
    doLaunch();

    SyncUtil.runToLocation("envTest");
    MIStoppedEvent stoppedEvent = SyncUtil.step(2, StepType.STEP_OVER);

    // The program has stored the content of $LAUNCHTEST into a variable called 'launchTest'.
    // Let's verify this variable is set to "IS SET".
    final IExpressionDMContext exprDmc =
        SyncUtil.createExpression(stoppedEvent.getDMContext(), "launchTest");
    Query<FormattedValueDMData> query =
        new Query<FormattedValueDMData>() {
          @Override
          protected void execute(DataRequestMonitor<FormattedValueDMData> rm) {
            fExpService.getFormattedExpressionValue(
                fExpService.getFormattedValueContext(exprDmc, MIExpressions.DETAILS_FORMAT), rm);
          }
        };
    try {
      fExpService.getExecutor().execute(query);
      FormattedValueDMData value = query.get(500, TimeUnit.MILLISECONDS);
      assertTrue(
          "Expected a string ending with \"IS SET\" but got " + value.getFormattedValue(),
          value.getFormattedValue().trim().endsWith("\"IS SET\""));
    } catch (InterruptedException e) {
      fail(e.getMessage());
    } catch (ExecutionException e) {
      fail(e.getCause().getMessage());
    } catch (TimeoutException e) {
      fail(e.getMessage());
    }

    // Check that the normal environment is there by checking that $HOME (which is stored in 'home"
    // exists.
    final IExpressionDMContext exprDmc2 =
        SyncUtil.createExpression(stoppedEvent.getDMContext(), "home");
    Query<FormattedValueDMData> query2 =
        new Query<FormattedValueDMData>() {
          @Override
          protected void execute(DataRequestMonitor<FormattedValueDMData> rm) {
            fExpService.getFormattedExpressionValue(
                fExpService.getFormattedValueContext(exprDmc2, MIExpressions.DETAILS_FORMAT), rm);
          }
        };
    try {
      fExpService.getExecutor().execute(query2);
      FormattedValueDMData value = query2.get(500, TimeUnit.MILLISECONDS);
      assertFalse("Expected something else than 0x0", value.getFormattedValue().equals("0x0"));
    } catch (InterruptedException e) {
      fail(e.getMessage());
    } catch (ExecutionException e) {
      fail(e.getCause().getMessage());
    } catch (TimeoutException e) {
      fail(e.getMessage());
    }
  }
Пример #29
0
  @SuppressWarnings({"unchecked", "boxing", "rawtypes"})
  private DiscoveryManager getRemoteProxyToDiscoveryManager(final String ip, final int port) {

    final String address = ip + ":" + port;
    final int timeout = 500; // 500 ms RemoteAPIImpl if need detailed version...

    this.logger.status("remoteproxytodiscovery/start", "ip", ip, "port", port);

    final DiscoveryManager newClient =
        Proxies.newClient(
            EXPORT_NAME, address, getClass().getClassLoader(), DiscoveryManager.class);

    // Execute collection asynchronously (TODO: cache pool usage could be improved)
    final ExecutorService cachePool =
        Executors.newCachedThreadPool(RemoteDiscoveryImpl.threadFactory);
    final ExecutorCompletionService<String> ecs = new ExecutorCompletionService(cachePool);
    final Future<String> future =
        ecs.submit(
            new Callable<String>() {

              public String call() throws Exception {
                return AccessController.doPrivileged(
                    new PrivilegedAction<String>() {
                      public String run() {
                        return newClient.ping(667) == 667 ? "OK" : null;
                      }
                    });
              }
            });

    // Wait at most half a second (TODO: Make this configurable)
    try {
      final String string = future.get(timeout, TimeUnit.MILLISECONDS);
      if (string == null) return null;

      return newClient;
    } catch (final InterruptedException e) {
      this.logger.status("remoteproxytodiscovery/exception/interrupted", "message", e.getMessage());
      e.printStackTrace();
    } catch (final ExecutionException e) {
      this.logger.status(
          "remoteproxytodiscovery/exception/executionexception", "message", e.getMessage());
    } catch (final TimeoutException e) {
      this.logger.status(
          "remoteproxytodiscovery/exception/timeoutexception", "message", e.getMessage());
    } catch (final SecurityException e) {
      this.logger.status(
          "remoteproxytodiscovery/exception/securityexception", "message", e.getMessage());
      e.printStackTrace();
    } finally {
      AccessController.doPrivileged(
          new PrivilegedAction<Object>() {
            public Object run() {
              future.cancel(true);
              cachePool.shutdownNow();
              return null;
            }
          });

      this.logger.status("remoteproxytodiscovery/end");
    }

    this.logger.status("remoteproxytodiscovery/end");
    return null;
  }