@Test
  public void readWithTimeoutSerialPortTest() throws IOException, InterruptedException {
    int streamDelayTooLong = 200;
    int streamDelayOk = 5;
    int timeout = 100;
    int cpuDelay = 10;

    SerialCommunicationsPort serial = org.mockito.Mockito.mock(SerialCommunicationsPort.class);
    byte[] bytes = "j".getBytes();
    byte[] bytes2 = "k".getBytes();
    Mockito.when(serial.read())
        .thenAnswer(new SerialPortReadDelayedAnswer(streamDelayTooLong, null))
        .thenAnswer(new SerialPortReadDelayedAnswer(streamDelayTooLong, bytes))
        .thenAnswer(new SerialPortReadDelayedAnswer(streamDelayTooLong, null))
        .thenAnswer(new SerialPortReadDelayedAnswer(streamDelayOk, bytes2))
        .thenAnswer(new SerialPortReadDelayedAnswer(streamDelayOk, null));

    String data = IOUtilities.readWithTimeout(serial, timeout, cpuDelay);
    Assert.assertEquals("", data);

    data = IOUtilities.readWithTimeout(serial, timeout, cpuDelay);
    Assert.assertEquals("j", data);

    data = IOUtilities.readWithTimeout(serial, timeout, cpuDelay);
    Assert.assertEquals("k", data);
  }
  @Test
  public void readWithTimeoutInputStreamTest() throws IOException, InterruptedException {
    int streamDelayTooLong = 200;
    int streamDelayOk = 5;
    int timeout = 100;
    int cpuDelay = 10;

    InputStream stream = org.mockito.Mockito.mock(InputStream.class);
    byte[] bytes = "hello".getBytes();
    byte[] bytes2 = "worlds".getBytes();
    byte[] checkBytes = new byte[bytes.length];
    byte[] checkBytes2 = new byte[bytes2.length];

    Mockito.when(stream.available())
        .thenReturn(0)
        .thenReturn(bytes.length)
        .thenReturn(bytes2.length)
        .thenReturn(0);
    Mockito.when(
            stream.read(
                Mockito.any(byte[].class), Mockito.any(Integer.class), Mockito.any(Integer.class)))
        .thenAnswer(new InputStreamReadDelayedAnswer(streamDelayTooLong, new byte[0]))
        .thenAnswer(new InputStreamReadDelayedAnswer(streamDelayTooLong, bytes))
        .thenAnswer(new InputStreamReadDelayedAnswer(streamDelayOk, bytes2));

    int dataRead = IOUtilities.readWithTimeout(stream, checkBytes, timeout, cpuDelay);
    Assert.assertEquals(0, dataRead);

    dataRead = IOUtilities.readWithTimeout(stream, checkBytes, timeout, cpuDelay);
    Assert.assertEquals(bytes.length, dataRead);
    Assert.assertArrayEquals(bytes, checkBytes);

    dataRead = IOUtilities.readWithTimeout(stream, checkBytes2, timeout, cpuDelay);
    Assert.assertArrayEquals(bytes2, checkBytes2);
  }
