@Test
 public void removeAllElements() throws Exception {
   List<ParserFeature> features = Collections.emptyList();
   document =
       XmlHelper.parse(
           getClass()
               .getResourceAsStream(
                   "/com/google/code/configprocessor/data/xml-target-config-2.xml"),
           features);
   RemoveAction action =
       new RemoveAction("/root/property[@attribute='value3']", NodeSetPolicy.ALL);
   XmlActionProcessingAdvisor advisor =
       new XmlRemoveActionProcessingAdvisor(
           action, expressionResolver, namespaceContext, Collections.<ParserFeature>emptyList());
   String expected =
       "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
           + LINE_SEPARATOR
           + "<root>"
           + LINE_SEPARATOR
           + " <property5>"
           + LINE_SEPARATOR
           + "  <nested1 a=\"1\"/>"
           + LINE_SEPARATOR
           + " </property5>"
           + LINE_SEPARATOR
           + "</root>"
           + LINE_SEPARATOR;
   executeTest(advisor, expected);
 }
 @Test
 public void testCompareWithEmptyLists() {
   final List<String> working = Collections.emptyList();
   final List<String> base = Collections.emptyList();
   final CollectionNode node = differ.compare(working, base);
   assertThat(node.hasChanges(), is(false));
   assertThat(node.hasChildren(), is(false));
 }
 @Test
 public void removeNestedElement() throws Exception {
   RemoveAction action = new RemoveAction("/root/property5/nested1");
   XmlActionProcessingAdvisor advisor =
       new XmlRemoveActionProcessingAdvisor(
           action, expressionResolver, namespaceContext, Collections.<ParserFeature>emptyList());
   String expected =
       "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
           + LINE_SEPARATOR
           + "<root>"
           + LINE_SEPARATOR
           + " <property1>value1</property1>"
           + LINE_SEPARATOR
           + " <property2/>"
           + LINE_SEPARATOR
           + " <property3 attribute=\"value3\">value3</property3>"
           + LINE_SEPARATOR
           + " <property4 attribute=\"value4\">value4</property4>"
           + LINE_SEPARATOR
           + " <property5/>"
           + LINE_SEPARATOR
           + "</root>"
           + LINE_SEPARATOR;
   executeTest(advisor, expected);
 }
  @Before
  public void setup() {
    for (int customerId = 1; customerId <= 5; customerId++) {
      ProcessInstance pi =
          sf.getWorkflowService()
              .startProcess(new QName(MODEL_NAME2, "OrderCreation").toString(), null, true);
      List<ActivityInstance> w = getWorklist();
      Assert.assertEquals("worklist", 1, w.size());
      ActivityInstance ai = w.get(0);
      Assert.assertEquals("process instance", pi.getOID(), ai.getProcessInstanceOID());
      Assert.assertEquals("activity instance", "EnterOrderData", ai.getActivity().getId());
      Map<String, Object> order = CollectionUtils.newMap();
      order.put("date", new Date());
      order.put("customerId", customerId);
      ai =
          complete(
              ai, PredefinedConstants.DEFAULT_CONTEXT, Collections.singletonMap("Order", order));

      try {
        ProcessInstanceStateBarrier.instance().await(pi.getOID(), ProcessInstanceState.Completed);
      } catch (Exception e) {
      }
      w = getWorklist();
    }
  }
 @Test
 public void testCompareWithRemovedCollection() throws Exception {
   final List<Object> working = null;
   final List<Object> base = Collections.emptyList();
   final CollectionNode node = differ.compare(working, base);
   assertThat(node.getState(), is(Node.State.REMOVED));
 }
 @Before
 public void inContext() {
   updatedFiles = newArrayList();
   core = new DefaultInfinitestCore(mock(TestRunner.class), new ControlledEventQueue());
   testDetector = mock(TestDetector.class);
   when(testDetector.getCurrentTests()).thenReturn(Collections.<String>emptySet());
   core.setTestDetector(testDetector);
 }
 @Test(expected = ParsingException.class)
 public void removeMissingSingleElement() throws Exception {
   RemoveAction action = new RemoveAction("/root/nonExistentProperty");
   XmlActionProcessingAdvisor advisor =
       new XmlRemoveActionProcessingAdvisor(
           action,
           expressionResolver,
           namespaceContext,
           Collections.<ParserFeature>emptyList(),
           true);
   executeTest(advisor, null);
 }
  @Test
  public void shouldAlsoLookForClassesInClassDirectories() throws Exception {
    newDir = new File("tempClassDir");
    List<File> buildPaths = asList(newDir);
    ClasspathProvider classpath =
        new StandaloneClasspath(
            Collections.<File>emptyList(),
            buildPaths,
            FakeEnvironments.systemClasspath() + pathSeparator + newDir.getAbsolutePath());

    String classname = "org.fakeco.Foobar2";
    createClass(classname);

    builder = new JavaClassBuilder(classpath);
    JavaClass javaClass = builder.createClass(classname);
    assertEquals(classname, javaClass.getName());
    assertFalse(javaClass.isATest());
  }
