Пример #1
0
  public void testGranularity() {

    Scheduler s = new Scheduler();

    // This should be fine
    s.setScheduleGranularity(1);

    try {

      // but this is not
      s.setScheduleGranularity(0);

    } catch (IllegalArgumentException ex) {
      assertEquals("Wrong exception message", "0: value doesn't make sense", ex.getMessage());
    }

    long value = -1 * Math.abs(rg.nextLong());

    try {
      // and neither is this
      s.setScheduleGranularity(value);

    } catch (IllegalArgumentException ex) {
      assertEquals(
          "Wrong exception message", value + ": value doesn't make sense", ex.getMessage());
    }
  }
Пример #2
0
  void test(List<String> opts, Main.Result expectResult, Set<Message> expectMessages) {
    System.err.println("test: " + opts);
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    try {
      DocumentationTask t = javadoc.getTask(pw, fm, null, null, opts, files);
      boolean ok = t.call();
      pw.close();
      String out = sw.toString().replaceAll("[\r\n]+", "\n");
      if (!out.isEmpty()) System.err.println(out);
      if (ok && expectResult != Main.Result.OK) {
        error("Compilation succeeded unexpectedly");
      } else if (!ok && expectResult != Main.Result.ERROR) {
        error("Compilation failed unexpectedly");
      } else check(out, expectMessages);
    } catch (IllegalArgumentException e) {
      System.err.println(e);
      String expectOut = expectMessages.iterator().next().text;
      if (expectResult != Main.Result.CMDERR) error("unexpected exception caught");
      else if (!e.getMessage().equals(expectOut)) {
        error("unexpected exception message: " + e.getMessage() + " expected: " + expectOut);
      }
    }

    //        if (errors > 0)
    //            throw new Error("stop");
  }
Пример #3
0
  public void testBadSequenceKeys() throws DatabaseException {

    open();
    try {
      PrimaryIndex<Boolean, BadSequenceKeyEntity1> index =
          store.getPrimaryIndex(Boolean.class, BadSequenceKeyEntity1.class);
      fail();
    } catch (IllegalArgumentException expected) {
      assertTrue(expected.getMessage().indexOf("Type not allowed for sequence") >= 0);
    }
    try {
      PrimaryIndex<BadSequenceKeyEntity2.Key, BadSequenceKeyEntity2> index =
          store.getPrimaryIndex(BadSequenceKeyEntity2.Key.class, BadSequenceKeyEntity2.class);
      fail();
    } catch (IllegalArgumentException expected) {
      assertTrue(expected.getMessage().indexOf("Type not allowed for sequence") >= 0);
    }
    try {
      PrimaryIndex<BadSequenceKeyEntity3.Key, BadSequenceKeyEntity3> index =
          store.getPrimaryIndex(BadSequenceKeyEntity3.Key.class, BadSequenceKeyEntity3.class);
      fail();
    } catch (IllegalArgumentException expected) {
      assertTrue(
          expected
                  .getMessage()
                  .indexOf(
                      "A composite key class used with a sequence may contain "
                          + "only a single integer key field")
              >= 0);
    }
    close();
  }
Пример #4
0
      @Override
      public void actionPerformed(ActionEvent evt) {
        final AddImageryPanel p;
        switch (type) {
          case WMS:
            p = new AddWMSLayerPanel();
            break;
          case TMS:
            p = new AddTMSLayerPanel();
            break;
          case WMTS:
            p = new AddWMTSLayerPanel();
            break;
          default:
            throw new IllegalStateException("Type " + type + " not supported");
        }

        final AddImageryDialog addDialog = new AddImageryDialog(gui, p);
        addDialog.showDialog();

        if (addDialog.getValue() == 1) {
          try {
            activeModel.addRow(p.getImageryInfo());
          } catch (IllegalArgumentException ex) {
            if (ex.getMessage() == null || ex.getMessage().isEmpty()) throw ex;
            else {
              JOptionPane.showMessageDialog(
                  Main.parent, ex.getMessage(), tr("Error"), JOptionPane.ERROR_MESSAGE);
            }
          }
        }
      }
  public void testInvalidConstructorArgs() {
    try {
      new LineStringBuilder((List<Coordinate>) null);
      fail("Exception expected");
    } catch (IllegalArgumentException e) {
      assertThat(
          "cannot create point collection with empty set of points", equalTo(e.getMessage()));
    }

    try {
      new LineStringBuilder(new CoordinatesBuilder());
      fail("Exception expected");
    } catch (IllegalArgumentException e) {
      assertThat(
          "cannot create point collection with empty set of points", equalTo(e.getMessage()));
    }

    try {
      new LineStringBuilder(new CoordinatesBuilder().coordinate(0.0, 0.0));
      fail("Exception expected");
    } catch (IllegalArgumentException e) {
      assertThat(
          "invalid number of points in LineString (found [1] - must be >= 2)",
          equalTo(e.getMessage()));
    }
  }
