/** * Converts a {@link JsonValue} to its corresponding Java object. Values of type {@link * JsonObject} or {@link JsonArray} are converted as specified by {@link #toJavaMap} and {@link * #toJavaList}, respectively. */ @Nullable public static Object toJavaObject(JsonValue value) { switch (value.getValueType()) { case ARRAY: return toJavaList((JsonArray) value); case FALSE: return Boolean.FALSE; case NULL: return null; case NUMBER: JsonNumber number = (JsonNumber) value; return number.isIntegral() ? number.intValue() : number.doubleValue(); case OBJECT: return toJavaMap((JsonObject) value); case STRING: return ((JsonString) value).getString(); case TRUE: return Boolean.TRUE; default: throw new VerifyException("Json value with unknown type: " + value); } }
private List<MethodSpec> getSuperMethodSpecs() { List<MethodSpec> methodSpecs = new ArrayList<>(); this.annotatedClazz.annotatedElement.getEnclosedElements().stream() .filter(element -> element instanceof ExecutableElement) .map(element -> (ExecutableElement) element) .forEach(method -> { ClassName preferenceRoom = ClassName.get(PreferenceRoom.class); MethodSpec.Builder builder = MethodSpec.overriding(method); MethodSpec methodSpec = builder.addStatement("$T.inject($N)", preferenceRoom, method.getParameters().get(0).getSimpleName()).build(); if(methodSpec.returnType != TypeName.get(Void.TYPE)) { throw new VerifyException(String.format("Returned '%s'. only return type can be void.", methodSpec.returnType.toString())); } methodSpecs.add(methodSpec); }); return methodSpecs; }
private void processInjector(PreferenceComponentAnnotatedClass annotatedClass) throws VerifyException { try { annotatedClass.annotatedElement.getEnclosedElements().stream() .filter(element -> element instanceof ExecutableElement) .map(element -> (ExecutableElement) element) .forEach(method -> { MethodSpec methodSpec = MethodSpec.overriding(method).build(); ParameterSpec parameterSpec = methodSpec.parameters.get(0); TypeElement injectedElement = processingEnv.getElementUtils().getTypeElement(parameterSpec.type.toString()); generateProcessInjector(annotatedClass, injectedElement); }); } catch (VerifyException e) { showErrorLog(e.getMessage(), annotatedClass.annotatedElement); e.printStackTrace(); } }
public KickbackElementClass(VariableElement variableElement, Elements elementUtils) throws VerifyException { KickbackElement kickbackElement = variableElement.getAnnotation(KickbackElement.class); Weak weak = variableElement.getAnnotation(Weak.class); Soft soft = variableElement.getAnnotation(Soft.class); PackageElement packageElement = elementUtils.getPackageOf(variableElement); this.variableElement = variableElement; this.packageName = packageElement.isUnnamed() ? null : packageElement.getQualifiedName().toString(); this.typeName = TypeName.get(variableElement.asType()); this.clazzName = variableElement.getSimpleName().toString(); this.value = variableElement.getConstantValue(); if(weak != null) this.isWeak = true; else this.isWeak = false; if(soft != null) this.isSoft = true; else this.isSoft = false; if(kickbackElement != null) { this.elementName = StringUtils.toUpperCamel(Strings.isNullOrEmpty(kickbackElement.name()) ? this.clazzName : kickbackElement.name()); } else { this.elementName = StringUtils.toUpperCamel(this.clazzName); } checkPrimitiveType(); checkModifierValidate(); checkAnnotationValidate(); }
@Provides @JsonPayload @SuppressWarnings("unchecked") static Map<String, Object> provideJsonPayload( @Header("Content-Type") MediaType contentType, @Payload String payload) { if (!JSON_UTF_8.is(contentType.withCharset(UTF_8))) { throw new UnsupportedMediaTypeException( String.format("Expected %s Content-Type", JSON_UTF_8.withoutParameters())); } try { return (Map<String, Object>) JSONValue.parseWithException(payload); } catch (ParseException e) { throw new BadRequestException( "Malformed JSON", new VerifyException("Malformed JSON:\n" + payload, e)); } }
/** * Search for public key on keyring based on a substring (like an email address). * * @throws VerifyException if the key couldn't be found. * @see #lookupKeyPair */ public static PGPPublicKey lookupPublicKey( PGPPublicKeyRingCollection keyring, String query, KeyRequirement want) { try { // Safe by specification. @SuppressWarnings("unchecked") Iterator<PGPPublicKeyRing> results = keyring.getKeyRings(checkNotNull(query, "query"), true, true); verify(results.hasNext(), "No public key found matching substring: %s", query); while (results.hasNext()) { Optional<PGPPublicKey> result = lookupPublicSubkey(results.next(), want); if (result.isPresent()) { return result.get(); } } throw new VerifyException(String.format( "No public key (%s) found matching substring: %s", want, query)); } catch (PGPException e) { throw new VerifyException(String.format( "Public key lookup with query %s failed: %s", query, e.getMessage())); } }
/** * Same as {@link #lookupPublicKey} but also retrieves the associated private key. * * @throws VerifyException if either keys couldn't be found. * @see #lookupPublicKey */ @SuppressWarnings("deprecation") public static PGPKeyPair lookupKeyPair( PGPPublicKeyRingCollection publics, PGPSecretKeyRingCollection privates, String query, KeyRequirement want) { PGPPublicKey publicKey = lookupPublicKey(publics, query, want); PGPPrivateKey privateKey; try { PGPSecretKey secret = verifyNotNull(privates.getSecretKey(publicKey.getKeyID()), "Keyring missing private key associated with public key id: %x (query '%s')", publicKey.getKeyID(), query); // We do not support putting a password on the private key so we're just going to // put char[0] here. privateKey = secret.extractPrivateKey( new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()) .build(new char[0])); } catch (PGPException e) { throw new VerifyException(e.getMessage()); } return new PGPKeyPair(publicKey, privateKey); }
@Test public void testSaveRevision_objectDoesntExist_newRevisionIsOne_throwsVe() throws Exception { VerifyException thrown = expectThrows( VerifyException.class, () -> ofy() .transact( new VoidWork() { @Override public void vrun() { saveRevision("despondency", DateTime.parse("1984-12-18TZ"), FULL, 1); } })); assertThat(thrown).hasMessageThat().contains("object missing"); }
@Test public void testSaveRevision_objectExistsAtZero_newRevisionIsZero_throwsVe() throws Exception { save("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0); VerifyException thrown = expectThrows( VerifyException.class, () -> ofy() .transact( new VoidWork() { @Override public void vrun() { saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0); } })); assertThat(thrown).hasMessageThat().contains("object already created"); }
@Test public void testSaveRevision_objectExistsAtZero_newRevisionIsTwo_throwsVe() throws Exception { save("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0); VerifyException thrown = expectThrows( VerifyException.class, () -> ofy() .transact( new VoidWork() { @Override public void vrun() { saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 2); } })); assertThat(thrown).hasMessageThat().contains("should be at 1 "); }
@Test public void testPublishDomainFails_whenDnsUpdateReturnsError() throws Exception { DomainResource domain = persistActiveDomain("example.tld") .asBuilder() .setNameservers(ImmutableSet.of(Key.create(persistActiveHost("ns1.example.tld")))) .build(); persistResource(domain); when(mockResolver.send(any(Message.class))).thenReturn(messageWithResponseCode(Rcode.SERVFAIL)); VerifyException thrown = expectThrows( VerifyException.class, () -> { writer.publishDomain("example.tld"); writer.commit(); }); assertThat(thrown).hasMessageThat().contains("SERVFAIL"); }
@Test public void testPublishHostFails_whenDnsUpdateReturnsError() throws Exception { HostResource host = persistActiveSubordinateHost("ns1.example.tld", persistActiveDomain("example.tld")) .asBuilder() .setInetAddresses(ImmutableSet.of(InetAddresses.forString("10.0.0.1"))) .build(); persistResource(host); when(mockResolver.send(any(Message.class))).thenReturn(messageWithResponseCode(Rcode.SERVFAIL)); VerifyException thrown = expectThrows( VerifyException.class, () -> { writer.publishHost("ns1.example.tld"); writer.commit(); }); assertThat(thrown).hasMessageThat().contains("SERVFAIL"); }
@Test public void testRun_errorResponse() throws Exception { reset(connection); command.setConnection(connection); when(connection.send( eq(CreatePremiumListAction.PATH), anyMapOf(String.class, String.class), any(MediaType.class), any(byte[].class))) .thenReturn( JSON_SAFETY_PREFIX + "{\"status\":\"error\",\"error\":\"foo already exists\"}"); VerifyException thrown = expectThrows( VerifyException.class, () -> runCommandForced("-i=" + premiumTermsPath, "-n=foo")); assertThat(thrown).hasMessageThat().contains("Server error:"); }
@Test(expected = VerifyException.class) public void testOnDataCaseLeafFail() throws DataValidationFailedException { final DataTree inMemoryDataTree = new InMemoryDataTreeFactory().create( DataTreeConfiguration.DEFAULT_CONFIGURATION, schemaContext); final YangInstanceIdentifier.NodeIdentifier choice1Id = new YangInstanceIdentifier.NodeIdentifier(QName.create( TestModel.TEST_QNAME, "choice1")); final YangInstanceIdentifier ii = TestModel.TEST_PATH.node(choice1Id); final ChoiceNode choice1 = Builders.choiceBuilder().withNodeIdentifier(choice1Id) .withChild(leafNode(QName.create(TestModel.TEST_QNAME, "case1-leaf1"), "leaf-value")).build(); final DataTreeModification modificationTree = inMemoryDataTree.takeSnapshot().newModification(); modificationTree.write(ii, choice1); modificationTree.ready(); inMemoryDataTree.validate(modificationTree); final DataTreeCandidate prepare = inMemoryDataTree.prepare(modificationTree); inMemoryDataTree.commit(prepare); }
@Test(expected = UnresolvableException.class) public void testYangFunctionContext() throws UnresolvableException, FunctionCallException { final YangFunctionContext yangFun = YangFunctionContext.getInstance(); assertNotNull(yangFun); final Function function = yangFun.getFunction("urn:opendaylight.test2", null, "current"); assertNotNull(function); try { final Context context = mock(Context.class); final ArrayList<Object> list = new ArrayList<>(); function.call(context, list); fail(); } catch (VerifyException e) { // Expected } yangFun.getFunction("urn:opendaylight.test2", "test2", "root"); }
@VisibleForTesting protected Optional<Map.Entry<String, VersionUniverse>> getVersionUniverse(TargetNode<?, ?> root) { Optional<String> universeName = getVersionUniverseName(root); if (!universeName.isPresent() && !universes.isEmpty()) { return Optional.of(Iterables.get(universes.entrySet(), 0)); } if (!universeName.isPresent()) { return Optional.empty(); } VersionUniverse universe = universes.get(universeName.get()); if (universe == null) { throw new VerifyException( String.format( "%s: unknown version universe \"%s\"", root.getBuildTarget(), universeName.get())); } return Optional.of(new AbstractMap.SimpleEntry<>(universeName.get(), universe)); }
/** Converts a {@link JsonObject} to a {@link JSONObject}. */ public static JSONObject toOrgJson(JsonObject json) { try { return new JSONObject(json.toString()); } catch (JSONException e) { // Should never happen, because we start from a valid JSON object. throw new VerifyException(e); } }
private void checkOverrideMethods() { annotatedElement.getEnclosedElements().stream() .filter(element -> element instanceof ExecutableElement) .map(element -> (ExecutableElement) element) .forEach(method -> { if(keyNameFields.contains(method.getSimpleName().toString().replace(SETTER_PREFIX, ""))) throw new VerifyException(getMethodNameVerifyErrorMessage(method.getSimpleName().toString())); else if(keyNameFields.contains(method.getSimpleName().toString().replace(GETTER_PREFIX, ""))) throw new VerifyException(getMethodNameVerifyErrorMessage(method.getSimpleName().toString())); else if(keyNameFields.contains(method.getSimpleName().toString().replace(HAS_PREFIX, ""))) throw new VerifyException(getMethodNameVerifyErrorMessage(method.getSimpleName().toString())); else if(keyNameFields.contains(method.getSimpleName().toString().replace(REMOVE_PREFIX, ""))) throw new VerifyException(getMethodNameVerifyErrorMessage(method.getSimpleName().toString())); }); }
public MethodSpec getConstructorSpec() { MethodSpec.Builder builder = MethodSpec.constructorBuilder() .addModifiers(PUBLIC) .addParameter(ParameterSpec.builder(TypeName.get(injectedElement.asType()), INJECT_OBJECT).addAnnotation(NonNull.class).build()); injectedElement.getEnclosedElements().stream() .filter(variable -> variable instanceof VariableElement) .map(variable -> (VariableElement) variable) .forEach(variable -> { if(variable.getAnnotation(InjectPreference.class) != null) { String annotatedFieldName = TypeName.get(variable.asType()).toString(); if(annotatedFieldName.contains(".") || annotatedFieldName.contains("\\.")) { ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(annotatedFieldName); String arr = StandardCharsets.UTF_8.decode(byteBuffer).toString(); String[] typedArray = arr.split("\\."); annotatedFieldName = typedArray[typedArray.length-1]; } ClassName componentClazz = ClassName.get(annotatedClazz.packageName, COMPONENT_PREFIX + annotatedClazz.clazzName); if(annotatedClazz.generatedClazzList.contains(annotatedFieldName)) { builder.addStatement(INJECT_OBJECT + ".$N = $T.getInstance().$N()", variable.getSimpleName(), componentClazz, annotatedFieldName.replace(PREFERENCE_PREFIX, "")); } else if((COMPONENT_PREFIX + annotatedClazz.clazzName).equals(annotatedFieldName)) { builder.addStatement(INJECT_OBJECT + ".$N = $T.getInstance()", variable.getSimpleName(), componentClazz); } else { throw new VerifyException(String.format("'%s' type can not be injected", annotatedFieldName)); } } }); return builder.build(); }
private void processEntity(TypeElement annotatedType) throws VerifyException { try { PreferenceEntityAnnotatedClass annotatedClazz = new PreferenceEntityAnnotatedClass(annotatedType, processingEnv.getElementUtils()); checkDuplicatedPreferenceEntity(annotatedClazz); generateProcessEntity(annotatedClazz); } catch (VerifyException e) { showErrorLog(e.getMessage(), annotatedType); e.printStackTrace(); } }
private void processComponent(TypeElement annotatedType) throws VerifyException { try { PreferenceComponentAnnotatedClass annotatedClazz = new PreferenceComponentAnnotatedClass(annotatedType, processingEnv.getElementUtils(), annotatedEntityNameMap); checkDuplicatedPreferenceComponent(annotatedClazz); generateProcessComponent(annotatedClazz); } catch (VerifyException e) { showErrorLog(e.getMessage(), annotatedType); e.printStackTrace(); } }
private void checkDuplicatedPreferenceEntity(PreferenceEntityAnnotatedClass annotatedClazz) throws VerifyException { if(annotatedEntityMap.containsKey(annotatedClazz.entityName)) { throw new VerifyException("@PreferenceRoom key name is duplicated."); } else { annotatedEntityMap.put(annotatedClazz.entityName, annotatedClazz); annotatedEntityNameMap.put(annotatedClazz.typeName + ".class", annotatedClazz.entityName); } }
private void checkDuplicatedPreferenceComponent(PreferenceComponentAnnotatedClass annotatedClazz) { if(annotatedComponentList.contains(annotatedClazz)) throw new VerifyException("@PreferenceComponent is duplicated."); else { annotatedComponentList.add(annotatedClazz); } }
private void processKickbackBox(TypeElement annotatedType) { try { KickbackBoxAnnotatedClass annotatedClazz = new KickbackBoxAnnotatedClass(annotatedType, processingEnv.getElementUtils()); checkDuplicatedKickbackBox(annotatedClazz); generateProcessKickbackBox(annotatedClazz); } catch (VerifyException e) { showErrorLog(e.getMessage(), annotatedType); } }
private void checkDuplicatedKickbackBox(KickbackBoxAnnotatedClass annotatedClazz) throws VerifyException { String keyName = annotatedClazz.boxName; if(annotatedBoxMap.containsKey(keyName)) { throw new VerifyException("@KickbackBox key name is duplicated."); } else { annotatedBoxMap.put(keyName, annotatedClazz); } }
private FakeRawProcess() { try { stdoutOutputStream = new PipedOutputStream(stdout); stderrOutputStream = new PipedOutputStream(stderr); } catch (IOException e) { // Can only happen if piped input streams are already connected, and we know they are not. throw new VerifyException(e); } }
@Override public int await() throws InterruptedException { try { return exitCodeFuture.get(); } catch (ExecutionException e) { throw new VerifyException(e); } }
/** * Sets the process as terminated with the specified exit code. This has no effect if the * process is already terminated. */ private void setTerminated(int exitCode) { exitCodeFuture.set(exitCode); try { stdoutOutputStream.close(); stderrOutputStream.close(); } catch (IOException e) { // PipedOutputStream#close never throws IOException despite declaring it. throw new VerifyException(e); } }
@Test public void testApplyModifyTransactionRequestNotAbort() throws Exception { final TestProbe probe = createProbe(); final ModifyTransactionRequestBuilder builder = new ModifyTransactionRequestBuilder(TRANSACTION_ID, probe.ref()); builder.setSequence(0); builder.setReady(); final ModifyTransactionRequest request = builder.build(); assertOperationThrowsException(() -> transaction.replayModifyTransactionRequest(request, createCallbackMock(), Ticker.systemTicker().read()), VerifyException.class); }
default <C extends Component> C ensureAndGet(Class<C> clazz) { Optional<C> component = get(clazz); if (!component.isPresent()) { throw new VerifyException("Component class " + clazz.getName() + " isn't provided by this entity."); } return component.get(); }
/** Always returns a {@link InMemoryKeyring} instance. */ @Provides static Keyring provideKeyring() { PGPKeyPair dummyKey; try (InputStream publicInput = PGP_PUBLIC_KEYRING.openStream(); InputStream privateInput = PGP_PRIVATE_KEYRING.openStream()) { PGPPublicKeyRingCollection publicKeys = new BcPGPPublicKeyRingCollection(PGPUtil.getDecoderStream(publicInput)); PGPSecretKeyRingCollection privateKeys = new BcPGPSecretKeyRingCollection(PGPUtil.getDecoderStream(privateInput)); dummyKey = lookupKeyPair(publicKeys, privateKeys, EMAIL_ADDRESS, ENCRYPT_SIGN); } catch (PGPException | IOException e) { throw new VerifyException("Failed to load PGP keys from jar", e); } // Use the same dummy PGP keypair for all required PGP keys -- a real production system would // have different values for these keys. Pass dummy values for all Strings. return new InMemoryKeyring( dummyKey, dummyKey, dummyKey.getPublicKey(), dummyKey, dummyKey.getPublicKey(), "not a real key", "not a real key", "not a real password", "not a real login", "not a real password", "not a real login", "not a real credential", "not a real key"); }
@Test public void testFailure_nullRegistryUser() throws Exception { persistClaimsModeDomain(); persistResource(Registry.get("tld").asBuilder().setLordnUsername(null).build()); VerifyException thrown = expectThrows(VerifyException.class, action::run); assertThat(thrown).hasMessageThat().contains("lordnUsername is not set for tld."); }
@Test public void testResponseIdMismatchThrowsExeption() throws Exception { expectedResponse.getHeader().setID(1 + simpleQuery.getHeader().getID()); when(mockSocket.getInputStream()) .thenReturn(new ByteArrayInputStream(messageToBytesWithLength(expectedResponse))); when(mockSocket.getOutputStream()).thenReturn(new ByteArrayOutputStream()); VerifyException thrown = expectThrows(VerifyException.class, () -> resolver.send(simpleQuery)); assertThat(thrown) .hasMessageThat() .contains( "response ID " + expectedResponse.getHeader().getID() + " does not match query ID " + simpleQuery.getHeader().getID()); }
@Test public void testResponseOpcodeMismatchThrowsException() throws Exception { simpleQuery.getHeader().setOpcode(Opcode.QUERY); expectedResponse.getHeader().setOpcode(Opcode.STATUS); when(mockSocket.getInputStream()) .thenReturn(new ByteArrayInputStream(messageToBytesWithLength(expectedResponse))); when(mockSocket.getOutputStream()).thenReturn(new ByteArrayOutputStream()); VerifyException thrown = expectThrows(VerifyException.class, () -> resolver.send(simpleQuery)); assertThat(thrown) .hasMessageThat() .contains("response opcode 'STATUS' does not match query opcode 'QUERY'"); }
private String matchQuotedSubscript() { // quote has already been matched // seek until we see the close quote StringBuilder token = new StringBuilder(); boolean escaped = false; while (hasNextCharacter() && (escaped || peekCharacter() != QUOTE)) { if (escaped) { switch (peekCharacter()) { case QUOTE: case BACKSLASH: token.append(peekCharacter()); break; default: throw invalidJsonPath(); } escaped = false; } else { switch (peekCharacter()) { case BACKSLASH: escaped = true; break; case QUOTE: throw new VerifyException("Should be handled by loop condition"); default: token.append(peekCharacter()); } } nextCharacter(); } if (escaped) { verify(!hasNextCharacter(), "Loop terminated after escape while there is still input"); throw invalidJsonPath(); } match(QUOTE); return token.toString(); }
private void checkReturnValue(long value, long funcDecl) { if (value == 0) { throw new VerifyException( "Z3 unexpectedly claims that the value of " + Native.funcDeclToString(z3context, funcDecl) + " does not matter in model."); } }
@Test public void testGetMessageId_missing() throws Exception { when(message.getHeader("Message-ID")) .thenReturn(new String[0]); try { localMailMessage.getMessageId(); assertWithMessage("Should have thrown an exception").fail(); } catch (VerifyException expected) { // OK! } }
@Test public void testGetFromHeader_missing() throws Exception { when(message.getHeader("From")) .thenReturn(new String[0]); try { localMailMessage.getFromHeader(); assertWithMessage("Should have thrown an exception").fail(); } catch (VerifyException expected) { // OK! } }