Пример #9
0
  private <T> Collection<T> random(Store<T> s, int rows, int sampleSize) {
    if (rows > 0) {
      Set<T> ret = new HashSet<T>();
      Random r = new Random();
      for (int i = 0; i < sampleSize; i++) {
        try {
          int rand = r.nextInt(rows);
          if (rand != 0) {
            T t;
            try {
              Method lazy = s.getClass().getDeclaredMethod("lazyGet", Long.TYPE);
              t = (T) lazy.invoke(s, new Long(rand));
            } catch (NoSuchMethodException e) {
              System.out.println("WARN:: Unable to lazily get object. Using full get.");
              t = s.get(Integer.valueOf(rand).longValue());
            } catch (InvocationTargetException e) {
              System.out.println("WARN:: Unable to lazily get object. Using full get.");
              t = s.get(Integer.valueOf(rand).longValue());
            } catch (IllegalAccessException e) {
              System.out.println("WARN:: Unable to lazily get object. Using full get.");
              t = s.get(Integer.valueOf(rand).longValue());
            }

            if (t != null) {
              ret.add(t);
            }
          }
        } catch (IOException e) {
          System.out.println("ERROR:: could not get random object from store");
        }
      }
      return ret;
    } else {
      return Collections.emptySet();
    }
  }
  /**
   * The following test case should ensure that
   *
   * <ul>
   *   <li>Any modifications to an attribute of a BOI via API isn't reflected to process data which
   *       are using the BO
   *   <li>Any modifications to an attribute of a BOI via the process data is only reflected to the
   *       BOI which is attached to the synthetic process instance and that it doesn't affect other
   *       BOIs which are used in other processes
   * </ul>
   */
  @Test
  public void checkFilteringOnBusinessObjectAttrChange() {
    // setup
    final int customerIdOffset = 100;
    final int customerCount = 3;
    for (int customerId = 1; customerId <= customerCount; customerId++) {
      ProcessInstance pi =
          sf.getWorkflowService()
              .startProcess(new QName(MODEL_NAME2, "DistributedOrder").toString(), null, true);
      List<ActivityInstance> w = getWorklist(pi);
      Assert.assertEquals("worklist", 1, w.size());
      ActivityInstance ai = w.get(0);
      Assert.assertEquals("activity instance", "CreateOrder", ai.getActivity().getId());
      Map<String, Object> order = CollectionUtils.newMap();
      order.put("date", new Date());
      order.put("customerId", customerIdOffset + customerId);
      order.put("items", "item " + customerId);
      ai =
          complete(
              ai, PredefinedConstants.DEFAULT_CONTEXT, Collections.singletonMap("Order", order));

      try {
        ActivityInstanceStateBarrier.instance().await(ai.getOID(), ActivityInstanceState.Completed);
      } catch (Exception e) {
      }
    }

    // after DistributeCreation activity is completed we have the following state:
    // * 2 asynchronous subprocesses are started: one which copies the data and the
    //   other one which doesn't
    // * 3 synchronous subprocesses are triggered: one with shared data, one with separate
    //   but copied data and the last one with separate data without copying
    // This results into the following state:
    // * Each process has created four business object instances
    //   * One which is attached to a synthetic process instance
    //   * 3 other BOIs which are attached to a real process instance
    String businessObjectQualifiedId = new QName(MODEL_NAME2, "Order").toString();
    BusinessObjectQuery businessObjectQuery =
        BusinessObjectQuery.findForBusinessObject(businessObjectQualifiedId);
    businessObjectQuery
        .getFilter()
        .addAndTerm()
        .add(DataFilter.greaterThan("Order", "customerId", customerIdOffset));
    businessObjectQuery.setPolicy(
        new BusinessObjectQuery.Policy(
            BusinessObjectQuery.Option.WITH_VALUES, BusinessObjectQuery.Option.WITH_DESCRIPTION));
    BusinessObjects bos = sf.getQueryService().getAllBusinessObjects(businessObjectQuery);
    Assert.assertEquals("Only one business object, namely Order, is expected", 1, bos.getSize());
    Assert.assertEquals(
        "Business object instances count isn't the same as started process ergo the count of the synthetic process instances",
        customerCount,
        getTotalSize(bos));

    // Wait that all ShowOrder processes are started (unfortunately we cannot use
    // ProcessInstanceStateBarrier here
    // because of the async processes.
    ProcessInstanceQuery piQuery = ProcessInstanceQuery.findAlive("ShowOrder");
    boolean waitForPIs = true;
    while (waitForPIs) {
      long instanceCount = sf.getQueryService().getProcessInstancesCount(piQuery);
      waitForPIs = instanceCount != (customerCount * 5);

      if (waitForPIs) {
        try {
          Thread.sleep(100);
        } catch (InterruptedException e) {
        }
      }
    }

    BusinessObject bo = bos.get(0);
    BusinessObject.Value customer101 = null;
    for (BusinessObject.Value boValue : bo.getValues()) {
      Map<?, ?> boAttr = (Map<?, ?>) boValue.getValue();
      Integer customerId = (Integer) boAttr.get("customerId");
      if (Integer.valueOf(customerIdOffset + 1).equals(customerId)) {
        customer101 = boValue;
      }
    }
    Assert.assertNotNull("Customer " + customerIdOffset + 1 + " not found", customer101);

    // Update BOI via API...
    ((Map) customer101.getValue()).put("items", "newitems");
    sf.getWorkflowService()
        .updateBusinessObjectInstance(businessObjectQualifiedId, customer101.getValue());

    // ...and validate if no process data is modified
    piQuery = ProcessInstanceQuery.findActive();
    FilterTerm filter = piQuery.getFilter().addAndTerm();
    filter.add(
        DataFilter.between(
            "Order", "customerId", customerIdOffset, customerIdOffset + customerCount));
    filter.add(DataFilter.like("Order", "items", "item%"));
    filter.addAndTerm().add(ProcessInstanceHierarchyFilter.ROOT_PROCESS);
    piQuery.setPolicy(SubsetPolicy.UNRESTRICTED);
    ProcessInstances rootPIs = sf.getQueryService().getAllProcessInstances(piQuery);
    // Root process instances are the DistributedOrder processes and the ShowOrder processes which
    // was started
    // as async processes and which had copied the data
    Assert.assertEquals(
        "Changes in BOIs must not be reflected in process instance data",
        customerCount * 2,
        rootPIs.getTotalCount());

    // Update BOI for a given process via data path...
    long piOid = rootPIs.get(0).getOID();
    ((Map) customer101.getValue()).put("items", "newitems1");
    sf.getWorkflowService().setOutDataPath(piOid, "OrderDataPath", (Map) customer101.getValue());

    // ...and validate if the BOI is updated...
    businessObjectQuery =
        BusinessObjectQuery.findWithPrimaryKey(
            businessObjectQualifiedId, ((Map) customer101.getValue()).get("customerId"));
    businessObjectQuery.setPolicy(
        new BusinessObjectQuery.Policy(BusinessObjectQuery.Option.WITH_VALUES));
    bos = sf.getQueryService().getAllBusinessObjects(businessObjectQuery);
    Assert.assertEquals("Only one business object, namely Order, is expected", 1, bos.getSize());
    List<BusinessObject.Value> boValues = bos.get(0).getValues();
    Assert.assertEquals(1, boValues.size());
    Assert.assertEquals("newitems1", ((Map) boValues.get(0).getValue()).get("items"));

    // ...but the other process instance data should be untouched
    piQuery = ProcessInstanceQuery.findActive();
    filter = piQuery.getFilter().addAndTerm();
    filter.add(
        DataFilter.between(
            "Order", "customerId", customerIdOffset, customerIdOffset + customerCount));
    filter.add(DataFilter.like("Order", "items", "item%"));
    filter.addAndTerm().add(ProcessInstanceHierarchyFilter.ROOT_PROCESS);
    piQuery.setPolicy(SubsetPolicy.UNRESTRICTED);
    rootPIs = sf.getQueryService().getAllProcessInstances(piQuery);
    Assert.assertEquals(
        "Changes in BOIs must not be reflected in process instance data",
        (customerCount * 2) - 1,
        rootPIs.getTotalCount());
  }
 @Test
 public void testCompareWithAddedCollection() throws Exception {
   final List<Object> working = Collections.emptyList();
   final CollectionNode node = differ.compare(working, null);
   assertThat(node.getState(), is(Node.State.ADDED));
 }
  protected OrderModel placeTestOrder(final boolean valid)
      throws InvalidCartException, CalculationException {
    final CartModel cart = cartService.getSessionCart();
    final UserModel user = userService.getCurrentUser();
    cartService.addNewEntry(cart, productService.getProductForCode("testProduct1"), 1, null);
    cartService.addNewEntry(cart, productService.getProductForCode("testProduct2"), 2, null);
    cartService.addNewEntry(cart, productService.getProductForCode("testProduct3"), 3, null);

    final AddressModel deliveryAddress = new AddressModel();
    deliveryAddress.setOwner(user);
    deliveryAddress.setFirstname("Der");
    deliveryAddress.setLastname("Buck");
    deliveryAddress.setTown("Muenchen");
    deliveryAddress.setCountry(commonI18NService.getCountry("DE"));
    modelService.save(deliveryAddress);

    final DebitPaymentInfoModel paymentInfo = new DebitPaymentInfoModel();
    paymentInfo.setOwner(cart);
    paymentInfo.setBank("MeineBank");
    paymentInfo.setUser(user);
    paymentInfo.setAccountNumber("34434");
    paymentInfo.setBankIDNumber("1111112");
    paymentInfo.setBaOwner("Ich");
    paymentInfo.setCode("testPaymentInfo1");
    modelService.save(paymentInfo);

    cart.setDeliveryMode(deliveryService.getDeliveryModeForCode("free"));
    cart.setDeliveryAddress(deliveryAddress);
    cart.setPaymentInfo(paymentInfo);

    final CardInfo card = new CardInfo();
    card.setCardType(CreditCardType.VISA);
    card.setCardNumber("4111111111111111");
    card.setExpirationMonth(Integer.valueOf(12));
    if (valid) {
      card.setExpirationYear(Integer.valueOf(Calendar.getInstance().get(Calendar.YEAR) + 2));
    } else {
      card.setExpirationYear(Integer.valueOf(Calendar.getInstance().get(Calendar.YEAR) - 2));
    }

    final PaymentTransactionModel paymentTransaction =
        paymentService
            .authorize(
                "code4" + codeNo++,
                BigDecimal.ONE,
                Currency.getInstance("EUR"),
                deliveryAddress,
                deliveryAddress,
                card)
            .getPaymentTransaction();

    cart.setPaymentTransactions(Collections.singletonList(paymentTransaction));
    modelService.save(cart);
    calculationService.calculate(cart);

    final CommerceCheckoutParameter parameter = new CommerceCheckoutParameter();
    parameter.setEnableHooks(true);
    parameter.setCart(cart);
    parameter.setSalesApplication(SalesApplication.WEB);

    return commerceCheckoutService.placeOrder(parameter).getOrder();
  }
