Ejemplo n.º 1
0
 public Collection<ValidationResult> getErrors() {
   Collection<ValidationResult> result = new ArrayList<>();
   for (Validator validator : validators) {
     result.addAll(validator.getErrors());
   }
   return result;
 }
  private ServerContext createServerContext(
      String gitRemoteUrl, AuthenticationInfo authenticationInfo) {
    ServerContext.Type type =
        UrlHelper.isVSO(UrlHelper.getBaseUri(gitRemoteUrl))
            ? ServerContext.Type.VSO_DEPLOYMENT
            : ServerContext.Type.TFS;
    final Client client = ServerContext.getClient(type, authenticationInfo);
    final Validator validator = new Validator(client);
    final UrlHelper.ParseResult uriParseResult = UrlHelper.tryParse(gitRemoteUrl, validator);
    if (uriParseResult.isSuccess()) {
      final ServerContextBuilder builder =
          new ServerContextBuilder()
              .type(type)
              .uri(gitRemoteUrl)
              .authentication(authenticationInfo)
              .teamProject(validator.getRepository().getProjectReference())
              .repository(validator.getRepository())
              .collection(validator.getCollection());

      // Set the uri of the context to the server uri (TODO change context so that it can be any URI
      // in the hierarchy)
      final URI serverUri = URI.create(uriParseResult.getServerUrl());
      builder.uri(serverUri);

      return builder.buildWithClient(client);
    }

    return null;
  }
Ejemplo n.º 3
0
  // escidoc:2110495 released item (1 locator escidoc:2110494)
  // has reference
  @Test
  public void testReleasedItem_2110495() throws Exception {

    indexer.indexItemsStart(new File(TEST_RESOURCES_OBJECTS + "escidoc_2110495"));
    indexer.finalizeIndex();

    assertTrue(
        "Expected 1 found " + indexer.getIndexingReport().getFilesIndexingDone(),
        indexer.getIndexingReport().getFilesIndexingDone() == 1);
    assertTrue(indexer.getIndexingReport().getFilesErrorOccured() == 0);
    assertTrue(indexer.getIndexingReport().getFilesSkippedBecauseOfTime() == 0);

    validator = new Validator(indexer);
    Map<String, Set<Fieldable>> fieldMap = validator.getFieldsOfDocument();
    assertTrue(fieldMap != null);

    Set<Fieldable> fields = fieldMap.get(getFieldNameFor("stored_filename1"));
    assertTrue(fields == null);
    assertTrue(fieldMap.get(getFieldNameFor("stored_filename1")) == null);
    assertTrue(fieldMap.get(getFieldNameFor("stored_fulltext1")) == null);

    assertTrue(fieldMap.get(getFieldNameFor("stored_filename")) == null);
    assertTrue(fieldMap.get(getFieldNameFor("stored_fulltext")) == null);

    // assertTrue(fieldMap.get("escidoc.property.created-by.name").equals("Nadine Schröder"));

    validator.compareToReferenceIndex();

    assertTrue(
        Arrays.toString(indexer.getIndexingReport().getErrorList().toArray()),
        indexer.getIndexingReport().getErrorList().size() == 0);
  }
Ejemplo n.º 4
0
  /** @param args */
  public static void main(String[] args) {

    CourseEnrollment myCourse;
    Transcript myTranscript = new Transcript();

    // temp variables
    String code, grade;
    int credits;

    System.out.println("Welcome to the transcript application.\n");

    while (myTranscript.getUserChoice().equalsIgnoreCase("y")) {
      Scanner sc = new Scanner(System.in);
      myCourse = new CourseEnrollment();
      code = Validator.validateCourseCode(sc, "Enter course:\t");
      myCourse.setCourseCode(code);

      credits = Validator.validateCredits(sc, "Enter credits:\t", 0, 4);
      myCourse.setCredits(credits);

      grade = Validator.validateGrade(sc, "Enter grade:\t");
      myCourse.setGrade(grade);

      myTranscript.addCourse(myCourse);
      myTranscript.getOverallGPA();
      System.out.print("\nAnother line item? (y/n):   ");
      myTranscript.setUserChoice(sc.next());
    }
    System.out.println("\nCourse\t    Credits\t  Grade\t  Quality Points");
    System.out.println("\n------------------------------------------------------");
    System.out.println(myTranscript);
  }
