/** * PUBLIC: Return a session broker that behaves as a client session broker. An acquire session * broker is done under the covers on each session inside the session broker, and a new broker is * returned. * * <p>NOTE: when finished with the client broker, it should be releases. See * releaseClientSessionBroker. */ public SessionBroker acquireClientSessionBroker() { log(SessionLog.FINER, SessionLog.CONNECTION, "acquire_client_session_broker"); SessionBroker clientBroker = copySessionBroker(); clientBroker.parent = this; clientBroker .getIdentityMapAccessorInstance() .setIdentityMapManager(getIdentityMapAccessorInstance().getIdentityMapManager()); clientBroker.commitManager = getCommitManager(); clientBroker.commandManager = getCommandManager(); clientBroker.externalTransactionController = getExternalTransactionController(); clientBroker.setServerPlatform(getServerPlatform()); String sessionName; AbstractSession serverSession; Iterator names = this.getSessionsByName().keySet().iterator(); while (names.hasNext()) { sessionName = (String) names.next(); serverSession = getSessionForName(sessionName); if (serverSession instanceof org.eclipse.persistence.sessions.server.ServerSession) { if (serverSession.getProject().hasIsolatedClasses()) { throw ValidationException.isolatedDataNotSupportedInSessionBroker(sessionName); } clientBroker.internalRegisterSession( sessionName, ((org.eclipse.persistence.sessions.server.ServerSession) serverSession) .acquireClientSession()); } else { throw ValidationException.cannotAcquireClientSessionFromSession(); } } clientBroker.initializeSequencing(); return clientBroker; }
public void testMessageInterpolation() { // get validators List validatorList = annotationActionValidatorManager.getValidators( AnnotatedTestBean.class, "beanMessageBundle"); assertEquals(3, validatorList.size()); try { AnnotatedTestBean bean = new AnnotatedTestBean(); bean.setName("foo"); bean.setCount(150); ValidatorContext context = new GenericValidatorContext(bean); annotationActionValidatorManager.validate(bean, "beanMessageBundle", context); assertTrue(context.hasErrors()); assertTrue(context.hasFieldErrors()); List<String> l = context.getFieldErrors().get("count"); assertNotNull(l); assertEquals(1, l.size()); assertEquals("Count must be between 1 and 100, current value is 150.", l.get(0)); } catch (ValidationException ex) { ex.printStackTrace(); fail("Validation error: " + ex.getMessage()); } }
/** * INTERNAL: Convert all the class-name-based settings in this InheritancePolicy to actual * class-based settings. This method is used when converting a project that has been built with * class names to a project with classes. It will also convert referenced classes to the versions * of the classes from the classLoader. */ public void convertClassNamesToClasses(ClassLoader classLoader) { Vector newParentInterfaces = new Vector(); for (Iterator iterator = getParentInterfaceNames().iterator(); iterator.hasNext(); ) { String interfaceName = (String) iterator.next(); Class interfaceClass = null; try { if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) { try { interfaceClass = (Class) AccessController.doPrivileged( new PrivilegedClassForName(interfaceName, true, classLoader)); } catch (PrivilegedActionException exception) { throw ValidationException.classNotFoundWhileConvertingClassNames( interfaceName, exception.getException()); } } else { interfaceClass = org.eclipse.persistence.internal.security.PrivilegedAccessHelper.getClassForName( interfaceName, true, classLoader); } } catch (ClassNotFoundException exc) { throw ValidationException.classNotFoundWhileConvertingClassNames(interfaceName, exc); } newParentInterfaces.add(interfaceClass); } this.parentInterfaces = newParentInterfaces; }
/** * INTERNAL: Convert all the class-name-based settings in this mapping to actual class-based * settings. This method is used when converting a project that has been built with class names to * a project with classes. */ @Override public void convertClassNamesToClasses(ClassLoader classLoader) { super.convertClassNamesToClasses(classLoader); Iterator iterator = getTypeIndicatorNameTranslation().entrySet().iterator(); this.typeIndicatorTranslation = new HashMap(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); String referenceClassName = (String) entry.getKey(); Object indicator = entry.getValue(); Class referenceClass = null; try { if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) { try { referenceClass = (Class) AccessController.doPrivileged( new PrivilegedClassForName(referenceClassName, true, classLoader)); } catch (PrivilegedActionException exception) { throw ValidationException.classNotFoundWhileConvertingClassNames( referenceClassName, exception.getException()); } } else { referenceClass = PrivilegedAccessHelper.getClassForName(referenceClassName, true, classLoader); } } catch (ClassNotFoundException exception) { throw ValidationException.classNotFoundWhileConvertingClassNames( referenceClassName, exception); } addClassIndicator(referenceClass, indicator); } }
@Test @Play("order_response_validation_error") public void deveTratarExceptionCasoOcorraErroValidacao() { try { Order createdOrder = moip.orders() .setOwnId("java_sdk_1") .addItem("Nome do produto", 0, "Mais info...", 1000) .setShippingAmount(100) .setCustomer( moip.customers() .setOwnId("java_sdk_customer_1") .setFullname("Jose da Silva") .setEmail("*****@*****.**") .setBirthDate("1988-12-30") .setTaxDocument("33333333333") .setPhone("11", "66778899", "55") .setShippingAddress( new Address() .setStreet("Avenida Faria Lima") .setStreetNumber("2927") .setComplement("8") .setDistrict("Itaim") .setCity("São Paulo") .setState("SP") .setZipCode("01234000"))) .create(); fail("Deveria lançar uma exception"); } catch (ValidationException v) { Assert.assertEquals("deve estar entre 1 e 9999", v.getErrors().get(0).getDescription()); Assert.assertEquals("items[0].quantity", v.getErrors().get(0).getPath()); } }
/** handles Hibernate validation exception */ public void afterThrowing(Method m, Object[] args, Object target, InvalidStateException e) { Logger log = LoggerFactory.getLogger(target.getClass()); StringBuilder logText = new StringBuilder(excMessage(e)); if (e.getInvalidValues() != null && e.getInvalidValues().length > 0) { for (InvalidValue each : e.getInvalidValues()) { logText.append(" : ").append(each.getPropertyPath()).append(" "); logText.append("'").append(each.getMessage()).append("'"); logText.append(" "); logText.append(each.getPropertyPath()).append("="); logText.append(each.getValue()); } logText.append(" rootBean=").append(e.getInvalidValues()[0].getRootBean()); } if (isJmsContext()) { LogMessage message = new LogMessage( mapLogCode(mapLogCode(ValidationException.ERROR_CODE)), logText.toString()); log.error("{}", message); } else { LogMessage message = new LogMessage(mapLogCode(ValidationException.ERROR_CODE), logText.toString()); log.debug("{}", message); } ValidationException newException = new ValidationException(excMessage(e)); newException.setLogged(true); newException.setInvalidValues(e.getInvalidValues()); throw newException; }
/** * Validate a set of properties for a description, and return a report. * * @param props the input properties * @param desc the configuration description * @return the validation report */ public static Report validate(final Properties props, final Description desc) { final Report report = new Report(); final List<Property> properties = desc.getProperties(); if (null != properties) { for (final Property property : properties) { final String key = property.getName(); final String value = props.getProperty(key); if (null == value || "".equals(value)) { if (property.isRequired()) { report.errors.put(key, "required"); continue; } } else { // try to validate final Property.Validator validator = property.getValidator(); if (null != validator) { try { if (!validator.isValid(value)) { report.errors.put(key, "Invalid value"); } } catch (ValidationException e) { report.errors.put(key, "Invalid value: " + e.getMessage()); } } } } } return report; }
void internalDoAction(final ActionPane pane) { try { pane.action().run(); } catch (final ValidationException e) { JOptionPane.showMessageDialog(this, e.getUserMessage()); return; } OkCancelDialog.this.setVisible(false); }
/* * This action receives the form submission from the page for the final step of the signature process. We'll call * REST PKI to complete the signature. */ @RequestMapping( value = "/xml-signature-complete", method = {RequestMethod.POST}) public String complete( @RequestParam(value = "token", required = true) String token, @RequestParam(value = "signature", required = true) String signature, Model model) throws IOException, RestException { // Instantiate the FullXmlSignatureFinisher class, responsible for completing the signature // process. For more // information, see: // https://pki.rest/Content/docs/java-client/index.html?com/lacunasoftware/restpki/XmlSignatureFinisher.html XmlSignatureFinisher signatureFinisher = new XmlSignatureFinisher(Util.getRestPkiClient()); // Set the token for this signature (rendered in a hidden input field, see file // templates/xml-full-signature.html) signatureFinisher.setToken(token); // Set the result of the signature operation signatureFinisher.setSignature(signature); // Call the finish() method, which finalizes the signature process and returns the signed XML's // bytes byte[] signedXml; try { signedXml = signatureFinisher.finish(); } catch (ValidationException e) { // The call above may throw a ValidationException if any validation errors occur (for // instance, if the // certificate is revoked). If so, we'll render a page showing what went wrong. model.addAttribute("title", "Validation of the signature failed"); // The toString() method of the ValidationResults object can be used to obtain the checks // performed, but the // string contains tabs and new line characters for formatting. Therefore, we call the method // Util.getValidationResultsHtml() to convert these characters to <br>'s and 's. model.addAttribute("vrHtml", Util.getValidationResultsHtml(e.getValidationResults())); return "validation-failed"; } // Get information about the certificate used by the user to sign the file. This method must // only be called after // calling the finish() method. PKCertificate signerCert = signatureFinisher.getCertificateInfo(); // At this point, you'd typically store the signed XML on your database. For demonstration // purposes, we'll // store the XML on a temporary folder and return to the page an identifier that can be used to // download it. String filename = UUID.randomUUID() + ".xml"; Files.write(Application.getTempFolderPath().resolve(filename), signedXml); model.addAttribute("signerCert", signerCert); model.addAttribute("filename", filename); return "xml-signature-info"; }
/** * Process this instruction * * @param context the dynamic context of the transformation * @return a TailCall to be executed by the caller, always null for this instruction */ public TailCall processLeavingTail(XPathContext context) throws XPathException { Controller controller = context.getController(); SequenceReceiver out = context.getReceiver(); int opt = options; int ann = annotation; // we may need to change the namespace prefix if the one we chose is // already in use with a different namespace URI: this is done behind the scenes // by the Outputter CharSequence value = expandChildren(context); if (schemaType != null) { // test whether the value actually conforms to the given type XPathException err = schemaType.validateContent( value, DummyNamespaceResolver.getInstance(), context.getConfiguration().getNameChecker()); if (err != null) { ValidationException verr = new ValidationException( "Attribute value " + Err.wrap(value, Err.VALUE) + " does not the match the required type " + schemaType.getDescription() + ". " + err.getMessage()); verr.setErrorCode("XTTE1540"); verr.setLocator(this); throw verr; } } else if (validationAction == Validation.STRICT || validationAction == Validation.LAX) { try { ann = controller.getConfiguration().validateAttribute(nameCode, value, validationAction); } catch (ValidationException e) { DynamicError err = DynamicError.makeDynamicError(e); String errorCode = e.getErrorCodeLocalPart(); if (errorCode == null) { errorCode = (validationAction == Validation.STRICT ? "XTTE1510" : "XTTE1515"); } err.setErrorCode(errorCode); err.setXPathContext(context); err.setLocator(this); err.setIsTypeError(true); throw err; } } try { out.attribute(nameCode, ann, value, locationId, opt); } catch (XPathException err) { throw dynamicError(this, err, context); } return null; }
/** * Validates the given Object * * @param object the Object to validate * @param resolver the ClassDescriptorResolver to load ClassDescriptors for use during validation. */ public void validate(Object object, ClassDescriptorResolver resolver) throws ValidationException { if (object == null) { throw new ValidationException("Cannot validate a null Object."); } if (resolver == null) { resolver = new ClassDescriptorResolverImpl(); } XMLClassDescriptor classDesc = resolver.resolve(object.getClass()); // -- we cannot validate an object if ClassDescriptor is null if (classDesc == null) return; TypeValidator validator = classDesc.getValidator(); XMLFieldDescriptor fieldDesc = null; try { if (validator != null) { if (validator instanceof ClassValidator) ((ClassValidator) validator).validate(object, resolver); else validator.validate(object); } // -- default validation else { // -- just validate each field FieldDescriptor[] fields = classDesc.getFields(); if (fields != null) { for (int i = 0; i < fields.length; i++) { fieldDesc = (XMLFieldDescriptor) fields[i]; if (fieldDesc == null) continue; FieldValidator fieldValidator = fieldDesc.getValidator(); if (fieldValidator != null) fieldValidator.validate(object, resolver); } } } } catch (ValidationException vx) { // -- add location information XPathLocation loc = (XPathLocation) vx.getLocation(); if (loc == null) { loc = new XPathLocation(); vx.setLocation(loc); if (fieldDesc != null) { if (fieldDesc.getNodeType() == NodeType.Attribute) loc.addAttribute(fieldDesc.getXMLName()); else loc.addChild(fieldDesc.getXMLName()); } } loc.addParent(classDesc.getXMLName()); throw vx; } } // -- validate
/** * Get the typed value of a node that is annotated with this schema type. This method must be * called only for a valid type. * * @param node the node whose typed value is required * @return a SequenceIterator over the atomic values making up the typed value of the specified * node. The objects returned by this iterator are of type {@link * org.orbeon.saxon.value.AtomicValue} */ public SequenceIterator getTypedValue(NodeInfo node) throws XPathException { try { return getTypedValue( node.getStringValue(), new InscopeNamespaceResolver(node), node.getConfiguration().getNameChecker()); } catch (ValidationException err) { throw new XPathException( "Internal error: value doesn't match its type annotation. " + err.getMessage()); } }
public boolean isAccountCreationSuccessful() { try { gatherNewAccountInfo(); validateCredentials(); storeLoginAttributes(); return true; } catch (ValidationException ex) { request.setAttribute("error", ex.getMessage()); return false; } }
/** * Validate that a {@link FieldMapping} is compatible with this builder's current set of * mappings and add it to the set of mappings. * * <p>A mapping is not compatible if it results in: * * <pre> * 1. Multiple occVersion mappings in the mapping set * 2. Both a counter and an occVersion mapping in the mapping set * </pre> * * @param fm a {@code FieldMapping} to add to this builder */ private void addField(FieldMapping fm) { // validate! if (fm.getMappingType() == FieldMapping.MappingType.OCC_VERSION) { ValidationException.check(!hasOCCVersion, "Cannot use multiple occVersion fields"); ValidationException.check(!hasCounter, "Cannot use both counter and occVersion fields"); hasOCCVersion = true; } else if (fm.getMappingType() == FieldMapping.MappingType.COUNTER) { ValidationException.check(!hasOCCVersion, "Cannot use both counter and occVersion fields"); hasCounter = true; } fieldMappings.add(fm); }
public void register() { if (user.getPassword().equals(verify)) { try { userService.createUser(user); hibernateTestService.testHibernateIntegration(); registered = true; } catch (ValidationException e) { facesMessages.add(e.getMessage()); } } else { facesMessages.add("verify", "Re-enter your password"); verify = null; } }
/** INTERNAL: Return the create table statement. */ public Writer buildCreationWriter(AbstractSession session, Writer writer) throws ValidationException { try { DatabasePlatform platform = session.getPlatform(); writer.write("CREATE PACKAGE " + getFullName()); writer.write(" AS"); writer.write("\n"); for (Enumeration statementsEnum = getStatements().elements(); statementsEnum.hasMoreElements(); ) { writer.write((String) statementsEnum.nextElement()); writer.write(platform.getBatchDelimiterString()); writer.write("\n"); } for (Enumeration proceduresEnum = getProcedures().elements(); proceduresEnum.hasMoreElements(); ) { writer.write("\n"); String procedureString = ((StoredProcedureDefinition) proceduresEnum.nextElement()) .buildCreationWriter(session, writer) .toString(); writer.write(procedureString.substring(7, procedureString.length())); writer.write("\n"); } writer.write(platform.getBatchEndString()); writer.write("\n" + session.getPlatform().getStoredProcedureTerminationToken()); } catch (IOException ioException) { throw ValidationException.fileError(ioException); } return writer; }
/** * PUBLIC: Connect to the database using the predefined login. This connects all of the child * sessions and expects that they are in a valid state to be connected. */ public void login(String userName, String password) throws DatabaseException { // Bug#3440544 Check if logged in already to stop the attempt to login more than once if (isLoggedIn) { throw ValidationException.alreadyLoggedIn(this.getName()); } else { if (this.eventManager != null) { this.eventManager.preLogin(this); } // Bug 3848021 - ensure the external transaction controller is initialized if (!isConnected()) { getServerPlatform().initializeExternalTransactionController(); } // Connection all sessions and initialize for (Iterator sessionEnum = getSessionsByName().values().iterator(); sessionEnum.hasNext(); ) { DatabaseSessionImpl session = (DatabaseSessionImpl) sessionEnum.next(); if (session.hasEventManager()) { session.getEventManager().preLogin(session); } session.getDatasourceLogin().setUserName(userName); session.getDatasourceLogin().setPassword(password); if (!session.isConnected()) { session.connect(); } } initializeDescriptors(); this.isLoggedIn = true; } }
/** * INTERNAL: Return the database platform specific information. This allows TopLink to configure * certain advanced features for the database desired. NOTE: this must only be used for relational * specific usage and will not work for non-relational datasources. */ public DatabasePlatform getPlatform() { try { return (DatabasePlatform) getDatasourcePlatform(); } catch (ClassCastException wrongType) { throw ValidationException.notSupportedForDatasource(); } }
/** INTERNAL: Return the session by name. */ public AbstractSession getSessionForName(String name) throws ValidationException { AbstractSession sessionByName = getSessionsByName().get(name); if (sessionByName == null) { throw ValidationException.noSessionRegisteredForName(name); } return sessionByName; }
private void add(FieldPartitioner fp) { ValidationException.check( !names.contains(fp.getName()), "Partition name %s conflicts with an existing field or partition name", fp.getName()); fieldPartitioners.add(fp); names.add(fp.getName()); }
@Override protected void processSubmission(String elementName) { String value = request.getParameter(elementName); tracker.recordInput(this, value); updateClientTimeZone(elementName); Date parsedValue = null; try { if (InternalUtils.isNonBlank(value)) { // Regardless of the timeZone set on the DateFormat, the value is parsed in // the current default TimeZone. Use the calendar to adjust it out. Date inDefaultTimeZone = format.parse(value); parsedValue = convertDateToClientTimeZone(inDefaultTimeZone); } } catch (ParseException ex) { tracker.recordError(this, messages.format("tapx-date-value-not-parseable", value)); return; } try { fieldValidationSupport.validate(parsedValue, resources, validate); } catch (ValidationException ex) { tracker.recordError(this, ex.getMessage()); return; } if (min != null && parsedValue.before(min)) { tracker.recordError(this, messages.get("tapx-date-value-to-early")); return; } if (max != null && parsedValue.after(max)) { tracker.recordError(this, messages.get("tapx-date-value-too-late")); return; } this.value = parsedValue; }
@SuppressWarnings({"unchecked"}) @Override protected void processSubmission(String controlName) { UploadedFile uploaded = decoder.getFileUpload(controlName); if (uploaded != null && (uploaded.getFileName() == null || uploaded.getFileName().length() == 0)) { uploaded = null; } try { fieldValidationSupport.validate(uploaded, resources, validate); } catch (ValidationException ex) { validationTracker.recordError(this, ex.getMessage()); } value = uploaded; }
/** PUBLIC: Add the field-value pair to the row. */ public Object put(Object key, Object value) throws ValidationException { if (key instanceof String) { return put((String) key, value); } else if (key instanceof DatabaseField) { return put((DatabaseField) key, value); } else { throw ValidationException.onlyFieldsAreValidKeysForDatabaseRows(); } }
/** INTERNAL: Return the drop type statement. */ public Writer buildDeletionWriter(AbstractSession session, Writer writer) throws ValidationException { try { writer.write("DROP TYPE " + getFullName()); } catch (IOException ioException) { throw ValidationException.fileError(ioException); } return writer; }
public void handleValidationException(ValidationException exception, ResponseBuilder builder) { builder.status(BAD_REQUEST); ValidationErrorMessageWrapper error = new ValidationErrorMessageWrapper(); for (ConstraintViolation<Object> violation : exception.getViolations()) { error.addMessage(violation.getMessage()); } builder.entity(error); }
public void testShortCircuitNoErrors() { // get validators List validatorList = annotationActionValidatorManager.getValidators(AnnotationUser.class, null); assertEquals(10, validatorList.size()); try { AnnotationUser user = new AnnotationUser(); user.setName("Mark"); user.setEmail("*****@*****.**"); user.setEmail2("*****@*****.**"); ValidatorContext context = new GenericValidatorContext(user); annotationActionValidatorManager.validate(user, null, context); assertFalse(context.hasErrors()); } catch (ValidationException ex) { ex.printStackTrace(); fail("Validation error: " + ex.getMessage()); } }
/** * INTERNAL: Set the name of the Platform to be used. Creates a new instance of the specified * Class. */ public void setPlatformClassName(String platformClassName) throws ValidationException { Class platformClass = null; try { // First try loading with the Login's class loader platformClass = this.getClass().getClassLoader().loadClass(platformClassName); Platform platform = null; if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) { try { platform = (Platform) AccessController.doPrivileged(new PrivilegedNewInstanceFromClass(platformClass)); } catch (PrivilegedActionException exception) { throw exception.getException(); } } else { platform = (Platform) PrivilegedAccessHelper.newInstanceFromClass(platformClass); } usePlatform(platform); } catch (Exception cne) { // next try using ConversionManager try { platformClass = ConversionManager.loadClass(platformClassName); Platform platform = null; if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) { try { platform = (Platform) AccessController.doPrivileged( new PrivilegedNewInstanceFromClass(platformClass)); } catch (PrivilegedActionException exception) { throw ValidationException.platformClassNotFound( exception.getException(), platformClassName); } } else { platform = (Platform) PrivilegedAccessHelper.newInstanceFromClass(platformClass); } usePlatform(platform); } catch (Exception cne2) { // if still not found, throw exception throw ValidationException.platformClassNotFound(cne2, platformClassName); } } }
public Item evaluateItem(XPathContext context) throws XPathException { Orphan o = (Orphan) super.evaluateItem(context); if (schemaType != null) { XPathException err = schemaType.validateContent( o.getStringValueCS(), DummyNamespaceResolver.getInstance(), context.getConfiguration().getNameChecker()); if (err != null) { throw new ValidationException( "Attribute value " + Err.wrap(o.getStringValueCS(), Err.VALUE) + " does not the match the required type " + schemaType.getDescription() + ". " + err.getMessage()); } o.setTypeAnnotation(schemaType.getFingerprint()); if (schemaType.isNamespaceSensitive()) { throw new DynamicError( "Cannot validate a parentless attribute whose content is namespace-sensitive"); } } else if (validationAction == Validation.STRICT || validationAction == Validation.LAX) { try { int ann = context .getController() .getConfiguration() .validateAttribute(nameCode, o.getStringValueCS(), validationAction); o.setTypeAnnotation(ann); } catch (ValidationException e) { DynamicError err = DynamicError.makeDynamicError(e); err.setErrorCode(e.getErrorCodeLocalPart()); err.setXPathContext(context); err.setLocator(this); err.setIsTypeError(true); throw err; } } return o; }
@Test public void 金融機関口座を取得する() { tx( () -> { assertThat( FiAccount.load(rep, "normal", "sample", "JPY"), allOf( hasProperty("accountId", is("normal")), hasProperty("category", is("sample")), hasProperty("currency", is("JPY")), hasProperty("fiCode", is("sample-JPY")), hasProperty("fiAccountId", is("FInormal")))); try { FiAccount.load(rep, "normal", "sample", "USD"); fail(); } catch (ValidationException e) { assertThat(e.getMessage(), is(ErrorKeys.EntityNotFound)); } }); }
/** INTERNAL: Return the session to be used for the class. */ public AbstractSession getSessionForClass(Class domainClass) throws ValidationException { if (domainClass == null) { // CR2114; we don't have a session name. Return us. return this; } String sessionName = getSessionNamesByClass().get(domainClass); if (sessionName == null) { throw ValidationException.noSessionRegisteredForClass(domainClass); } return getSessionsByName().get(sessionName); }