Пример #6
0
  /**
   * the trainer works with the catalog
   *
   * @param trainer
   */
  private static void work(Trainer trainer) {
    trainer.addGrade("florin", 10);
    trainer.addGrade("florin", 9);

    try {
      trainer.addGrade("dana", 4);
    } catch (IllegalArgumentException e) {
      System.out.println(e.getMessage());
    }

    trainer.addGrade("radu", 9);
    trainer.addGrade("radu", 10);

    trainer.addGrade("andrei", 9);
    trainer.addGrade("florin", 9);

    try {
      trainer.addGrade("florin", 11);
    } catch (IllegalArgumentException e) {
      System.out.println(e.getMessage());
    }

    trainer.addGrade("ciprian", 8);
    trainer.addGrade("ciprian", 9);

    trainer.printGrades("radu");

    trainer.addGrade("radu", 10);
    trainer.printCatalog();
  }
Пример #7
0
  @Override
  public void run() {
    Utility.showProgressDialog(
        progressDialog, handler, context.getString(R.string.subscribe_progress_dialog_message));

    try {
      Utility.isConnectingToInternet(context);
      subscribeToChannel(channel);
      adapter.addItem(channel);
      Log.d(TAG, String.format("Subscribed to %s successfully", channel));
      Utility.showToast(context, handler, context.getString(R.string.subscribe_successfully));
    } catch (IllegalArgumentException e) {
      Utility.showToast(context, handler, e.getMessage());
      Log.e(TAG, e.getMessage());
    } catch (IOException e) {
      Utility.showToast(context, handler, e.getMessage());
      Log.e(TAG, e.getMessage());
    } catch (InterruptedException e) {
      Utility.showToast(context, handler, e.getMessage());
      Log.e(TAG, e.getMessage());
    } catch (IllegalAccessError e) {
      Utility.showToast(context, handler, e.getMessage());
      Log.e(TAG, e.getMessage());
    }

    Utility.dissmissProgressDialog(progressDialog, handler);
  }
 public void testSpecialTribeSetting() {
   {
     Settings settings = Settings.builder().put("tribe.blocks.write", "false").build();
     SettingsModule module = new SettingsModule(settings);
     assertInstanceBinding(module, Settings.class, (s) -> s == settings);
   }
   {
     Settings settings = Settings.builder().put("tribe.blocks.write", "BOOM").build();
     try {
       new SettingsModule(settings);
       fail();
     } catch (IllegalArgumentException ex) {
       assertEquals(
           "Failed to parse value [BOOM] cannot be parsed to boolean [ true/1/on/yes OR false/0/off/no ]",
           ex.getMessage());
     }
   }
   {
     Settings settings = Settings.builder().put("tribe.blocks.wtf", "BOOM").build();
     try {
       new SettingsModule(settings);
       fail();
     } catch (IllegalArgumentException ex) {
       assertEquals(
           "tribe.blocks validation failed: unknown setting [wtf] please check that any required plugins are"
               + " installed, or check the breaking changes documentation for removed settings",
           ex.getMessage());
     }
   }
 }
  public void testMutuallyExclusiveScopes() {
    new SettingsModule(Settings.EMPTY, Setting.simpleString("foo.bar", Property.NodeScope));
    new SettingsModule(Settings.EMPTY, Setting.simpleString("index.foo.bar", Property.IndexScope));

    // Those should fail
    try {
      new SettingsModule(Settings.EMPTY, Setting.simpleString("foo.bar"));
      fail("No scope should fail");
    } catch (IllegalArgumentException e) {
      assertThat(e.getMessage(), containsString("No scope found for setting"));
    }
    // Some settings have both scopes - that's fine too if they have per-node defaults
    try {
      new SettingsModule(
          Settings.EMPTY,
          Setting.simpleString("foo.bar", Property.IndexScope, Property.NodeScope),
          Setting.simpleString("foo.bar", Property.NodeScope));
      fail("already registered");
    } catch (IllegalArgumentException e) {
      assertThat(e.getMessage(), containsString("Cannot register setting [foo.bar] twice"));
    }

    try {
      new SettingsModule(
          Settings.EMPTY,
          Setting.simpleString("foo.bar", Property.IndexScope, Property.NodeScope),
          Setting.simpleString("foo.bar", Property.IndexScope));
      fail("already registered");
    } catch (IllegalArgumentException e) {
      assertThat(e.getMessage(), containsString("Cannot register setting [foo.bar] twice"));
    }
  }
  private void somethingIsWrongWithGenerateHash() {
    String randomString = "";
    int randomLength = (int) (Math.random() * 40);
    for (int i = 0; i < randomLength; i++) {
      randomString += (char) (Math.random() * Character.MAX_VALUE);
    }

    try {
      stringSearching.generateHash(null, 0);
      fail("Null character sequence did not throw exception.");
    } catch (IllegalArgumentException e) {
      assertNotNull("IllegalArgumentException needs a message", e.getMessage());
      assertTrue("Make sure the message is useful.", e.getMessage().length() > 10);
    }

    try {
      stringSearching.generateHash(randomString, (int) (Math.random() * Integer.MIN_VALUE));
      fail("Negative length did not throw exception.");
    } catch (IllegalArgumentException e) {
      assertNotNull("IllegalArgumentException needs a message!", e.getMessage());
      assertTrue("Make sure the message is useful.", e.getMessage().length() > 10);
    }

    try {
      stringSearching.generateHash(randomString, randomLength + (int) (Math.random() * 5));
      fail("length greater than randomString.length() did not throw" + "Exception");
    } catch (IllegalArgumentException e) {
      assertNotNull("IllegalArgumentException needs a message!");
      assertTrue("Make sure the message is useful.", e.getMessage().length() > 10);
    }
  }