Ejemplo n.º 5
0
 /**
  * Valida un objeto a partir de un validador concreto. <br>
  * El validador debe extender la clase Validator y soportar (verificado mediante el método
  * supports) el objeto a validar. Si no, lanza una IllegalArgumentException. <br>
  * El validador puede tener anotaciones de dependencias de Spring.
  *
  * @see com.lynxspa.sdm.web.services.validation.Validator
  * @see BindingResult#hasFieldErrors()
  * @param object El objeto a validar
  * @param validator El validador a utilizar.
  * @param BindingResult El resultado de la validación, es un objeto BindingResult de Spring. Para
  *     verificar que no hay errores de validación hay que llamar al método hasFieldErrors.
  * @param result
  */
 public void validate(Object object, Validator v, BindingResult result) {
   if (!v.supports(object.getClass())) {
     throw new IllegalArgumentException(
         "Validator " + v.getClass().toString() + " does not support " + object.getClass());
   }
   v.validate(object, result);
 }
Ejemplo n.º 6
0
 Validation validate() {
   Validation validation = new Validation();
   for (Validator validator : validators()) {
     validator.validate(validation);
   }
   return validation;
 }
Ejemplo n.º 7
0
 public void processValidationResults(Validator validator) {
   List<Reason> reasons = validator.getReasons();
   if (isIgnorValidator(validator)) {
     return;
   }
   if (!validator.hasReasons(null)) {
     if (myProblems.containsKey(validator)) {
       myProblems.remove(validator);
       fireStateChanged();
     }
   } else {
     boolean needUpdateReasons = false;
     //
     if (myProblems.containsKey(validator)) {
       List<Reason> currReasons = myProblems.get(validator);
       if (!equals(currReasons, reasons)) {
         needUpdateReasons = true;
       }
     } else {
       needUpdateReasons = true;
     }
     //
     if (needUpdateReasons) {
       // It's necessary to copy reasons' list here!!!
       myProblems.put(validator, new ArrayList<Reason>(reasons));
       fireStateChanged();
     }
   }
 }
Ejemplo n.º 8
0
 public void testLegacyValidate() throws Exception {
   System.out.println("validate - Legacy");
   File licenseFile = new File("testing", "LegacyTest.lic");
   License license = LicenseIO.importLicense(licenseFile);
   Validator validator = new Validator(license, pubKey);
   validator.validate();
 }
Ejemplo n.º 9
0
 public boolean validateTmDiff(Validator forward, Validator reverse, ValidationConfig c) {
   this.tmDiff = (double) (forward.getTm() - reverse.getTm());
   if (this.tmDiff > config.tmDifference || this.tmDiff < -(config.tmDifference)) {
     this.tmFlag = true;
     return false;
   }
   return true;
 }
Ejemplo n.º 10
0
 private void logValidatorNames() {
   StringBuilder validatorNamesBuilder = new StringBuilder();
   for (Validator validator : validators) {
     validatorNamesBuilder.append("\t");
     validatorNamesBuilder.append(validator.getClass().getCanonicalName());
     validatorNamesBuilder.append("\n");
   }
   logger.debug("following validators will be executed:\n" + validatorNamesBuilder);
 }
Ejemplo n.º 11
0
 /**
  * Invoke the specified Validators, if any, with the given validation hints.
  *
  * <p>Note: Validation hints may get ignored by the actual target Validator.
  *
  * @param validationHints one or more hint objects to be passed to a {@link SmartValidator}
  * @see #setValidator(Validator)
  * @see SmartValidator#validate(Object, Errors, Object...)
  */
 public void validate(Object... validationHints) {
   for (Validator validator : getValidators()) {
     if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) {
       ((SmartValidator) validator).validate(getTarget(), getBindingResult(), validationHints);
     } else if (validator != null) {
       validator.validate(getTarget(), getBindingResult());
     }
   }
 }
Ejemplo n.º 12
0
 public boolean validate() {
   long notErrors = 0;
   for (Validator validator : validators) {
     if (validator.validate()) {
       notErrors++;
     }
   }
   return notErrors == validators.size();
 }