Пример #13
0
public class HttpClientUtilsTest {

  //	public static void main(String[] args) throws Exception {
  //		System.out.println(0xFFFF);
  //		HttpClientUtilsTest.setUpClass();
  //	}

  static HttpServer httpServer;
  static HttpServer httpServer2;

  static ServerSocket serverSocket;
  static Collection<Socket> clientSockets = Collections.synchronizedSet(new HashSet<Socket>());
  static transient long testConnectionResetCount;

  static long g_beginTime;

  @BeforeClass
  public static void setUpClass() throws Exception {
    Logger.info(HttpClientUtilsTest.class, "-------------- setUpClass starting... -------------");
    g_beginTime = System.currentTimeMillis();

    httpServer = HttpServer.create(new InetSocketAddress(0xFFFF - 1), 0);
    httpServer.createContext("/test/testConnectionCount1", new testConnectionCountHandler());
    httpServer.createContext("/test/testConnectionCount2", new testConnectionCountHandler());
    httpServer.createContext("/test/testConnectionCount3", new testConnectionCountHandler());
    httpServer.createContext("/test/testConnectionCount4", new testConnectionCountHandler());
    httpServer.createContext("/test/testConnectionCount5", new testConnectionCountHandler());
    httpServer.createContext("/test/testConnectionCount6", new testConnectionCountHandler());
    httpServer.createContext("/test/testConnectionCount7", new testConnectionCountHandler());
    httpServer.createContext("/test/testConnectionTimeout", new testConnectionTimeoutHandler());
    httpServer.createContext(
        "/test/testConnectionRequestTimeout", new testConnectionTimeoutHandler());
    httpServer.createContext(
        "/test/testNoHttpResponseException", new testNoHttpResponseExceptionHandler());
    httpServer.createContext(
        "/test/testPostCustomerBodyAndCharset", new testCommonResponseHandler());
    httpServer.setExecutor(null); // creates a default executor
    httpServer.start();
    Logger.info(HttpClientUtilsTest.class, "-------------- HttpServer started -------------");

    httpServer2 = HttpServer.create(new InetSocketAddress(0xFFFF - 2), 0);
    httpServer2.createContext("/test/testConnectionCount1", new testConnectionCountHandler());
    httpServer2.createContext("/test/testConnectionCount2", new testConnectionCountHandler());
    httpServer2.createContext("/test/testConnectionCount3", new testConnectionCountHandler());
    httpServer2.createContext("/test/testConnectionCount4", new testConnectionCountHandler());
    httpServer2.createContext("/test/testConnectionCount5", new testConnectionCountHandler());
    httpServer2.createContext("/test/testConnectionCount6", new testConnectionCountHandler());
    httpServer2.createContext("/test/testConnectionCount7", new testConnectionCountHandler());
    httpServer2.createContext("/test/testConnectionTimeout", new testConnectionTimeoutHandler());
    httpServer2.createContext(
        "/test/testConnectionRequestTimeout", new testConnectionTimeoutHandler());
    httpServer2.setExecutor(null); // creates a default executor
    httpServer2.start();
    Logger.info(HttpClientUtilsTest.class, "-------------- HttpServer2 started -------------");

    serverSocket = new ServerSocket(65532);
    new Thread("SocketResetableServerSimulator") {
      @Override
      public void run() {
        while (true) {
          try {
            final Socket clientSocket = serverSocket.accept();
            clientSockets.add(clientSocket);
            ++testConnectionResetCount;
            new Thread("clientSocket_" + testConnectionResetCount) {
              @Override
              public void run() {
                Logger.info(this, testConnectionResetCount + "_Connected: " + clientSocket);
                try {
                  String req = null;
                  // req = IOUtils.toString(clientSocket.getInputStream());
                  Logger.info(this, testConnectionResetCount + "_Request content: " + req);
                  Thread.sleep(90000);
                } catch (Exception e) {
                  Throwable ee = ExceptionUtils.getRootCause(e);
                  if (ee == null) {
                    ee = e;
                  }
                  Logger.error(this, "", ee);
                } finally {
                  Logger.info(this, testConnectionResetCount + "_done: " + clientSocket);
                }
              }
            }.start();
          } catch (Exception e) {
            Throwable ee = ExceptionUtils.getRootCause(e);
            if (ee == null) {
              ee = e;
            }
            Logger.error(this, "", ee);
            // Assert.fail(String.valueOf(ee));
          }
        }
      }
    }.start();
    Logger.info(
        HttpClientUtilsTest.class,
        "-------------- SocketResetableServerSimulator started -------------");

    Timer timer = new Timer("F5-connection-reset-Timer", true);
    timer.schedule(
        new TimerTask() {
          @Override
          public void run() {
            Logger.info(this, "------------- clientSockets close ------------");
            Socket s = null;
            for (Iterator<Socket> iter = clientSockets.iterator(); iter.hasNext(); ) {
              s = iter.next();
              try {
                Logger.info(this, "------------- clientSocket: " + s);
                s.close();
                iter.remove();
              } catch (Exception e) {
                Throwable ee = ExceptionUtils.getRootCause(e);
                if (ee == null) {
                  ee = e;
                }
                Logger.error(this, "Socket.close error: " + s, ee);
              }
            }
          }
        },
        60000,
        60000);
    Logger.info(
        HttpClientUtilsTest.class,
        "-------------- F5-connection-reset-Timer started -------------");
  }