Пример #11
0
 @ExceptionHandler(IllegalArgumentException.class)
 @ResponseStatus(HttpStatus.BAD_REQUEST)
 @ResponseBody
 public Map<String, String> handleIllegalArgument(IllegalArgumentException e) {
   LOG.warn("Bad Request: " + e.getMessage(), e);
   return Collections.singletonMap("message", e.getMessage());
 }
 @Test
 public void testThrowMessageForMessageOnViolation() throws Exception {
   final ParametersPassesExpression annotation =
       proxyAnnotation(
           ParametersPassesExpression.class,
           "value",
           "myExpression",
           "messageOnViolation",
           "My message - ${#expression}");
   final MethodCall<ParametersPassesExpressionUnitTest> methodCall =
       toMethodCall(ParametersPassesExpressionUnitTest.class, this, "test", "a", 1, "b", 2);
   try {
     new Evaluator().throwMessageFor(annotation, methodCall, null);
     fail("Exception missing");
   } catch (IllegalArgumentException e) {
     assertThat(e.getMessage(), is("My message - " + annotation.value()));
     assertThat(e.getCause(), nullValue());
   }
   final Throwable cause = new Throwable("myCause");
   try {
     new Evaluator().throwMessageFor(annotation, methodCall, cause);
     fail("Exception missing");
   } catch (IllegalArgumentException e) {
     assertThat(e.getMessage(), is("My message - " + annotation.value()));
     assertThat(e.getCause(), is(cause));
   }
 }