Ejemplo n.º 13
0
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner sc = new Scanner(System.in);
    String choice = "y";
    while (choice.equalsIgnoreCase("y")) {
      System.out.println("Enter Name:");
      String Name = sc.nextLine();
      while (!(Validator.ValidateName(Name))) {
        System.out.println("Invalid Entry.Enter a Name");
        Name = sc.nextLine();
      }

      System.out.println("Enter Age:");
      String input = sc.nextLine();
      while (!(Validator.ValidateAge(input))) {
        System.out.println("Invalid Entry.Enter Age:");
        input = sc.nextLine();
      }
      int age = Integer.parseInt(input);
      System.out.println("Enter Height in inches:");
      input = sc.nextLine();
      while (!(Validator.ValidateHeight(input))) {
        System.out.println("Invalid Entry.Enter Height:");
        input = sc.nextLine();
      }
      int height = Integer.parseInt(input);
      System.out.println("Enter Weight in lbs:");
      input = sc.nextLine();
      while (!(Validator.ValidateWeight(input))) {
        System.out.println("Invalid Entry.Enter Weight:");
        input = sc.nextLine();
      }
      int weight = Integer.parseInt(input);
      System.out.println("Enter your favourite decimal number between 0 and 1:");
      input = sc.nextLine();
      while (!(Validator.ValidateNumber(input))) {
        System.out.println("Invalid Entry.Enter a new Number:");
        input = sc.nextLine();
      }
      double num = Double.parseDouble(input);
      System.out.println(
          "Name: "
              + Name
              + "\nAge: "
              + age
              + "\nHeight: "
              + height
              + " inches\nWeight: "
              + weight
              + " lbs"
              + "\nFavorite Number: "
              + num);
      System.out.println("Do you wish to continue:(y/n)?");
      choice = sc.nextLine();
    }
    sc.close();
  }
Ejemplo n.º 14
0
 public ValidationResult getFirstError() {
   for (Validator validator : validators) {
     List<ValidationResult> errors = validator.getErrors();
     if (errors != null && !errors.isEmpty()) {
       return errors.get(0);
     }
   }
   return null;
 }
Ejemplo n.º 15
0
  public static Validator getValidator(HtmlVersion version) {
    Collection<? extends Validator> validators = Lookup.getDefault().lookupAll(Validator.class);
    for (Validator v : validators) {
      if (v.canValidate(version)) {
        return v;
      }
    }

    return null;
  }
Ejemplo n.º 16
0
 private void assertValidators(Validator... validators) {
   Assert.notNull(validators, "Validators required");
   for (Validator validator : validators) {
     if (validator != null
         && (getTarget() != null && !validator.supports(getTarget().getClass()))) {
       throw new IllegalStateException(
           "Invalid target for Validator [" + validator + "]: " + getTarget());
     }
   }
 }
Ejemplo n.º 17
0
 public static Long getId(final Object model, boolean checkValidity) {
   Long id = null;
   if (model != null) {
     if (checkValidity) {
       Validator.checkValidModel(model);
     }
     id = Validator.checkValidId(model);
   }
   return id;
 }
Ejemplo n.º 18
0
 @SuppressWarnings("unchecked")
 static void initCollections(final Object model, final Nest<?> nest) {
   if (model == null || nest == null) {
     return;
   }
   for (Field field : model.getClass().getDeclaredFields()) {
     field.setAccessible(true);
     try {
       if (field.isAnnotationPresent(CollectionList.class)) {
         Validator.checkValidCollection(field);
         List<Object> list = (List<Object>) field.get(model);
         if (list == null) {
           CollectionList annotation = field.getAnnotation(CollectionList.class);
           RedisList<Object> redisList =
               new RedisList<Object>(annotation.of(), nest, field, model);
           field.set(model, redisList);
         }
       }
       if (field.isAnnotationPresent(CollectionSet.class)) {
         Validator.checkValidCollection(field);
         Set<Object> set = (Set<Object>) field.get(model);
         if (set == null) {
           CollectionSet annotation = field.getAnnotation(CollectionSet.class);
           RedisSet<Object> redisSet = new RedisSet<Object>(annotation.of(), nest, field, model);
           field.set(model, redisSet);
         }
       }
       if (field.isAnnotationPresent(CollectionSortedSet.class)) {
         Validator.checkValidCollection(field);
         Set<Object> sortedSet = (Set<Object>) field.get(model);
         if (sortedSet == null) {
           CollectionSortedSet annotation = field.getAnnotation(CollectionSortedSet.class);
           RedisSortedSet<Object> redisSortedSet =
               new RedisSortedSet<Object>(annotation.of(), annotation.by(), nest, field, model);
           field.set(model, redisSortedSet);
         }
       }
       if (field.isAnnotationPresent(CollectionMap.class)) {
         Validator.checkValidCollection(field);
         Map<Object, Object> map = (Map<Object, Object>) field.get(model);
         if (map == null) {
           CollectionMap annotation = field.getAnnotation(CollectionMap.class);
           RedisMap<Object, Object> redisMap =
               new RedisMap<Object, Object>(
                   annotation.key(), annotation.value(), nest, field, model);
           field.set(model, redisMap);
         }
       }
     } catch (IllegalArgumentException e) {
       throw new InvalidFieldException();
     } catch (IllegalAccessException e) {
       throw new InvalidFieldException();
     }
   }
 }