Exemple #3
0
  /**
   * Get content from the passed in URL. This code will open a connection to the passed in server,
   * fetch the requested content, and return it as a byte[].
   *
   * @param url URL to hit
   * @param inCookies Map of session cookies (or null if not needed)
   * @param outCookies Map of session cookies (or null if not needed)
   * @param allowAllCerts override certificate validation?
   * @return byte[] of content fetched from URL.
   */
  public static byte[] getContentFromUrl(
      URL url, Map inCookies, Map outCookies, boolean allowAllCerts) {
    URLConnection c = null;
    try {
      c = getConnection(url, inCookies, true, false, false, allowAllCerts);

      ByteArrayOutputStream out = new ByteArrayOutputStream(16384);
      InputStream stream = IOUtilities.getInputStream(c);
      IOUtilities.transfer(stream, out);
      stream.close();

      if (outCookies
          != null) { // [optional] Fetch cookies from server and update outCookie Map (pick up
        // JSESSIONID, other headers)
        getCookies(c, outCookies);
      }

      return out.toByteArray();
    } catch (
        SSLHandshakeException
            e) { // Don't read error response.  it will just cause another exception.
      LOG.warn("SSL Exception occurred fetching content from url: " + url, e);
      return null;
    } catch (Exception e) {
      readErrorResponse(c);
      LOG.warn("Exception occurred fetching content from url: " + url, e);
      return null;
    } finally {
      if (c instanceof HttpURLConnection) {
        disconnect((HttpURLConnection) c);
      }
    }
  }
  @Test
  public void inputStreamSplitReadLineTest() throws IOException {
    int streamDelayTooLong = 100;
    int timeout = 50;
    int cpuDelay = 10;

    StringBuilder builder = new StringBuilder();
    InputStream stream = org.mockito.Mockito.mock(InputStream.class);
    byte[] bytes = "o".getBytes();
    byte[] bytes2 = "k\nwo".getBytes();
    byte[] bytes3 = "rl".getBytes();
    byte[] bytes4 = "d\n".getBytes();
    Mockito.when(stream.available())
        .thenReturn(bytes.length)
        .thenReturn(bytes.length)
        .thenReturn(bytes2.length)
        .thenReturn(bytes2.length)
        .thenReturn(bytes3.length)
        .thenReturn(bytes3.length)
        .thenReturn(bytes4.length)
        .thenReturn(bytes4.length)
        .thenReturn(0);
    Mockito.when(
            stream.read(
                Mockito.any(byte[].class), Mockito.any(Integer.class), Mockito.any(Integer.class)))
        .thenAnswer(new InputStreamReadDelayedAnswer(streamDelayTooLong, bytes))
        .thenAnswer(new InputStreamReadDelayedAnswer(streamDelayTooLong, bytes2))
        .thenAnswer(new InputStreamReadDelayedAnswer(streamDelayTooLong, bytes3))
        .thenAnswer(new InputStreamReadDelayedAnswer(streamDelayTooLong, bytes4))
        .thenThrow(
            new IllegalArgumentException(
                "The read method should never have been called this time."));

    // This tests that an inputstream read wasn't able to complete a full line read in the given
    // timeout period.
    ParseState state = IOUtilities.readLine(stream, builder, "[\n]", 0, timeout, cpuDelay);
    Assert.assertEquals(1, state.parseLocation);
    Assert.assertEquals(null, state.currentLine);

    // The next read should be able to read the the ok
    state = IOUtilities.readLine(stream, builder, "[\n]", state.parseLocation, timeout, cpuDelay);
    Assert.assertEquals(0, state.parseLocation);
    Assert.assertEquals("ok\n", state.currentLine);

    // Again, this read won't be able to read the full amount of data in the timeout period.
    state = IOUtilities.readLine(stream, builder, "[\n]", state.parseLocation, timeout, cpuDelay);
    Assert.assertEquals(4, state.parseLocation);
    Assert.assertEquals(null, state.currentLine);

    // There is nothing left on the stream to read so it continues to parse the rest of the
    // StringBuilder
    state = IOUtilities.readLine(stream, builder, "[\n]", state.parseLocation, timeout, 10);
    Assert.assertEquals(0, state.parseLocation);
    Assert.assertEquals("world\n", state.currentLine);
  }
  @Test
  @PrepareForTest(IOUtilities.class)
  public void testNativeCommandCommunication() throws IOException {
    mockRuntime(LinuxNetworkManagerTest.SCAN_WIFI_DATA);

    List<ParseAction> actions = new ArrayList<ParseAction>();
    actions.add(
        new ParseAction(
            new String[] {"/bin/sh", "-c", "wpa_cli -i {0}"}, ">", SearchStyle.RepeatUntilFound));
    actions.add(
        new ParseAction(
            new String[] {"scan\n"},
            "[\\r\\s]*<\\d+>\\s*CTRL-EVENT-SCAN-RESULTS",
            SearchStyle.RepeatUntilFound));
    actions.add(new ParseAction(new String[] {""}, "\\s*>", SearchStyle.RepeatUntilFound));
    actions.add(
        new ParseAction(new String[] {"scan_results\n"}, "bssid.*", SearchStyle.RepeatUntilFound));
    actions.add(
        new ParseAction(
            new String[] {""},
            "\\s*([A-Fa-f0-9:]+)\\s+(\\d+)\\s+(\\d+)\\s+([\\[\\]\\+\\-\\w]+)\\s+(\\w*)\\s*",
            SearchStyle.RepeatWhileFound));

    List<String[]> dataReturned =
        IOUtilities.communicateWithNativeCommand(actions, "^>|\n", true, null, "wlan0");
    Assert.assertEquals("SomeNetwork", dataReturned.get(0)[4]);
    Assert.assertEquals("CenturyLink9999", dataReturned.get(1)[4]);
    Assert.assertEquals("SomeHouse", dataReturned.get(2)[4]);
  }