Пример #13
0
  public static List<Selection<?>> createFieldsSelect(
      Root<?> r, QueryParameters q, String idField) {

    List<Selection<?>> fields =
        q.getFields()
            .stream()
            .map(
                f -> {
                  try {
                    return r.get(f).alias(f);
                  } catch (IllegalArgumentException e) {

                    throw new NoSuchEntityFieldException(
                        e.getMessage(), f, r.getJavaType().getSimpleName());
                  }
                })
            .collect(Collectors.toList());

    try {
      fields.add(r.get(idField).alias(idField));
    } catch (IllegalArgumentException e) {

      throw new NoSuchEntityFieldException(
          e.getMessage(), idField, r.getJavaType().getSimpleName());
    }

    return fields.stream().distinct().collect(Collectors.toList());
  }
 private void startReceivingLocationUpdates() {
   if (mLocationManager == null) {
     mLocationManager =
         (android.location.LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
   }
   if (mLocationManager != null) {
     try {
       mLocationManager.requestLocationUpdates(
           android.location.LocationManager.NETWORK_PROVIDER, 1000, 0F, mLocationListeners[1]);
     } catch (SecurityException ex) {
       Log.i(TAG, "fail to request location update, ignore", ex);
     } catch (IllegalArgumentException ex) {
       Log.d(TAG, "provider does not exist " + ex.getMessage());
     }
     try {
       mLocationManager.requestLocationUpdates(
           android.location.LocationManager.GPS_PROVIDER, 1000, 0F, mLocationListeners[0]);
     } catch (SecurityException ex) {
       Log.i(TAG, "fail to request location update, ignore", ex);
     } catch (IllegalArgumentException ex) {
       Log.d(TAG, "provider does not exist " + ex.getMessage());
     }
     Log.d(TAG, "startReceivingLocationUpdates");
   }
 }
Пример #15
0
  @SmallTest
  @Feature({"Cronet"})
  public void testInvalidLoadState() throws Exception {
    try {
      Status.convertLoadState(LoadState.WAITING_FOR_APPCACHE);
      fail();
    } catch (IllegalArgumentException e) {
      // Expected because LoadState.WAITING_FOR_APPCACHE is not mapped.
    }

    try {
      Status.convertLoadState(-1);
      fail();
    } catch (AssertionError e) {
      // Expected.
    } catch (IllegalArgumentException e) {
      // If assertions are disabled, an IllegalArgumentException should be thrown.
      assertEquals("No request status found.", e.getMessage());
    }

    try {
      Status.convertLoadState(16);
      fail();
    } catch (AssertionError e) {
      // Expected.
    } catch (IllegalArgumentException e) {
      // If assertions are disabled, an IllegalArgumentException should be thrown.
      assertEquals("No request status found.", e.getMessage());
    }
  }
  public void test_assertFileArgumentExist() throws Exception {
    String[] twoArgs =
        new String[] {
          "-srcDir",
          PathUtil.findSrcDirectory(CommandLineArgumentsTest.class).getPath(),
          "-notReallyAFile",
          "chuipasunfichier"
        };
    CommandLineArguments arguments = new CommandLineArguments(twoArgs);

    arguments.assertFileArgument("srcDir");

    try {
      arguments.assertFileArgument("notReallyAFile");
      fail();
    } catch (IllegalArgumentException ex) {
      assertEquals(
          "L'argument 'notReallyAFile' (chuipasunfichier) n'est pas un fichier accessible.",
          ex.getMessage());
    }
    try {
      arguments.assertFileArgument("unknwonArg");
      fail();
    } catch (IllegalArgumentException ex1) {
      assertEquals("L'argument obligatoire 'unknwonArg' est absent.", ex1.getMessage());
    }
  }
Пример #17
0
  @Test
  public void testOnlyOneKindOfFilterSupported() throws Exception {
    IntColumn foo = intColumn("foo");
    FilterPredicate p = or(eq(foo, 10), eq(foo, 11));

    Job job = new Job();

    Configuration conf = job.getConfiguration();
    ParquetInputFormat.setUnboundRecordFilter(job, DummyUnboundRecordFilter.class);
    try {
      ParquetInputFormat.setFilterPredicate(conf, p);
      fail("this should throw");
    } catch (IllegalArgumentException e) {
      assertEquals(
          "You cannot provide a FilterPredicate after providing an UnboundRecordFilter",
          e.getMessage());
    }

    job = new Job();
    conf = job.getConfiguration();

    ParquetInputFormat.setFilterPredicate(conf, p);
    try {
      ParquetInputFormat.setUnboundRecordFilter(job, DummyUnboundRecordFilter.class);
      fail("this should throw");
    } catch (IllegalArgumentException e) {
      assertEquals(
          "You cannot provide an UnboundRecordFilter after providing a FilterPredicate",
          e.getMessage());
    }
  }
  @Test
  public void testReservedChars() throws Exception {
    CharsRefBuilder charsRefBuilder = new CharsRefBuilder();
    charsRefBuilder.append("sugg");
    charsRefBuilder.setCharAt(2, (char) CompletionAnalyzer.SEP_LABEL);
    try {
      new SuggestField("name", charsRefBuilder.toString(), 1);
      fail(
          "no exception thrown for suggestion value containing SEP_LABEL:"
              + CompletionAnalyzer.SEP_LABEL);
    } catch (IllegalArgumentException e) {
      assertTrue(e.getMessage().contains("[0x1f]"));
    }

    charsRefBuilder.setCharAt(2, (char) CompletionAnalyzer.HOLE_CHARACTER);
    try {
      new SuggestField("name", charsRefBuilder.toString(), 1);
      fail(
          "no exception thrown for suggestion value containing HOLE_CHARACTER:"
              + CompletionAnalyzer.HOLE_CHARACTER);
    } catch (IllegalArgumentException e) {
      assertTrue(e.getMessage().contains("[0x1e]"));
    }

    charsRefBuilder.setCharAt(2, (char) NRTSuggesterBuilder.END_BYTE);
    try {
      new SuggestField("name", charsRefBuilder.toString(), 1);
      fail(
          "no exception thrown for suggestion value containing END_BYTE:"
              + NRTSuggesterBuilder.END_BYTE);
    } catch (IllegalArgumentException e) {
      assertTrue(e.getMessage().contains("[0x0]"));
    }
  }
Пример #19
0
 /** Test the hexadecimal string representation of the host data with maximum. */
 public void testToHexStringWithMax() {
   assertTrue(null == HostData.toHexString(null, 100));
   try {
     assertTrue(null == HostData.toHexString(new byte[0], 5, 10, 100));
     fail("Length error not detected");
   } catch (IllegalArgumentException e) {
     assertEquals("Invalid start or length parameter", e.getMessage());
   }
   try {
     assertEquals("0001", HostData.toHexString(new byte[] {0x00, 0x01}, 1));
     fail("Length error not detected");
   } catch (IllegalArgumentException e) {
     assertEquals("maxBytes cannot be smaller than 2", e.getMessage());
   }
   assertEquals("0001", HostData.toHexString(new byte[] {0x00, 0x01}, 2));
   assertEquals("0001", HostData.toHexString(new byte[] {0x00, 0x01}, 3));
   assertEquals("00....02", HostData.toHexString(new byte[] {0x00, 0x01, 0x02}, 2));
   assertEquals("00....03", HostData.toHexString(new byte[] {0x00, 0x01, 0x02, 0x03}, 2));
   assertEquals("00....03", HostData.toHexString(new byte[] {0x00, 0x01, 0x02, 0x03}, 3));
   assertEquals("00010203", HostData.toHexString(new byte[] {0x00, 0x01, 0x02, 0x03}, 4));
   assertEquals(
       "00....04", HostData.toHexString(new byte[] {0x00, 0x01, 0x02, 0x03, 0x04}, 0, 5, 2));
   assertEquals(
       "00....03", HostData.toHexString(new byte[] {0x00, 0x01, 0x02, 0x03, 0x04}, 0, 4, 2));
   assertEquals(
       "01....04", HostData.toHexString(new byte[] {0x00, 0x01, 0x02, 0x03, 0x04}, 1, 4, 2));
   assertEquals(
       "01020304", HostData.toHexString(new byte[] {0x00, 0x01, 0x02, 0x03, 0x04}, 1, 4, 4));
 }
Пример #20
0
  @Test
  public void testMemoryUse() throws Exception {
    // Given
    Setting<Long> memUse = setting("mySetting", new Settings.DirectMemoryUsage(1024, 100), "5%");

    // When && Then
    assertThat(memUse.apply(Functions.<String, String>constant(null)), equalTo(51l));
    assertThat(memUse.apply(Functions.<String, String>constant("35M")), equalTo(95l));
    assertThat(memUse.apply(Functions.<String, String>constant("85%")), equalTo(95l));

    try {
      memUse.apply(Functions.<String, String>constant("bala%"));
      fail("Should've thrown.");
    } catch (IllegalArgumentException e) {
      assertThat(
          e.getMessage(),
          equalTo(
              "Bad value 'bala%' for setting 'mySetting': Invalid memory fraction, expected a value between 0.0% and 100.0%."));
    }

    try {
      memUse.apply(Functions.<String, String>constant("110.14%"));
      fail("Should've thrown.");
    } catch (IllegalArgumentException e) {
      assertThat(
          e.getMessage(),
          equalTo(
              "Bad value '110.14%' for setting 'mySetting': Invalid memory fraction, expected a value between 0.0% and 100.0%."));
    }
  }
  @Test
  public void testPLFM_1288() throws Exception {
    Project p = new Project();
    p.setName("Create without entity type");
    p.setEntityType(p.getClass().getName());
    p = (Project) entityServletHelper.createEntity(p, TEST_USER1);
    toDelete.add(p.getId());

    Study one = new Study();
    one.setName("one");
    one.setParentId(p.getId());
    one.setEntityType(Study.class.getName());
    one = (Study) entityServletHelper.createEntity(one, TEST_USER1);
    // Now try to re-use the name
    Code two = new Code();
    two.setName("code");
    two.setParentId(one.getId());
    two.setEntityType(Code.class.getName());
    try {
      two = (Code) entityServletHelper.createEntity(two, TEST_USER1);
      fail("Code cannot have a parent of type Study");
    } catch (IllegalArgumentException e) {
      System.out.println(e.getMessage());
      assertTrue(e.getMessage().indexOf(Code.class.getName()) > 0);
      assertTrue(e.getMessage().indexOf(Study.class.getName()) > 0);
    }
  }
Пример #22
0
  @Test
  public void testUnsigned() throws IOException {
    writer.writeUnsigned(1, 1);
    writer.writeUnsigned(2, 2);
    writer.writeUnsigned(3, 3);
    writer.writeUnsigned(4, 4);

    try {
      writer.writeUnsigned(8, 8);
      fail("No exception on bad argument");
    } catch (IllegalArgumentException e) {
      assertEquals("Unsupported byte count for unsigned: 8", e.getMessage());
    }

    BinaryReader reader = getReader();

    try {
      reader.expectUnsigned(8);
      fail("No exception on bad argument");
    } catch (IllegalArgumentException e) {
      assertEquals("Unsupported byte count for unsigned: 8", e.getMessage());
    }

    assertEquals(1, reader.expectUnsigned(1));
    assertEquals(2, reader.expectUnsigned(2));
    assertEquals(3, reader.expectUnsigned(3));
    assertEquals(4, reader.expectUnsigned(4));
  }
Пример #23
0
  public static void main(String args[]) {
    Manager2 m1, m2;
    String fname = JOptionPane.showInputDialog("First name: ");
    String sname = JOptionPane.showInputDialog("Surname: ");
    boolean valid = false;

    while (!valid) {
      try {
        double salary =
            Double.parseDouble(JOptionPane.showInputDialog("Weekly Salary: must be at least 600"));
        m2 = new Manager2(fname, sname, salary);
        JOptionPane.showMessageDialog(
            null,
            "Manager2 created successfully:\n "
                + m2.toString()
                + " and salary is "
                + m2.earnings());
        valid = true;
      } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(null, "Salary must be a number");
      } catch (IllegalArgumentException e) {
        JOptionPane.showMessageDialog(null, e.getMessage());
        System.out.print(e.getMessage());
      }
    }
  }