Ejemplo n.º 19
0
 @Override
 public List<ValidationFailure> validate() {
   final List<ValidationFailure> result = Lists.newArrayList();
   for (Validator validator : validators) {
     final List<ValidationFailure> failures = validator.validate();
     if (failures != null && !failures.isEmpty()) {
       result.addAll(failures);
     }
   }
   return result;
 }
Ejemplo n.º 20
0
 /**
  * Called to validate the form. If an error is found, it will be displayed in the corresponding
  * field.
  *
  * @return boolean true if the form is not valid, otherwise false
  */
 public boolean validate() {
   boolean formValid = true;
   boolean asError;
   for (Validator v : mValidates) {
     asError = v.validate();
     if (asError && formValid) {
       formValid = false;
     }
   }
   return formValid;
 }
Ejemplo n.º 21
0
  public static void main(String[] args) {

    Transcript transcript = new Transcript();
    ArrayList<CourseEnrollment> alist = new ArrayList<CourseEnrollment>();

    Scanner scan = new Scanner(System.in);
    String course = "";
    int credits = 0;
    String grade = "";
    System.out.println("Welome to the Transcript Application");
    System.out.println();
    System.out.println("Do you want to enter an item?(y/n) ");
    String choice = scan.next();
    scan.nextLine();
    while (choice.equalsIgnoreCase("y")) {

      course = Validator.getString(scan, "Enter course: ");
      credits = Validator.getInt(scan, "Enter credits: ", 1, 4);

      grade = Validator.getString(scan, "Enter grade: ");

      CourseEnrollment courseenrollment = new CourseEnrollment();
      courseenrollment.setCode(course);
      courseenrollment.setCredits(credits);
      courseenrollment.setGrade(grade);

      transcript.addCourse(courseenrollment);

      alist = transcript.getCourses();

      System.out.print("Continue? (y/n): ");
      choice = scan.nextLine();
      System.out.println();
    }

    alist = transcript.getCourses();

    System.out.println("Course\t\tCredits\t\tGrade\t\tQuality Point");
    System.out.println("------\t\t-------\t\t-----\t\t-------------");

    for (CourseEnrollment print : alist) {
      System.out.println(
          print.getCode()
              + "\t"
              + print.getCredits()
              + "\t\t"
              + print.getGrade()
              + "\t\t"
              + print.getGPAgrade());

      System.out.println();
    }
    System.out.println("\t\t\t\t\tGPA\t" + transcript.getOverallGPA());
  }
Ejemplo n.º 22
0
 /** Handle being deleted by cleaning up validators and so forth. */
 public void handleDelete() {
   for (Property prop : properties.values()) {
     if (prop.getValidators() != null) {
       for (String validatorName : prop.getValidators()) {
         Validator validator = getRobotTree().getValidator(validatorName);
         if (validator != null) {
           validator.delete(this, prop.getName());
         }
       }
     }
   }
 }
 /** {@inheritDoc} */
 @Override
 public void validate(Object node, JsonPointer at, ErrorHandler handler) throws SchemaException {
   for (Validator v : validators) {
     try {
       v.validate(node, at, new FailFastErrorHandler());
       return;
     } catch (ValidationException e) {
       // Only one helpers should success to be overall success.
     }
   }
   handler.error(new ValidationException("Invalid union validators.", getPath(at, null)));
 }
Ejemplo n.º 24
0
 @Test
 public void validateWorksIfUpdateDerivedValuesWasCalled() {
   Validator v = new Validator();
   v.enqueue(
       new DummyDomainObject() {
         @Override
         public void updateDerivedValues() {
           super.updateDerivedValues();
         }
       });
   // no exception means it passed
   v.validate();
 }