Exemple #6
0
 public static void readErrorResponse(URLConnection c) {
   if (c == null) {
     return;
   }
   InputStream in = null;
   try {
     int error = ((HttpURLConnection) c).getResponseCode();
     in = ((HttpURLConnection) c).getErrorStream();
     if (in == null) {
       return;
     }
     LOG.warn("HTTP error response: " + ((HttpURLConnection) c).getResponseMessage());
     // read the response body
     ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
     int count;
     byte[] bytes = new byte[8192];
     while ((count = in.read(bytes)) != -1) {
       out.write(bytes, 0, count);
     }
     LOG.warn("HTTP error Code:  " + error);
   } catch (ConnectException e) {
     LOG.error("Connection exception trying to read HTTP error response", e);
   } catch (IOException e) {
     LOG.error("IO Exception trying to read HTTP error response", e);
   } catch (Exception e) {
     LOG.error("Exception trying to read HTTP error response", e);
   } finally {
     IOUtilities.close(in);
   }
 }
  @Test
  public void serialPortSplitReadLineTest() throws IOException {
    int streamDelayTooLong = 100;
    int timeout = 50;
    int cpuDelay = 10;

    StringBuilder builder = new StringBuilder();
    SerialCommunicationsPort serial = org.mockito.Mockito.mock(SerialCommunicationsPort.class);
    Printer printer = org.mockito.Mockito.mock(Printer.class);
    byte[] bytes = "o".getBytes();
    byte[] bytes2 = "k\nwo".getBytes();
    byte[] bytes3 = "rl".getBytes();
    byte[] bytes4 = "d\n".getBytes();
    Mockito.when(serial.read())
        .thenAnswer(new SerialPortReadDelayedAnswer(streamDelayTooLong, bytes))
        .thenAnswer(new SerialPortReadDelayedAnswer(streamDelayTooLong, bytes2))
        .thenAnswer(new SerialPortReadDelayedAnswer(streamDelayTooLong, bytes3))
        .thenAnswer(new SerialPortReadDelayedAnswer(streamDelayTooLong, bytes4))
        .thenThrow(
            new IllegalArgumentException(
                "The read method should never have been called this time."));

    // This tests that an inputstream read wasn't able to complete a full line read in the given
    // timeout period.
    ParseState state = IOUtilities.readLine(printer, serial, builder, 0, timeout, cpuDelay);
    Assert.assertEquals(1, state.parseLocation);
    Assert.assertEquals(null, state.currentLine);

    // The next read should be able to read the the ok
    state = IOUtilities.readLine(printer, serial, builder, state.parseLocation, timeout, cpuDelay);
    Assert.assertEquals(0, state.parseLocation);
    Assert.assertEquals("ok\n", state.currentLine);

    // Again, this read won't be able to read the full amount of data in the timeout period.
    state = IOUtilities.readLine(printer, serial, builder, state.parseLocation, timeout, cpuDelay);
    Assert.assertEquals(4, state.parseLocation);
    Assert.assertEquals(null, state.currentLine);

    // There is nothing left on the stream to read so it continues to parse the rest of the
    // StringBuilder
    state = IOUtilities.readLine(printer, serial, builder, state.parseLocation, timeout, cpuDelay);
    Assert.assertEquals(0, state.parseLocation);
    Assert.assertEquals("world\n", state.currentLine);
  }
Exemple #8
0
 /** Still used in getNCubesFromResource */
 private static Object[] getJsonObjectFromResource(String name) throws IOException {
   JsonReader reader = null;
   try {
     URL url = NCubeManager.class.getResource("/" + name);
     File jsonFile = new File(url.getFile());
     InputStream in = new BufferedInputStream(new FileInputStream(jsonFile));
     reader = new JsonReader(in, true);
     return (Object[]) reader.readObject();
   } finally {
     IOUtilities.close(reader);
   }
 }
  private void testSingleLine(String line, StringBuilder builder, InputStream stream)
      throws IOException {
    int cpuDelay = 10;
    byte[] firstBytes = line.getBytes();
    Mockito.when(stream.available()).thenReturn(firstBytes.length).thenReturn(firstBytes.length);
    Mockito.when(
            stream.read(Mockito.any(byte[].class), Mockito.eq(0), Mockito.eq(firstBytes.length)))
        .thenAnswer(new InputStreamReadDelayedAnswer(0, firstBytes));

    ParseState state = IOUtilities.readLine(stream, builder, "[\n]", 0, 0, cpuDelay);

    Assert.assertEquals(0, state.parseLocation);
    Assert.assertEquals(line, state.currentLine);
  }
  @Test
  @PrepareForTest(IOUtilities.class)
  public void testNativeCommandExecution() throws IOException {
    String[] directories = new String[] {"Directory 1", "Directory2", "Final Directory"};
    StringBuilder builder = new StringBuilder();
    for (String directory : directories) {
      builder.append(directory);
      builder.append("\n");
    }

    mockRuntime(builder.toString());
    String[] returnedDirectories =
        IOUtilities.executeNativeCommand(new String[] {"ls {0}"}, null, "stuff");
    Assert.assertArrayEquals(directories, returnedDirectories);
  }
  public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
    int retry = _strategy.getRetryAttempts();
    Object result = null;
    do {
      HttpURLConnection c = null;
      try {
        c =
            (HttpURLConnection)
                UrlUtilities.getConnection(_strategy.buildURL(proxy, m, args), true, true, false);
        c.setRequestMethod("POST");

        _strategy.setCookies(c);

        // Formulate the POST data for the output stream.
        byte[] bytes = _strategy.generatePostData(proxy, m, args);
        c.setRequestProperty("Content-Length", String.valueOf(bytes.length));

        _strategy.setRequestHeaders(c);

        // send the post data
        IOUtilities.transfer(c, bytes);

        _strategy.getCookies(c);

        // Get the return value of the call
        result = _strategy.readResponse(c);
      } catch (ThreadDeath e) {
        throw e;
      } catch (Throwable e) {
        LOG.error("Error occurred getting HTTP response from server", e);
        UrlUtilities.readErrorResponse(c);
        if (retry-- > 0) {
          Thread.sleep(_strategy.getRetrySleepTime());
        }
      } finally {
        UrlUtilities.disconnect(c);
      }
    } while (retry > 0);

    try {
      checkForThrowable(result);
    } catch (Throwable t) {
      LOG.error("Error occurred on server", t);
      return null;
    }
    return result;
  }