Пример #24
0
  /** Error cases test. */
  @Test
  public void errorCasesTest() {
    try {
      ServiceFactory<SampleService> factory = null;
      Manager.register(SampleService.class, factory, null, new Scope[] {});
      Assert.fail("Exception shold be thrown before this step.");
    } catch (IllegalArgumentException e) {
      Assert.assertTrue(
          "Right exception should be there.", e.getMessage().startsWith("serviceFactory"));
    }

    try {
      Manager.register(null, new SampleServiceFactory(), null, new Scope[] {});
      Assert.fail("Exception shold be thrown before this step.");
    } catch (IllegalArgumentException e) {
      Assert.assertTrue("Right exception should be there.", e.getMessage().startsWith("service"));
    }

    try {
      Manager.get(null);
      Assert.fail("Exception shold be thrown before this step.");
    } catch (IllegalArgumentException e) {
      Assert.assertTrue("Right exception should be there.", e.getMessage().startsWith("service"));
    } catch (ManagerException e) {
      Assert.fail("No exception should be on this step.");
    }
  }
Пример #25
0
 private static Value parseTypedReference(URIString pUriStr) throws IllegalArgumentException {
   Value strVal;
   int pos = pUriStr.getPos();
   try {
     strVal = StringValue.parse(pUriStr);
   } catch (IllegalArgumentException e) {
     String msg =
         "Failed to retrieve typed reference string!\n"
             + pUriStr.markPosition()
             + "Nested message is:\n"
             + e.getMessage();
     throw new IllegalArgumentException(msg);
   }
   URIString refUriStr = new URIString(strVal.toString());
   try {
     URI ref = URI.parseRef(refUriStr, true);
     return new ReferenceValue(ref);
   } catch (IllegalArgumentException e) {
     String msg =
         "Failed to parse typed reference value!\n"
             + pUriStr.markPosition(pos)
             + "Nested message is:\n"
             + e.getMessage();
     throw new IllegalArgumentException(msg);
   }
 }
  public void testInvalidInput() throws Exception {
    Map<String, String> resource = createJobResource("", "bar/baz/boo");
    Subject subject = createSubject("testActionAuthorization", "admin-invalidinput");

    // subject does not match
    Decision decision = authorization.evaluate(resource, subject, "run", environment);
    assertEquals(
        "Expecting to see REJECTED_NO_SUBJECT_OR_ENV_FOUND.",
        Code.REJECTED_NO_SUBJECT_OR_ENV_FOUND,
        decision.explain().getCode());

    assertFalse("An empty job name should not be authorized.", decision.isAuthorized());

    subject = createSubject("testActionAuthorization", "admin");
    try {
      authorization.evaluate(
          createJobResource(null, "test"), subject, "invalid_input_missing_key", environment);
      assertTrue("A null resource key should not be evaluated.", false);
    } catch (IllegalArgumentException e) {
      assert e.getMessage().contains("Resource definition cannot contain null value");
    }

    try {
      authorization.evaluate(
          createJobResource("test_key_with_null_value", null),
          subject,
          "invalid_input_missing_value",
          environment);
      assertTrue("A null resource value should not be evaluated.", false);
    } catch (IllegalArgumentException e) {
      assert e.getMessage().contains("Resource definition cannot contain null value");
    }
  }
  public void testConflictNewType() throws Exception {
    XContentBuilder mapping =
        XContentFactory.jsonBuilder()
            .startObject()
            .startObject("type1")
            .startObject("properties")
            .startObject("foo")
            .field("type", "long")
            .endObject()
            .endObject()
            .endObject()
            .endObject();
    MapperService mapperService =
        createIndex("test", Settings.settingsBuilder().build(), "type1", mapping).mapperService();

    XContentBuilder update =
        XContentFactory.jsonBuilder()
            .startObject()
            .startObject("type2")
            .startObject("properties")
            .startObject("foo")
            .field("type", "double")
            .endObject()
            .endObject()
            .endObject()
            .endObject();

    try {
      mapperService.merge(
          "type2",
          new CompressedXContent(update.string()),
          MapperService.MergeReason.MAPPING_UPDATE,
          false);
      fail();
    } catch (IllegalArgumentException e) {
      // expected
      assertTrue(
          e.getMessage(),
          e.getMessage().contains("mapper [foo] cannot be changed from type [long] to [double]"));
    }

    try {
      mapperService.merge(
          "type2",
          new CompressedXContent(update.string()),
          MapperService.MergeReason.MAPPING_UPDATE,
          false);
      fail();
    } catch (IllegalArgumentException e) {
      // expected
      assertTrue(
          e.getMessage(),
          e.getMessage().contains("mapper [foo] cannot be changed from type [long] to [double]"));
    }

    assertTrue(
        mapperService.documentMapper("type1").mapping().root().getMapper("foo")
            instanceof LongFieldMapper);
    assertNull(mapperService.documentMapper("type2"));
  }
  @Test
  public void getResourceClassInfoByResource_nonExistentReferences_shouldFail() {
    authenticateSystemResource();

    final char[] password = generateUniquePassword();
    final Resource accessorResource = generateAuthenticatableResource(password);

    generateResourceClass(false, false);

    // authenticate and verify
    accessControlContext.authenticate(accessorResource, PasswordCredentials.newInstance(password));

    try {
      accessControlContext.getResourceClassInfoByResource(Resources.getInstance(-999L));
      fail("getting resource class info by resource for non-existent resource should have failed");
    } catch (IllegalArgumentException e) {
      assertThat(e.getMessage().toLowerCase(), containsString("not found"));
    }
    try {
      accessControlContext.getResourceClassInfoByResource(Resources.getInstance("invalid"));
      fail(
          "getting resource class info by resource for non-existent external resource reference should have failed");
    } catch (IllegalArgumentException e) {
      assertThat(e.getMessage().toLowerCase(), containsString("not found"));
    }
    try {
      accessControlContext.getResourceClassInfoByResource(Resources.getInstance(-999L, "invalid"));
      fail(
          "getting resource class info by resource for mismatched internal/external resource ids should have failed");
    } catch (IllegalArgumentException e) {
      assertThat(e.getMessage().toLowerCase(), containsString("not resolve"));
    }
  }