Ejemplo n.º 25
0
    public boolean isValid(String value) {
      errors = new ArrayList<>();

      boolean success = true;

      for (Validator validator : validators) {
        if (!validator.isValid(value)) {
          errors.add(validator.getErrorMessage());
          success = false;
        }
      }

      return success;
    }
Ejemplo n.º 26
0
  /**
   * Validates object against a JSON schema.
   *
   * @param o object to validate.
   * @param schemaResource schema used for validation.
   * @return {@link Validator}
   */
  public static Validator validateJson(Object o, String schemaResource) {
    JsonNode json = objectToJson(o);

    JsonNode schema;
    try {
      schema = JsonLoader.fromResource(schemaResource);
      return validateJson(json, schema);
    } catch (IOException e) {
      log.info(String.format("JsonUtils.validateJson(): Unable to load schema json"));
      Validator res = new Validator();
      res.addError("jsonerror", "Unable to load schema");
      return res;
    }
  }
Ejemplo n.º 27
0
  @Test
  public void testIsValidUrl_Second_Solution() throws Exception {
    PowerMockito.mockStatic(Validator.class);

    String url = "This is not an url";
    PowerMockito.doReturn(true).when(Validator.class, "isValidUrlStatic", url);

    boolean result = Validator.isValidUrlStatic(url);
    Assert.assertTrue("Should be true", result);

    // PowerMockito.verifyStatic(Mockito.times(1));
    PowerMockito.verifyStatic(); // Same as above
    Validator.isValidUrlStatic(url);
  }
Ejemplo n.º 28
0
  @Test
  public void testIsValidUrl_First_Solution() {
    PowerMockito.mockStatic(Validator.class);

    String url = "This is not an url";
    PowerMockito.when(Validator.isValidUrlStatic(url)).thenReturn(true);

    boolean result = Validator.isValidUrlStatic(url);
    result = Validator.isValidUrlStatic(url);
    Assert.assertTrue("Should be true", result);

    PowerMockito.verifyStatic(Mockito.times(2));
    Validator.isValidUrlStatic(url);
  }
Ejemplo n.º 29
0
  /** @param args */
  public static void main(String[] args) {
    Validator errorHander;
    try {
      // File docFile = new File("src/com/amitk/xml/xsd/hello/PurchaseOrder.xml");
      String schemaFileName =
          // "PurchaseOrderSchema.xsd";
          "Order.xsd";
      String xmlFileName =
          // "PurchaseOrder.xml";
          "OrderCreate.xml";
      String nameSpace = "http://www.matson.com/milportal/schema";

      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setValidating(true);
      dbf.setNamespaceAware(true);
      dbf.setAttribute(
          "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
          "http://www.w3.org/2001/XMLSchema");
      dbf.setAttribute(
          "http://java.sun.com/xml/jaxp/properties/schemaSource",
          // nameSpace + " " +
          "http://10.8.4.118:9050/MILOrderTrackEEM/static/Order.xsd");

      /*
      parser.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
      					nameSpace + " " +
      				   //"C:\\AmitK\\work\\project\\Learning\\EclipseWorkSpace\\XML\\src\\com\\amitk\\xml\\xsd\\hello\\" + schemaFileName);
      					"http://10.8.4.118:9050/MILOrderTrackEEM/static/Order.xsd");
      */
      DocumentBuilder builder = dbf.newDocumentBuilder();
      System.out.println(
          "Document builder impl:" + builder.getDOMImplementation().getClass().getName());

      errorHander = new Validator();
      builder.setErrorHandler(errorHander);
      // parser.setProperty(name, value)ErrorHandler(errorHander);
      // parser.parse("src/com/amitk/xml/xsd/hello/" + xmlFileName, errorHander);
      builder.parse("src/com/amitk/xml/xsd/hello/" + xmlFileName);

      if (errorHander.hasErrors()) {
        // errorHander.saxParseException.printStackTrace();
        System.out.println(errorHander.getErrors());
      } else {
        System.out.println("xml file parsed successfully");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 30
0
 /**
  * Checks whether longitude and latitude is within bounds.
  *
  * @param latitude
  * @param longitude
  * @return true if both are within bounds.
  */
 public boolean isLegal(double latitude, double longitude) {
   if (Validator.validCoords(latitude, longitude)) {
     return true;
   }
   log.debug("out of bounds");
   return false;
 }