Esempio n. 1
0
 @Test(expected = InvalidObjectException.class)
 public void shouldNotDeserializeListWithSizeLessThanOne() throws Throwable {
   try {
     /*
      * This implementation is stable regarding jvm impl changes of object serialization. The index of the number
      * of List elements is gathered dynamically.
      */
     final byte[] listWithOneElement = Serializables.serialize(List.of(0));
     final byte[] listWithTwoElements = Serializables.serialize(List.of(0, 0));
     int index = -1;
     for (int i = 0; i < listWithOneElement.length && index == -1; i++) {
       final byte b1 = listWithOneElement[i];
       final byte b2 = listWithTwoElements[i];
       if (b1 != b2) {
         if (b1 != 1 || b2 != 2) {
           throw new IllegalStateException("Difference does not indicate number of elements.");
         } else {
           index = i;
         }
       }
     }
     if (index == -1) {
       throw new IllegalStateException("Hack incomplete - index not found");
     }
     /*
      * Hack the serialized data and fake zero elements.
      */
     listWithOneElement[index] = 0;
     Serializables.deserialize(listWithOneElement);
   } catch (IllegalStateException x) {
     throw (x.getCause() != null) ? x.getCause() : x;
   }
 }
Esempio n. 2
0
 @Override
 public void validate(final Environment env) throws ValidationException {
   try {
     for (final File file : env.files("*.xml")) {
       final String name = file.getAbsolutePath().substring(env.basedir().toString().length());
       if (env.exclude("xml", name)) {
         Logger.info(this, "%s: skipped", name);
         continue;
       }
       Logger.info(this, "%s: to be validated", name);
       final XML document = new XMLDocument(file);
       try {
         new StrictXML(document);
       } catch (final IllegalStateException ex) {
         if (ex.getCause() != null && ex.getCause() instanceof SAXException) {
           Logger.warn(
               // @checkstyle LineLength (1 line)
               this,
               "Failed to validate file %s against schema(s). Cause: %s",
               name,
               ex.toString());
         } else {
           throw new IllegalStateException(ex);
         }
       } catch (final IllegalArgumentException ex) {
         throw new ValidationException(ex);
       }
       if (this.format) {
         XmlValidator.formatting(file.toString(), FileUtils.readFileToString(file));
       }
     }
   } catch (final IOException ex) {
     throw new IllegalStateException(ex);
   }
 }
  @Test(dependsOnMethods = "testResolveVolumeOffering")
  public void testCreateVolume() throws Exception {
    try {
      volume =
          connection.createVolumeInLocation(
              location.getId(), TAG, FORMAT, cheapestStorage.getName(), cheapestStorage.getId());
      // wait up to 5 minutes for this to become "unmounted"
      assert new RetryablePredicate<Volume>(
              new VolumeUnmounted(connection), 300, 5, TimeUnit.SECONDS)
          .apply(volume);
    } catch (IllegalStateException e) {
      int code = HttpResponseException.class.cast(e.getCause()).getResponse().getStatusCode();
      if (code == 409 || code == 500) {
        Set<? extends Volume> volumes = connection.listVolumes();
        try {
          volume =
              Iterables.find(
                  volumes,
                  new Predicate<Volume>() {

                    @Override
                    public boolean apply(Volume input) {
                      return input.getState() == Volume.State.UNMOUNTED;
                    }
                  });
        } catch (NoSuchElementException ex) {
          killInstance(TAG + 1);
        }
      } else {
        throw e;
      }
    }
    assertEquals(volume.getInstanceId(), null);
    assertEquals(volume.getLocation(), location.getId());

    final String id = volume.getId();
    Set<? extends Volume> allVolumes = connection.listVolumes();

    // refresh volume as it may have been just created
    volume =
        Iterables.find(
            allVolumes,
            new Predicate<Volume>() {

              @Override
              public boolean apply(Volume input) {
                return input.getId().equals(id);
              }
            });

    assert (allVolumes.contains(volume)) : String.format("volume %s not in %s", volume, volume);
  }
 @Test
 public void testDestroyNonExistingCache() throws Exception {
   final TreeWalker treeWalker = new TreeWalker();
   treeWalker.configure(new DefaultConfiguration("default config"));
   treeWalker.setCacheFile("/invalid");
   try {
     treeWalker.destroy();
     // till
     if (!System.getProperty("os.name").startsWith("Windows")) {
       fail();
     }
   } catch (IllegalStateException ex) {
     assertTrue(ex.getCause() instanceof IOException);
   }
 }
  @Test(dependsOnMethods = "resolveImageAndInstanceType")
  public void testAllocateIpAddress() throws Exception {

    Offering offering =
        Iterables.find(
            connection.listAddressOfferings(),
            new Predicate<Offering>() {

              @Override
              public boolean apply(Offering arg0) {
                return arg0.getLocation().equals(location.getId());
              }
            });

    try {
      ip = connection.allocateAddressInLocation(location.getId(), offering.getId());
      System.out.println(ip);
      assertEquals(ip.getIp(), null);
      // wait up to 30 seconds for this to become "free"
      new RetryablePredicate<Address>(new AddressFree(connection), 30, 2, TimeUnit.SECONDS)
          .apply(ip);
      refreshIpAndReturnAllAddresses();
      assertEquals(ip.getInstanceId(), null);
    } catch (IllegalStateException e) {
      if (HttpResponseException.class.cast(e.getCause()).getResponse().getStatusCode() == 409) {
        ip =
            Iterables.find(
                connection.listAddresses(),
                new Predicate<Address>() {

                  @Override
                  public boolean apply(Address input) {
                    return input.getState() == Address.State.FREE;
                  }
                });
      } else {
        throw e;
      }
    }
    assertEquals(ip.getInstanceId(), null);
    assertEquals(ip.getLocation(), location.getId());

    Set<? extends Address> allAddresses = refreshIpAndReturnAllAddresses();

    assert (allAddresses.contains(ip)) : String.format("ip %s not in %s", ip, allAddresses);
  }
  public void testHandleServiceVersionMismatchThrowsRuntimeException() throws Exception {
    DummyService service = createDummyService();

    service.callCheckServiceVersion(1, 0, null);
    service.checkHandleServiceVersionMismatchInvoked(false);
    RuntimeException rte = new RuntimeException();
    try {
      service.callCheckServiceVersion(1, 1, rte);
    } catch (IllegalStateException e) {
      System.err.println(e);
      if (e.getCause() != rte) {
        fail("expected cause to be original exception");
      }
    } catch (Exception e) {
      System.err.println(e);
      fail("expected IllegalStateException");
    }

    service.checkHandleServiceVersionMismatchInvoked(true);
  }
  protected void error(HttpServletRequest req, HttpServletResponse res, Exception excp)
      throws ServletException {

    Throwable t = excp;
    if (excp instanceof MethodInvocationException)
      t = ((MethodInvocationException) excp).getWrappedThrowable();

    try {
      if (t instanceof ResourceNotFoundException) {
        LOG.error(t.getMessage() + "(" + req.getRequestURL().toString() + ")");
        if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_NOT_FOUND);
      } else {
        StringBuilder log = new StringBuilder("ERROR:Unknown Velocity Error,url=");
        log.append(req.getRequestURL());
        if (req.getQueryString() != null) {
          log.append('?');
          log.append(req.getQueryString());
        }
        log.append('(');
        log.append(new Date());
        log.append(')');
        LOG.error(log.toString(), t);
        log = null;
        req.setAttribute("javax.servlet.jsp.jspException", t);
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      }

    } catch (IOException e) {
      LOG.error("Exception occured in VelocityServlet.error", e);
      throw new ServletException(e);

    } catch (IllegalStateException e) {
      LOG.error("==============<<IllegalStateException>>==============", e.getCause());
      throw new ServletException(e);
    }
    return;
  }