Пример #29
0
  private void dumpDocuments() throws IOException {
    outputBanner("Documents");

    int totalDocs = mIndexReader.numDocs();

    outputLn();
    outputLn("There are " + totalDocs + " documents in this index.");

    mConsole.debug("Total number of documents: " + totalDocs);
    for (int i = 0; i < totalDocs; i++) {
      Document doc = null;
      try {
        doc = mIndexReader.document(i, null);
      } catch (IllegalArgumentException e) {
        if ("attempt to access a deleted document".equals(e.getMessage())) {
          mConsole.warn(
              "encountered exception while dumping document " + i + ": " + e.getMessage());
        } else {
          throw e;
        }
      }
      dumpDocument(i, doc);

      if ((i + 1) % 100 == 0) {
        mConsole.debug("Dumped " + (i + 1) + " documents");
      }
    }
  }
Пример #30
0
 private void readSettingsFrame(
     ChannelHandlerContext ctx, ByteBuf payload, Http2FrameListener listener)
     throws Http2Exception {
   if (flags.ack()) {
     listener.onSettingsAckRead(ctx);
   } else {
     int numSettings = payloadLength / SETTING_ENTRY_LENGTH;
     Http2Settings settings = new Http2Settings();
     for (int index = 0; index < numSettings; ++index) {
       char id = (char) payload.readUnsignedShort();
       long value = payload.readUnsignedInt();
       try {
         settings.put(id, Long.valueOf(value));
       } catch (IllegalArgumentException e) {
         switch (id) {
           case SETTINGS_MAX_FRAME_SIZE:
             throw connectionError(FRAME_SIZE_ERROR, e, e.getMessage());
           case SETTINGS_INITIAL_WINDOW_SIZE:
             throw connectionError(FLOW_CONTROL_ERROR, e, e.getMessage());
           default:
             throw connectionError(PROTOCOL_ERROR, e, e.getMessage());
         }
       }
     }
     listener.onSettingsRead(ctx, settings);
   }
 }