  @AfterClass
  public static void tearDownClass() {
    Logger.info(
        HttpClientUtilsTest.class,
        "============= [tearDownClass]global take time milliseconds: "
            + (System.currentTimeMillis() - g_beginTime));
    if (httpServer != null) {
      httpServer.stop(0);
    }
    if (httpServer2 != null) {
      httpServer2.stop(0);
    }
    if (serverSocket != null && !serverSocket.isClosed()) {
      try {
        serverSocket.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    for (Socket s : clientSockets) {
      try {
        if (!s.isClosed()) s.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  HttpClientUtils httpClientUtils;

  long beginTime;

  @Before
  public void reset() {
    Logger.info(this, "-------------- reset begin -------------");
    beginTime = System.currentTimeMillis();
    if (httpClientUtils != null) {
      httpClientUtils.destroy();
    }
    Logger.info(this, "-------------- reset end -------------");
  }

  @After
  public void clean() {
    Logger.info(
        this,
        "============= test take time milliseconds: " + (System.currentTimeMillis() - beginTime));
    if (httpClientUtils != null) {
      httpClientUtils.destroy();
    }
  }

  @Test
  public void testConnectionCount() {
    testConnectionCount = 0;
    httpClientUtils = new HttpClientUtils();
    //		httpClientUtils.setMaxConnPerRoute(0);  // default:-1, means 2
    //		httpClientUtils.setMaxConnTotal(0);     // default:-1, means 20

    httpClientUtils.setMaxConnPerRoute(3);
    httpClientUtils.setMaxConnTotal(100);

    //		httpClientUtils.setMaxConnPerRoute(100);
    //		httpClientUtils.setMaxConnTotal(3);

    httpClientUtils.initHttpClient();
    Logger.info(this, "-------------- HttpClient initialized -------------");

    final ExceptionHandler exceptionHandler =
        new ExceptionHandler() {
          public boolean handle(Throwable e) {
            return e == null;
          }
        };

    new Thread("t-1") {
      @Override
      public void run() {
        runTest("http://localhost:65534/test/testConnectionCount", 7, exceptionHandler, 2);
      }
    }.start();
    new Thread("t-2") {
      @Override
      public void run() {
        runTest("http://localhost:65533/test/testConnectionCount", 7, exceptionHandler, 1);
      }
    }.start();
    new Thread("t-3") {
      @Override
      public void run() {
        runTest("http://www.baidu.com", 1, exceptionHandler, 10);
      }
    }.start();
    runTest("https://www.lufax.com", 1, exceptionHandler, 3);
    /*
            测试结论:
    		1、 ”Connection“ == 【URL】;“Route” == 【IP:port】。
    		2、连接数越多,并发性能越高;反之,将频繁进行Connection released/leased。
    		3、当连接数满足不了并发的要求时,并发请求Connection的线程将wait。

    		【route allocated: 1 of 3; total allocated: 9 of 100】
    [DEBUG]-[2014-03-07 09:56:46.828]-[http://localhost:65533/test/testConnectionCount_runTest_1] - Connection released: [id: 4][route: {}->http://localhost:65533][total kept alive: 6; route allocated: 1 of 3; total allocated: 9 of 100]
    [org.apache.http.impl.conn.PoolingHttpClientConnectionManager]
    	org.apache.http.impl.conn.PoolingHttpClientConnectionManager.releaseConnection(PoolingHttpClientConnectionManager.java:282)
    		 */
  }

  @Test
  public void testConnectionTimeout() {
    testConnectionTimeoutCount = 0;
    httpClientUtils = new HttpClientUtils();

    httpClientUtils.setMaxConnPerRoute(1);
    httpClientUtils.setMaxConnTotal(1);

    /*
          PING www.a.shifen.com (115.239.210.26) 56(84) bytes of data.
    64 bytes from 115.239.210.26: icmp_seq=1 ttl=50 time=6.97 ms
    PING www-wide.l.google.com (74.125.128.199) 56(84) bytes of data.
    64 bytes from hg-in-f199.1e100.net (74.125.128.199): icmp_seq=1 ttl=42 time=33.2 ms
     */
    httpClientUtils.setConnectTimeout(10);

    httpClientUtils.initHttpClient();
    Logger.info(this, "-------------- HttpClient initialized -------------");

    ExceptionHandler exceptionHandler =
        new ExceptionHandler() {
          public boolean handle(Throwable e) {
            return e == null;
          }
        };
    ExceptionHandler exceptionHandler2 =
        new ExceptionHandler() {
          public boolean handle(Throwable e) {
            return (ConnectException.class == e.getClass())
                && "Network is unreachable".equals(e.getMessage());
          }
        };

    runTest("http://www.baidu.com", 1, exceptionHandler, 1);
    runTest("https://www.lufax.com/", 1, exceptionHandler2, 1);

    /*
            测试结论:
    		1、...timed out. Connection will be retried using another IP address

    		9、runTest("https://www.google.com.hk", 1, exceptionHandler, 1); 测试日志阶段截段:
    [BUG]-[2014-03-05 19:40:06.211]-[testConnectionCount_12] - Connecting to www.google.com.hk/74.125.128.199:443
    [org.apache.http.conn.HttpClientConnectionManager]
    	org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:114)

    [DEBUG]-[2014-03-05 19:40:06.213]-[testConnectionCount_12] - Connect to www.google.com.hk/74.125.128.199:443 timed out. Connection will be retried using another IP address
    [org.apache.http.conn.HttpClientConnectionManager]
    	org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:143)

    [DEBUG]-[2014-03-05 19:40:06.214]-[testConnectionCount_12] - Connecting to www.google.com.hk/2404:6800:4005:c00:0:0:0:c7:443
    [org.apache.http.conn.HttpClientConnectionManager]
    	org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:114)

    [DEBUG]-[2014-03-05 19:40:06.214]-[testConnectionCount_12] - http-outgoing-101: Shutdown connection
    [org.apache.http.impl.conn.DefaultManagedHttpClientConnection]
    	org.apache.http.impl.conn.LoggingManagedHttpClientConnection.shutdown(LoggingManagedHttpClientConnection.java:87)

    [DEBUG]-[2014-03-05 19:40:06.214]-[testConnectionCount_12] - Connection discarded
    [org.apache.http.impl.execchain.MainClientExec]
    	org.apache.http.impl.execchain.ConnectionHolder.abortConnection(ConnectionHolder.java:126)

    [DEBUG]-[2014-03-05 19:40:06.214]-[testConnectionCount_12] - http-outgoing-101: Close connection
    [org.apache.http.impl.conn.DefaultManagedHttpClientConnection]
    	org.apache.http.impl.conn.LoggingManagedHttpClientConnection.close(LoggingManagedHttpClientConnection.java:79)

    [DEBUG]-[2014-03-05 19:40:06.214]-[testConnectionCount_12] - Connection released: [id: 101][route: {s}->https://www.google.com.hk:443][total kept alive: 0; route allocated: 0 of 1; total allocated: 0 of 1]
    [org.apache.http.impl.conn.PoolingHttpClientConnectionManager]
    	org.apache.http.impl.conn.PoolingHttpClientConnectionManager.releaseConnection(PoolingHttpClientConnectionManager.java:282)

    [DEBUG]-[2014-03-05 19:40:06.214]-[testConnectionCount_13] - Connection leased: [id: 102][route: {s}->https://www.google.com.hk:443][total kept alive: 0; route allocated: 1 of 1; total allocated: 1 of 1]
    [org.apache.http.impl.conn.PoolingHttpClientConnectionManager]
    	org.apache.http.impl.conn.PoolingHttpClientConnectionManager.leaseConnection(PoolingHttpClientConnectionManager.java:246)
    		 */
  }

  @Test
  public void testConnectionRequestTimeout() {
    testConnectionResetCount = 0;
    httpClientUtils = new HttpClientUtils();

    httpClientUtils.setMaxConnPerRoute(1);
    httpClientUtils.setMaxConnTotal(1);
    httpClientUtils.setConnectRequestTimeout(100);
    httpClientUtils.setConnectTimeout(10);

    httpClientUtils.initHttpClient();

    ExceptionHandler exceptionHandler =
        new ExceptionHandler() {
          public boolean handle(Throwable e) {
            if (e.getMessage().contains("Timeout waiting for connection from pool")) {
              Assert.assertTrue(false);
              // throw new RuntimeException("No available connect to user", e);
            }
            return e == null;
          }
        };
    runTest("http://localhost:65534/test/testConnectionRequestTimeout", 1, exceptionHandler, 2);
  }

  @Test
  public void testNoHttpResponseExceptionRetry() {
    testConnectionResetCount = 0;
    httpClientUtils = new HttpClientUtils();
    httpClientUtils.initHttpClient();

    ExceptionHandler exceptionHandler =
        new ExceptionHandler() {
          public boolean handle(Throwable e) {
            return e instanceof NoHttpResponseException;
          }
        };
    runTest("http://localhost:65534/test/testNoHttpResponseException", 1, exceptionHandler, 1);
  }

  @Test
  public void testSocketTimeout() {
    testConnectionTimeoutCount = 0;
    httpClientUtils = new HttpClientUtils();

    httpClientUtils.setMaxConnPerRoute(1);
    httpClientUtils.setMaxConnTotal(1);
    httpClientUtils.setSocketTimeout(2500);

    httpClientUtils.initHttpClient();
    Logger.info(this, "-------------- HttpClient initialized -------------");

    ExceptionHandler exceptionHandler =
        new ExceptionHandler() {
          public boolean handle(Throwable e) {
            return (SocketTimeoutException.class == e.getClass())
                && "Read timed out".equals(e.getMessage());
          }
        };

    runTest("http://localhost:65534/test/testConnectionTimeout", 1, exceptionHandler, 1);
  }

  @Test
  public void testConnectionResetByHttpClientUtils() throws IOException {
    testConnectionResetCount = 0;

    httpClientUtils = new HttpClientUtils();
    httpClientUtils.initHttpClient();
    Logger.info(this, "-------------- HttpClient initialized -------------");

    String resp = null;
    try {
      resp = httpClientUtils.get("http://*****:*****@see 'http://www.coderanch.com/t/490463/sockets/java/Timeout-retry-URLHTTPRequest'
   */
  @Test
  public void testConnectionResetByHttpURLConnection() throws IOException {
    testConnectionResetCount = 0;

    String resp = null;
    try {
      HttpURLConnection conn =
          (HttpURLConnection) new URL("http://localhost:65532/soso").openConnection();
      conn.setDoOutput(true);
      conn.setRequestMethod("POST");
      conn.getOutputStream().write("username".getBytes());
      resp = conn.getResponseCode() + "";
    } catch (IOException e) {
      Throwable ee = ExceptionUtils.getRootCause(e);
      if (ee == null) {
        ee = e;
      }
      Logger.error(this, "", ee);
      Assert.assertNotSame(NoHttpResponseException.class, ee.getClass());
      Assert.assertSame(SocketException.class, ee.getClass());
      Assert.assertTrue(
          "Connection reset".equals(ee.getMessage())
              || "Socket closed".equals(ee.getMessage())
              || "Unexpected end of file from server".equals(ee.getMessage()));
    } finally {
      Logger.info(
          this,
          "resp[HttpURLConnection]-["
              + testConnectionResetCount
              + "]=========["
              + resp
              + "]=========");
    }
    Assert.assertEquals(2, testConnectionResetCount);
  }

  private transient boolean ok = true;

  public void runTest(
      final String url,
      final int urlGroupSize,
      final ExceptionHandler exceptionHandler,
      int threadCount) {
    ok = true;
    long beginTime = System.currentTimeMillis();
    ArrayList<Thread> list = new ArrayList<Thread>();
    for (int t = 1; t <= threadCount; t++) {
      Thread tt =
          new Thread(url + "_runTest_" + t) {
            @Override
            public void run() {
              boolean useGroup = urlGroupSize > 1;
              for (int i = 1; i <= urlGroupSize; i++) {
                if (!ok) return;

                String resp = null;
                Throwable t = null;
                try {
                  if (useGroup) {
                    resp = httpClientUtils.get(url + i);
                  } else {
                    resp = httpClientUtils.get(url);
                  }
                } catch (Throwable e) {
                  Throwable ee = ExceptionUtils.getRootCause(e);
                  if (ee == null) {
                    ee = e;
                  }
                  Logger.error(this, "", ee);
                  t = ee;
                } finally {
                  if (ok) {
                    ok = exceptionHandler.handle(t);
                  }
                }
                Logger.info(this, "resp[" + i + "]=========[" + resp + "]=========");
              }
            }
          };
      list.add(tt);
      tt.start();
    }
    for (Thread tt : list) {
      try {
        tt.join();
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    }
    Assert.assertTrue(ok);
    Logger.info(this, "take time milliseconds: " + (System.currentTimeMillis() - beginTime));
  }

  static interface ExceptionHandler {
    boolean handle(Throwable t);
  }

  static class testConnectionCountHandler implements HttpHandler {
    public void handle(HttpExchange t) throws IOException {
      ++testConnectionCount;
      Logger.info(this, "testConnectionCountHandler testConnectionCount: " + testConnectionCount);
      // InputStream is = t.getRequestBody();
      // read(is); // .. read the request body
      String response = getClass().getSimpleName();
      t.sendResponseHeaders(200, response.length());
      OutputStream os = t.getResponseBody();
      os.write(response.getBytes());
      os.close();
    }
  }

  static transient long testConnectionCount;

  static class testConnectionTimeoutHandler implements HttpHandler {
    public void handle(HttpExchange t) throws IOException {
      ++testConnectionTimeoutCount;
      Logger.info(
          this,
          "testConnectionTimeoutHandler testConnectionTimeoutCount: " + testConnectionTimeoutCount);
      try {
        Thread.sleep(3000);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
      Logger.info(this, "==========testConnectionTimeoutHandler sleep after.");
      // InputStream is = t.getRequestBody();
      // read(is); // .. read the request body
      String response = getClass().getSimpleName();
      t.sendResponseHeaders(200, response.length());
      OutputStream os = t.getResponseBody();
      os.write(response.getBytes());
      os.close();
    }
  }

  static class testNoHttpResponseExceptionHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
      ++testConnectionTimeoutCount;
      Logger.info(
          this,
          "testNoHttpResponseExceptionHandler testConnectionTimeoutCount: "
              + testConnectionTimeoutCount);
      try {
        Thread.sleep(3000);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
      Logger.info(this, "==========testNoHttpResponseExceptionHandler sleep 3s after.");
      //            httpExchange.sendResponseHeaders(200, 0);//no response
      httpExchange.close();
    }
  }

  static class testCommonResponseHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
      ++testConnectionTimeoutCount;
      Logger.info(
          this,
          "testCommonResponseHandler testConnectionTimeoutCount: " + testConnectionTimeoutCount);

      Logger.info(
          this, String.format("request headers:%s", httpExchange.getRequestHeaders().entrySet()));
      Logger.info(this, String.format("request method:%s", httpExchange.getRequestMethod()));
      Logger.info(this, String.format("request uri:%s", httpExchange.getRequestURI()));
      Logger.info(this, String.format("request body:%s", httpExchange.getRequestBody()));

      String resp = "OK";
      httpExchange.sendResponseHeaders(200, resp.getBytes().length);
      httpExchange.getResponseBody().write(resp.getBytes());
      httpExchange.close();
    }
  }

  static transient long testConnectionTimeoutCount;

  @Test
  public void testPostCustomerBodyAndCharset() {
    httpClientUtils = new HttpClientUtils();
    httpClientUtils.initHttpClient();
    Logger.info(this, "-------------- HttpClient initialized -------------");
    // testPostCustomerBodyAndCharset
    String resp = "";
    try {
      resp =
          httpClientUtils.post(
              "http://localhost:65534/test/testPostCustomerBodyAndCharset",
              "<?xml version=\"1.0\" encoding=\"GBK\"?><AIPG><INFO>你好</INFO></AIPG>",
              "GBK");
    } catch (IOException e) {
      Throwable ee = ExceptionUtils.getRootCause(e);
      if (ee == null) {
        ee = e;
      }
      Logger.error(this, "", ee);
      Assert.assertTrue(false);
      //            Assert.assertNotSame(NoHttpResponseException.class, ee.getClass());
      //            Assert.assertSame(SocketException.class, ee.getClass());
      //            Assert.assertTrue("Connection reset".equals(ee.getMessage()) || "Socket
      // closed".equals(ee.getMessage()) || "Unexpected end of file from
      // server".equals(ee.getMessage()));
    } finally {
      Logger.info(
          this,
          "resp[HttpURLConnection]-["
              + testConnectionResetCount
              + "]=========["
              + resp
              + "]=========");
    }
    //        Assert.assertEquals(1, testConnectionResetCount);
    Assert.assertTrue(true);
  }

  @Test
  public void test_get_baidu() throws Exception {
    httpClientUtils = new HttpClientUtils();
    httpClientUtils.setReUserConnection(false);
    httpClientUtils.initHttpClient();
    Logger.info(this, "-------------- HttpClient initialized -------------");
    //        for(int i =0;i<3){
    //
    //        }
    httpClientUtils.get("http://www.lufax.com" + "?" + RandomUtils.nextInt());
    httpClientUtils.get("http://www.lufax.com" + "?" + RandomUtils.nextInt());
    //         httpClientUtils.get("http://www.lufax.com" + "?" + RandomUtils.nextInt());
    //         httpClientUtils.get("http://www.lufax.com" + "?" + RandomUtils.nextInt());
    //         httpClientUtils.get("http://www.lufax.com" + "?" + RandomUtils.nextInt());
    //         httpClientUtils.get("http://www.lufax.com" + "?" + RandomUtils.nextInt());

    ExceptionHandler exceptionHandler =
        new ExceptionHandler() {
          public boolean handle(Throwable e) {
            return true;
          }
        };
    runTest("http://www.lufax.com", 1, exceptionHandler, 10);

    //        System.out.println(resp);
  }
}