/** Test {@link DeviceSetup#setUp(ITestDevice, IBuildInfo)} when build does not boot */
 public void testSetup_buildError() throws Exception {
   mMockDevice.setRecoveryMode(RecoveryMode.ONLINE);
   mMockFlasher.overrideDeviceOptions(mMockDevice);
   mMockFlasher.setForceSystemFlash(false);
   mMockFlasher.setDataWipeSkipList(Arrays.asList(new String[] {}));
   mMockFlasher.flash(mMockDevice, mMockBuildInfo);
   mMockDevice.waitForDeviceOnline();
   EasyMock.expect(mMockDevice.enableAdbRoot()).andStubReturn(Boolean.TRUE);
   mMockDevice.setDate(null);
   EasyMock.expect(mMockDevice.getBuildId()).andReturn(mMockBuildInfo.getBuildId());
   EasyMock.expect(mMockDevice.getBuildFlavor()).andReturn(mMockBuildInfo.getBuildFlavor());
   EasyMock.expect(mMockDevice.isEncryptionSupported()).andStubReturn(Boolean.TRUE);
   EasyMock.expect(mMockDevice.isDeviceEncrypted()).andStubReturn(Boolean.FALSE);
   mMockDevice.clearLogcat();
   mMockDevice.waitForDeviceAvailable(EasyMock.anyLong());
   EasyMock.expectLastCall().andThrow(new DeviceUnresponsiveException("foo"));
   mMockDevice.setRecoveryMode(RecoveryMode.AVAILABLE);
   EasyMock.replay(mMockFlasher, mMockDevice);
   try {
     mDeviceFlashPreparer.setUp(mMockDevice, mMockBuildInfo);
     fail("DeviceFlashPreparerTest not thrown");
   } catch (BuildError e) {
     // expected; use the general version to make absolutely sure that
     // DeviceFailedToBootError properly masquerades as a BuildError.
     assertTrue(e instanceof DeviceFailedToBootError);
   }
   EasyMock.verify(mMockFlasher, mMockDevice);
 }
 /** Set EasyMock expectations for a normal setup call */
 private void doSetupExpectations() throws TargetSetupError, DeviceNotAvailableException {
   mMockDevice.setRecoveryMode(RecoveryMode.ONLINE);
   mMockFlasher.overrideDeviceOptions(mMockDevice);
   mMockFlasher.setForceSystemFlash(false);
   mMockFlasher.setDataWipeSkipList(Arrays.asList(new String[] {}));
   mMockFlasher.flash(mMockDevice, mMockBuildInfo);
   mMockDevice.waitForDeviceOnline();
   EasyMock.expect(mMockDevice.enableAdbRoot()).andStubReturn(Boolean.TRUE);
   mMockDevice.setDate(null);
   EasyMock.expect(mMockDevice.getBuildId()).andReturn(mMockBuildInfo.getBuildId());
   EasyMock.expect(mMockDevice.getBuildFlavor()).andReturn(mMockBuildInfo.getBuildFlavor());
   EasyMock.expect(mMockDevice.isEncryptionSupported()).andStubReturn(Boolean.TRUE);
   EasyMock.expect(mMockDevice.isDeviceEncrypted()).andStubReturn(Boolean.FALSE);
   mMockDevice.clearLogcat();
   mMockDevice.waitForDeviceAvailable(EasyMock.anyLong());
   mMockDevice.setRecoveryMode(RecoveryMode.AVAILABLE);
   mMockDevice.postBootSetup();
 }
  private Map<String, String> testUpload(
      String path,
      final byte[] contents,
      String location,
      String profile,
      String version,
      boolean hasLocationHeader)
      throws Exception {
    final String old = System.getProperty("karaf.data");
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    FileUtils.deleteDirectory(new File("target/tmp"));

    Server server = new Server(0);
    server.setHandler(
        new AbstractHandler() {
          @Override
          public void handle(
              String target,
              Request baseRequest,
              HttpServletRequest request,
              HttpServletResponse response)
              throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
          }
        });
    server.start();

    try {
      int localPort = server.getConnectors()[0].getLocalPort();
      List<String> remoteRepos = Arrays.asList("http://relevant.not/maven2@id=central");
      RuntimeProperties props = new MockRuntimeProperties();
      MavenUploadProxyServlet servlet =
          new MavenUploadProxyServlet(
              props,
              "target/tmp",
              remoteRepos,
              false,
              "always",
              "warn",
              "http",
              "localhost",
              localPort,
              "fuse",
              "fuse",
              null,
              projectDeployer);

      HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
      EasyMock.expect(request.getPathInfo()).andReturn(path);
      EasyMock.expect(request.getInputStream())
          .andReturn(
              new ServletInputStream() {
                private int i;

                @Override
                public int read() throws IOException {
                  if (i >= contents.length) {
                    return -1;
                  }
                  return (contents[i++] & 0xFF);
                }
              });
      EasyMock.expect(request.getHeader("X-Location")).andReturn(location);
      EasyMock.expect(request.getParameter("profile")).andReturn(profile);
      EasyMock.expect(request.getParameter("version")).andReturn(version);

      final Map<String, String> headers = new HashMap<>();

      HttpServletResponse rm = EasyMock.createMock(HttpServletResponse.class);
      HttpServletResponse response =
          new HttpServletResponseWrapper(rm) {
            @Override
            public void addHeader(String name, String value) {
              headers.put(name, value);
            }
          };
      response.setStatus(EasyMock.anyInt());
      EasyMock.expectLastCall().anyTimes();
      response.setContentLength(EasyMock.anyInt());
      EasyMock.expectLastCall().anyTimes();
      response.setContentType((String) EasyMock.anyObject());
      EasyMock.expectLastCall().anyTimes();
      response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong());
      EasyMock.expectLastCall().anyTimes();
      response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject());
      EasyMock.expectLastCall().anyTimes();

      EasyMock.replay(request, rm);

      servlet.start();
      servlet.doPut(request, response);

      EasyMock.verify(request, rm);

      Assert.assertEquals(hasLocationHeader, headers.containsKey("X-Location"));

      return headers;
    } finally {
      server.stop();
      if (old != null) {
        System.setProperty("karaf.data", old);
      }
    }
  }
  private void testDownload(Handler serverHandler) throws Exception {
    final String old = System.getProperty("karaf.data");
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    FileUtils.deleteDirectory(new File("target/tmp"));

    Server server = new Server(0);
    server.setHandler(serverHandler);
    server.start();

    try {
      int localPort = server.getConnectors()[0].getLocalPort();
      List<String> remoteRepos = Arrays.asList("http://relevant.not/maven2@id=central");
      RuntimeProperties props = new MockRuntimeProperties();
      MavenDownloadProxyServlet servlet =
          new MavenDownloadProxyServlet(
              props,
              "target/tmp",
              remoteRepos,
              false,
              "always",
              "warn",
              "http",
              "localhost",
              localPort,
              "fuse",
              "fuse",
              null,
              projectDeployer,
              5);

      HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
      EasyMock.expect(request.getPathInfo())
          .andReturn("org.apache.camel/camel-core/2.13.0/camel-core-2.13.0-sources.jar");

      HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
      final ByteArrayOutputStream baos = new ByteArrayOutputStream();
      EasyMock.expect(response.getOutputStream())
          .andReturn(
              new ServletOutputStream() {
                @Override
                public void write(int b) throws IOException {
                  baos.write(b);
                }

                @Override
                public void write(byte[] b, int off, int len) throws IOException {
                  baos.write(b, off, len);
                }
              })
          .anyTimes();
      response.setStatus(EasyMock.anyInt());
      EasyMock.expectLastCall().anyTimes();
      response.setContentLength(EasyMock.anyInt());
      EasyMock.expectLastCall().anyTimes();
      response.setContentType((String) EasyMock.anyObject());
      EasyMock.expectLastCall().anyTimes();
      response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong());
      EasyMock.expectLastCall().anyTimes();
      response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject());
      EasyMock.expectLastCall().anyTimes();

      EasyMock.replay(request, response);

      servlet.start();
      servlet.doGet(request, response);
      Assert.assertArrayEquals(new byte[] {0x42}, baos.toByteArray());

      EasyMock.verify(request, response);
    } finally {
      server.stop();
      if (old != null) {
        System.setProperty("karaf.data", old);
      }
    }
  }
 /**
  * Expects any long argument. For details, see the EasyMock documentation.
  *
  * @return <code>0</code>.
  */
 protected final long anyLong() {
   return EasyMock.anyLong();
 }
  protected Set<String> commonMocks(int liveNodesCount) throws Exception {

    shardHandlerFactoryMock.getShardHandler();
    expectLastCall()
        .andAnswer(
            new IAnswer<ShardHandler>() {
              @Override
              public ShardHandler answer() throws Throwable {
                log.info("SHARDHANDLER");
                return shardHandlerMock;
              }
            })
        .anyTimes();
    workQueueMock.peekTopN(EasyMock.anyInt(), anyObject(Set.class), EasyMock.anyLong());
    expectLastCall()
        .andAnswer(
            new IAnswer<List>() {
              @Override
              public List answer() throws Throwable {
                Object result;
                int count = 0;
                while ((result = queue.peek()) == null) {
                  Thread.sleep(1000);
                  count++;
                  if (count > 1) return null;
                }

                return Arrays.asList(result);
              }
            })
        .anyTimes();

    workQueueMock.getTailId();
    expectLastCall()
        .andAnswer(
            new IAnswer<Object>() {
              @Override
              public Object answer() throws Throwable {
                Object result = null;
                Iterator iter = queue.iterator();
                while (iter.hasNext()) {
                  result = iter.next();
                }
                return result == null ? null : ((QueueEvent) result).getId();
              }
            })
        .anyTimes();

    workQueueMock.peek(true);
    expectLastCall()
        .andAnswer(
            new IAnswer<Object>() {
              @Override
              public Object answer() throws Throwable {
                Object result;
                while ((result = queue.peek()) == null) {
                  Thread.sleep(1000);
                }
                return result;
              }
            })
        .anyTimes();

    workQueueMock.remove(anyObject(QueueEvent.class));
    expectLastCall()
        .andAnswer(
            new IAnswer<Object>() {
              @Override
              public Object answer() throws Throwable {
                queue.remove((QueueEvent) getCurrentArguments()[0]);
                return null;
              }
            })
        .anyTimes();

    workQueueMock.poll();
    expectLastCall()
        .andAnswer(
            new IAnswer<Object>() {
              @Override
              public Object answer() throws Throwable {
                return queue.poll();
              }
            })
        .anyTimes();

    zkStateReaderMock.getClusterState();
    expectLastCall()
        .andAnswer(
            new IAnswer<Object>() {
              @Override
              public Object answer() throws Throwable {
                return clusterStateMock;
              }
            })
        .anyTimes();

    zkStateReaderMock.getZkClient();
    expectLastCall()
        .andAnswer(
            new IAnswer<Object>() {
              @Override
              public Object answer() throws Throwable {
                return solrZkClientMock;
              }
            })
        .anyTimes();

    zkStateReaderMock.updateClusterState(anyBoolean());

    clusterStateMock.getCollections();
    expectLastCall()
        .andAnswer(
            new IAnswer<Object>() {
              @Override
              public Object answer() throws Throwable {
                return collectionsSet;
              }
            })
        .anyTimes();
    final Set<String> liveNodes = new HashSet<>();
    for (int i = 0; i < liveNodesCount; i++) {
      final String address = "localhost:" + (8963 + i) + "_solr";
      liveNodes.add(address);

      zkStateReaderMock.getBaseUrlForNodeName(address);
      expectLastCall()
          .andAnswer(
              new IAnswer<Object>() {
                @Override
                public Object answer() throws Throwable {
                  // This works as long as this test does not use a
                  // webapp context with an underscore in it
                  return address.replaceAll("_", "/");
                }
              })
          .anyTimes();
    }
    zkStateReaderMock.getClusterProps();
    expectLastCall()
        .andAnswer(
            new IAnswer<Map>() {
              @Override
              public Map answer() throws Throwable {
                return new HashMap();
              }
            });

    solrZkClientMock.getZkClientTimeout();
    expectLastCall()
        .andAnswer(
            new IAnswer<Object>() {
              @Override
              public Object answer() throws Throwable {
                return 30000;
              }
            })
        .anyTimes();

    clusterStateMock.hasCollection(anyObject(String.class));
    expectLastCall()
        .andAnswer(
            new IAnswer<Boolean>() {
              @Override
              public Boolean answer() throws Throwable {
                String key = (String) getCurrentArguments()[0];
                return collectionsSet.contains(key);
              }
            })
        .anyTimes();

    clusterStateMock.getLiveNodes();
    expectLastCall()
        .andAnswer(
            new IAnswer<Object>() {
              @Override
              public Object answer() throws Throwable {
                return liveNodes;
              }
            })
        .anyTimes();
    solrZkClientMock.create(
        anyObject(String.class),
        anyObject(byte[].class),
        anyObject(CreateMode.class),
        anyBoolean());
    expectLastCall()
        .andAnswer(
            new IAnswer<String>() {
              @Override
              public String answer() throws Throwable {
                String key = (String) getCurrentArguments()[0];
                zkMap.put(key, null);
                handleCreateCollMessage((byte[]) getCurrentArguments()[1]);
                return key;
              }
            })
        .anyTimes();

    solrZkClientMock.makePath(anyObject(String.class), anyObject(byte[].class), anyBoolean());
    expectLastCall()
        .andAnswer(
            new IAnswer<String>() {
              @Override
              public String answer() throws Throwable {
                String key = (String) getCurrentArguments()[0];
                return key;
              }
            })
        .anyTimes();

    solrZkClientMock.makePath(
        anyObject(String.class),
        anyObject(byte[].class),
        anyObject(CreateMode.class),
        anyBoolean());
    expectLastCall()
        .andAnswer(
            new IAnswer<String>() {
              @Override
              public String answer() throws Throwable {
                String key = (String) getCurrentArguments()[0];
                return key;
              }
            })
        .anyTimes();

    solrZkClientMock.exists(anyObject(String.class), anyBoolean());
    expectLastCall()
        .andAnswer(
            new IAnswer<Boolean>() {
              @Override
              public Boolean answer() throws Throwable {
                String key = (String) getCurrentArguments()[0];
                return zkMap.containsKey(key);
              }
            })
        .anyTimes();

    zkMap.put("/configs/myconfig", null);

    return liveNodes;
  }