@Override public void validate(Validation validation) { validation.mustHaveNonEmptySource(DIR); validation.mustHaveIssues(DIR); validation.mustHaveSize(DIR); validation.mustHaveComments(DIR); }
static void save() { if (Http.Response.current() == null) { // Some request like WebSocket don't have any response return; } if (Validation.errors().isEmpty()) { // Only send "delete cookie" header when the cookie was present in the request if (Http.Request.current().cookies.containsKey(Scope.COOKIE_PREFIX + "_ERRORS") || !Scope.SESSION_SEND_ONLY_IF_CHANGED) { Http.Response.current().setCookie(Scope.COOKIE_PREFIX + "_ERRORS", "", "0s"); } return; } try { StringBuilder errors = new StringBuilder(); if (Validation.current() != null && Validation.current().keep) { for (Error error : Validation.errors()) { errors.append("\u0000"); errors.append(error.key); errors.append(":"); errors.append(error.message); for (String variable : error.variables) { errors.append("\u0001"); errors.append(variable); } errors.append("\u0000"); } } String errorsData = URLEncoder.encode(errors.toString(), "utf-8"); Http.Response.current().setCookie(Scope.COOKIE_PREFIX + "_ERRORS", errorsData); } catch (Exception e) { throw new UnexpectedException("Errors serializationProblem", e); } }
/** * This method finds the average distances between the partitions and parses those to the * validation object for the calculation of the column confidence. */ private void setClusterCertainties() { method: while (true) { ArrayList<Integer> totalDistances = data.get(0).getDistances(); for (Line line : data) { if (data.indexOf(line) > 0) { for (int x = 0; x < line.getDistances().size(); x++) { if (!(x >= totalDistances.size() || x >= line.getDistances().size())) { int totalDistance = totalDistances.get(x) + line.getDistances().get(x); totalDistances.set(x, totalDistance); } else { LOGGER.info( "Found a problem during the cluster certainties. I've given the table a very low confidence"); ArrayList<Integer> lowValidation = new ArrayList<Integer>(); for (int o : line.getDistances()) { lowValidation.add(0); } validation.setClusterCertainty(lowValidation, data.get(0).getDistanceThreshold()); validation.setLineThreshold(data.get(0).getDistanceThreshold()); break method; } } } } ArrayList<Integer> averageDistances = new ArrayList<Integer>(); for (int distance : totalDistances) { averageDistances.add(distance / data.size()); } validation.setClusterCertainty(averageDistances, data.get(0).getDistanceThreshold()); validation.setLineThreshold(data.get(0).getDistanceThreshold()); break method; } }
public List<ErrorMessage> getConstraintViolations() { List<ErrorMessage> allConstraintViolations = new ArrayList<>(); for (Validation<?> propertyValidator : propertyValidators) { allConstraintViolations.addAll(propertyValidator.getConstraintViolations()); } return allConstraintViolations; }
private boolean checkValidation() { boolean ret = true; if (!Validation.hasText(username)) ret = false; if (!Validation.hasText(password)) ret = false; return ret; }
public void go() throws Exception { Validation validation = validate(); if (validation.isSuccessful()) { subprocessLogger.registerAsExitHook("Following processes were alive at shutdown: "); startServer(); } else { validation.logErrors(); } }
/** * This method removes the lines that have missing data and stores them in a separate variable. * These lines might contain valuable information about the content or could be a mistake by the * OCR or separator. They need special processing in order to be useful (as done in the * addLinesWithMissingDataToColumns method). */ private void findMissingData() { ArrayList<Line> dataWithoutMissingLines = new ArrayList<Line>(); ArrayList<Line> linesWithMissingData = new ArrayList<Line>(); ArrayList<Integer> numberOfClusters = new ArrayList<Integer>(); int highestAmountOfClusters = 0; // calculating the highest amount of clusters: for (Line line : data) { numberOfClusters.add(line.getClusterSize()); if (line.getClusterSize() > highestAmountOfClusters) { highestAmountOfClusters = line.getClusterSize(); } } // calculate the highest amount of cluster occurrences: int highestAmountOfClustersOccurrences = 0; ArrayList<Integer> numberOfClustersSave = new ArrayList<Integer>(numberOfClusters); while (numberOfClusters.contains(highestAmountOfClusters)) { highestAmountOfClustersOccurrences++; numberOfClusters.remove(numberOfClusters.indexOf(highestAmountOfClusters)); } numberOfClusters = new ArrayList<Integer>(numberOfClustersSave); validation.setHighestAmountOfClustersOccurrences(highestAmountOfClustersOccurrences); if (highestAmountOfClustersOccurrences > 4) { int mostFrequentAmountOfClusters = CommonMethods.mostCommonElement(numberOfClusters); validation.setMostFrequentNumberOfClusters(mostFrequentAmountOfClusters); validation.setHighestAmountOfClusters(highestAmountOfClusters); for (Line line : data) { if (line.getClusterSize() < highestAmountOfClusters) { linesWithMissingData.add(line); } else { dataWithoutMissingLines.add(line); } } this.linesWithMissingData = linesWithMissingData; this.data = dataWithoutMissingLines; } else if (numberOfClusters.size() > 0) { int mostFrequentAmountOfClusters = CommonMethods.mostCommonElement(numberOfClusters); validation.setMostFrequentNumberOfClusters(mostFrequentAmountOfClusters); validation.setHighestAmountOfClusters(highestAmountOfClusters); for (Line line : data) { if (line.getClusterSize() < mostFrequentAmountOfClusters) { // Now we now this line got missing data linesWithMissingData.add(line); } else { dataWithoutMissingLines.add(line); } } this.linesWithMissingData = linesWithMissingData; this.data = dataWithoutMissingLines; // System.out.println("Lines without missing data: "); // for (Line line : data){ // System.out.println(line); // } } }
public void testServletBridgeLibraryIsMissing() { IWARProduct product = createBasicProduct(); Validator validator = new Validator(product); Validation validation = validator.validate(); assertFalse(validation.isValid()); ValidationError[] errors = validation.getErrors(); boolean foundServletBridgeMissing = false; for (int i = 0; i < errors.length; i++) { ValidationError error = errors[i]; String message = error.getMessage(); if (error.getType() == ValidationError.LIBRARY_MISSING && message.indexOf(SERVLETBRIDGE) != -1) { foundServletBridgeMissing = true; } } assertTrue(foundServletBridgeMissing); }
public static List<String> fromStringToList(String str, String separator) { if (!Validation.IsNullOrEmpty(str)) { String[] strArr = str.split("\\" + separator); return Arrays.asList(strArr); } else { return new ArrayList<>(); } }
private ValidationMethodSupport( PresentationModel owner, Method annotatedMethod, ResourceBundle bundle) { this.resourceBundle = bundle; Validation anno = annotatedMethod.getAnnotation(Validation.class); String message = anno.message(); boolean validWhen = anno.validWhen(); if (annotatedMethod.getParameterTypes() != null && annotatedMethod.getParameterTypes().length > 0) { throw new IllegalArgumentException( "method '" + annotatedMethod.getName() + "' must not declare any parameter when annotated with @Validation"); } if (Boolean.TYPE.isAssignableFrom(annotatedMethod.getReturnType())) { if (message == null || message.length() == 0) { // throw new IllegalArgumentException("@Validation on boolean method // '"+annotatedMethod.getName()+"' must define the message attribute"); message = getDefaultMessage(); } rule = new BooleanMethodValidationRule(validWhen, message); } else if (ValidationState.class.isAssignableFrom(annotatedMethod.getReturnType())) { if (message != null && message.length() > 0) { throw new IllegalArgumentException( "@Validation on method '" + annotatedMethod.getName() + "' must NOT define the message attribute"); } rule = new ValidationStateMethodValidationRule(); } else { throw new IllegalArgumentException( "the return type of method '" + annotatedMethod.getName() + "' must either be boolean or a ValidationState"); } this.owner = owner; this.annotatedMethod = annotatedMethod; for (int i = 0; i < anno.path().length; ++i) { Path path = Path.parse(anno.path()[i]); LOG.debug("Observing " + owner + " at " + path + "."); this.obervations.add(new ValidationTargetObservation(owner, path)); } }
/** * Diagnostic print of expression structure. The abstract expression tree is written to the * supplied output destination. */ public void explain(ExpressionPresenter out) { out.startElement("documentNode"); out.emitAttribute("validation", Validation.toString(validation)); if (getSchemaType() != null) { out.emitAttribute("type", getSchemaType().getDescription()); } content.explain(out); out.endElement(); }
private void checkForMissingRequiredBundle(final String id) throws IOException { IWARProduct product = createPlainProducttWithLibraries(); Validator validator = new Validator(product); Validation validation = validator.validate(); assertFalse(validation.isValid()); ValidationError[] errors = validation.getErrors(); boolean foundMissingBundle = false; for (int i = 0; i < errors.length && !foundMissingBundle; i++) { ValidationError error = errors[i]; if (error.getType() == ValidationError.BUNDLE_MISSING) { IProductPlugin missingBundle = (IProductPlugin) error.getCausingObject(); String message = error.getMessage(); if (missingBundle.getId().equals(id) && message.indexOf(id) != -1) { foundMissingBundle = true; } } } assertTrue(foundMissingBundle); }
public void testContainsServletBridgeLibrary() throws Exception { IWARProduct product = createBasicProduct(); IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot(); IProject project = wsRoot.getProject("warProduct"); if (!project.exists()) { project.create(null); project.open(null); } IFile jar = project.getFile(SERVLETBRIDGE + ".jar"); if (!jar.exists()) { File bridge = File.createTempFile(SERVLETBRIDGE, ".jar"); FileInputStream stream = new FileInputStream(bridge); jar.create(stream, true, null); } product.addLibrary(jar.getFullPath(), false); Validator validator = new Validator(product); Validation validation = validator.validate(); assertTrue(validation.isValid()); }
/** This method checks if the table itself is a false positive and should be flagged. */ public void checkForFalsePositive() { int almostEmptyColumns = 0; for (Column2 column : dataInColumns) { if (column.getNumberOfCells() == 1) { almostEmptyColumns += 1; } } if (almostEmptyColumns >= 2) { validation.setFalsePositive(true); } }
public static Calendar ToDate(String date) { Calendar now = Calendar.getInstance(); if (!Validation.IsNullOrEmpty(date) || date.contains("-")) { String[] arr = date.split("\\-"); if (arr.length == 3) { now.set(ToInt(arr[0]), ToInt(arr[1]) - 1, ToInt(arr[2])); } } return now; }
public void testLibrariesDoesntExist() { IWARProduct product = createBasicProduct(); String projectPath = File.separator + "test"; Path path = new Path(projectPath + File.separator + "test.jar"); product.addLibrary(path, false); Path servletBridgePath = new Path(projectPath + File.separator + SERVLETBRIDGE_JAR); product.addLibrary(servletBridgePath, false); Validator validator = new Validator(product); Validation validation = validator.validate(); assertFalse(validation.isValid()); ValidationError[] errors = validation.getErrors(); boolean testJarIsMissing = false; for (int i = 0; i < errors.length; i++) { ValidationError error = errors[i]; String message = error.getMessage(); if (error.getType() == ValidationError.LIBRARY_DOESNT_EXIST && message.indexOf("test.jar") != -1) { testJarIsMissing = true; } } assertTrue(testJarIsMissing); }
/** * This method adds lines with missing partitions to the current columns. It loops trough lines * that were flagged for containing missing data and then adds the ones to columns that they fit * in (or to columns that fit in the partition). If this fails it will also try to check if the * partition merely touches a column, although this will return a lower validation score if * successful. */ private void addLinesWithMissingDataToColumns() { ArrayList<Cell> cellsWithMissingDataAdded = new ArrayList<Cell>(); ArrayList<Column2> newDataInColumns = new ArrayList<Column2>(); for (Line line : linesWithMissingData) { ArrayList<ArrayList<Element>> clusters = line.getClusters(); for (ArrayList<Element> cluster : clusters) { for (Column2 column : dataInColumns) { if (column.fitsInColumn(Line.getClusterX1(cluster), Line.getClusterX2(cluster)) && column.columnFitsIn(Line.getClusterX1(cluster), Line.getClusterX2(cluster))) { // then we need to add this cluster to that column: newDataInColumns.remove(column); column.addCell(cluster); newDataInColumns.add(column); Cell cell = new Cell(cluster, 3, line.getLineNumber()); cellsWithMissingDataAdded.add(cell); } else if (column.fitsInColumn(Line.getClusterX1(cluster), Line.getClusterX2(cluster)) || column.columnFitsIn(Line.getClusterX1(cluster), Line.getClusterX2(cluster))) { // then we need to add this cluster to that column: newDataInColumns.remove(column); column.addCell(cluster); newDataInColumns.add(column); Cell cell = new Cell(cluster, 2, line.getLineNumber()); cellsWithMissingDataAdded.add(cell); } else if (column.touchesColumn(Line.getClusterX1(cluster), Line.getClusterX2(cluster))) { // System.out.println("CLUSTER: " + cluster + " touches: " + // column); newDataInColumns.remove(column); column.addCell(cluster); newDataInColumns.add(column); Cell cell = new Cell(cluster, 1, line.getLineNumber()); cellsWithMissingDataAdded.add(cell); } } } } validation.setCellsWithMissingDataAdded(cellsWithMissingDataAdded.size()); validation.setCellsWithMissingDataAddedScores(cellsWithMissingDataAdded); }
private void checkForBannedBundle(final String id) throws Exception { IWARProduct product = createBasicProductWithLibraries(); IProductPlugin plugin = new ProductPlugin(product.getModel()); plugin.setId(id); IProductPlugin[] plugins = new IProductPlugin[] {plugin}; product.addPlugins(plugins); Validator validator = new Validator(product); Validation validation = validator.validate(); assertFalse(validation.isValid()); ValidationError[] errors = validation.getErrors(); boolean foundBannedBundle = false; for (int i = 0; i < errors.length && !foundBannedBundle; i++) { ValidationError error = errors[i]; if (error.getType() == ValidationError.BUNDLE_BANNED) { IProductPlugin bannedPlugin = (IProductPlugin) error.getCausingObject(); String message = error.getMessage(); if (bannedPlugin.getId().equals(id) && message.indexOf(id) != -1) { foundBannedBundle = true; } } } assertTrue(foundBannedBundle); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { LOGGER.debug("Add reports rights to user"); String userId = req.getParameter("userId"); if (Validation.isInteger(userId)) { long id = Long.parseLong(userId); LOGGER.debug("Id is valid. Updating user. ID: ", id); GlobalUser user = globalUserService.getUserById(id); user.setReports(1); globalUserService.updateUser(user); } else { LOGGER.debug("User ID is not numeric. ID: ", userId); } resp.sendRedirect("usersList"); }
/** * Set the EPSG code ranges for which the coordinates should be switched * * @param codes EPSG code ranges * @throws ConfigurationException If an error occurs */ @Setting(FeatureQuerySettingsProvider.EPSG_CODES_WITH_NORTHING_FIRST) public void setEpsgCodesWithNorthingFirstAxisOrder(final String codes) throws ConfigurationException { Validation.notNullOrEmpty("EPSG Codes to switch coordinates for", codes); final String[] splitted = codes.split(";"); for (final String entry : splitted) { final String[] splittedEntry = entry.split("-"); Range r = null; if (splittedEntry.length == 1) { r = new Range(Integer.parseInt(splittedEntry[0]), Integer.parseInt(splittedEntry[0])); } else if (splittedEntry.length == 2) { r = new Range(Integer.parseInt(splittedEntry[0]), Integer.parseInt(splittedEntry[1])); } else { throw new ConfigurationException( String.format( "Invalid format of entry in '%s': %s", FeatureQuerySettingsProvider.EPSG_CODES_WITH_NORTHING_FIRST, entry)); } epsgsWithNorthingFirstAxisOrder.add(r); } }
/** * Called when user presses Login button. * * <p>Checks to see if user-entered username is an already registered user. If not, it prompts the * user to register. * * @param view view that is clicked */ public void logInUser(View view) { EditText etUsername = (EditText) findViewById(R.id.enterUsername); String username = etUsername.getText().toString().trim(); UserRegistrationController urc = new UserRegistrationController(this); userManager = new ESUserManager(""); // Try to retrieve the data. If no internet, pop up some toast to say so. if (!NetworkChecker.isNetworkAvailable(this)) { Toast.makeText( this, "No internet connection. Please check your internet connection and try again.", Toast.LENGTH_LONG) .show(); } else { if (Validation.hasText(etUsername)) { // Calls GetThreat to check if user is on server Thread thread = new GetThread(username); thread.start(); } } }
// postfix should not be null or "" boolean accessTest(String postfix, String prefix, String field, String log) throws HttpException, IOException { if (postfix == null || postfix.equals("") || postfix.equals("null")) return true; // String logon_site // int LOGON_PORT=80; String url = HelpFunctions.getUrl(prefix, postfix); // if(ur) // System.out.println("**"+url+"** "+field); String urlRegex = Validation.urlRegex; if (!Validation.regexTest(urlRegex, url, field, log)) return false; // client.getHostConfiguration().setHost(url, LOGON_PORT); try { GetMethod getMethod = new GetMethod(url); int status = client.executeMethod(getMethod); // not found the webpage if (status == 404) { Excel2Database.excel2DBLog.writeLine( "ValidTest for " + field + " : '" + postfix + "' cann't be resolved." + log); return false; } else if (status == 200) { if (errorInfoMap.keySet().contains(prefix)) { String pageContent = getMethod.getResponseBodyAsString(); String errorInfo = errorInfoMap.get(prefix); if (pageContent.contains(errorInfo)) { Excel2Database.excel2DBLog.writeLine( "ValidTest for " + field + " : '" + postfix + "' can't be resolved." + log); return false; } } } getMethod.releaseConnection(); } catch (Exception e) { // TODO: handle exception System.out.println(url); } return true; }
private ValidatorFactory() { Configuration<?> config = Validation.byDefaultProvider().configure(); final MessageInterpolator defaultMessageInterpolator = config.getDefaultMessageInterpolator(); config.messageInterpolator( new MessageInterpolator() { @Override public String interpolate(String messageTemplate, Context context) { String message; if (context.getConstraintDescriptor().getPayload() != null && context.getConstraintDescriptor().getPayload().contains(Localized.class)) { // Retrieve message from message library message = MessageUtility.getLocalizedMessage(messageTemplate).getMessage(); } else { message = defaultMessageInterpolator.interpolate(messageTemplate, context); } return message; } @Override public String interpolate(String messageTemplate, Context context, Locale locale) { String message; if (context.getConstraintDescriptor().getPayload() != null && context.getConstraintDescriptor().getPayload().contains(Localized.class)) { // Retrieve message from message library message = MessageUtility.getLocalizedMessage(messageTemplate, locale).getMessage(); } else { message = defaultMessageInterpolator.interpolate(messageTemplate, context); } return message; } }); // Stop validation if Entity action is DELETE config.traversableResolver( new TraversableResolver() { @Override public boolean isReachable( Object traversableObject, Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) { if (traversableObject != null && AbstractBindingBean.class.isAssignableFrom(traversableObject.getClass())) { AbstractBindingBean bean = (AbstractBindingBean) traversableObject; if (bean.getEntityAction() != null && bean.getEntityAction() == EntityAction.DELETE) { return false; } } return true; } @Override public boolean isCascadable( Object traversableObject, Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) { return true; } }); javax.validation.ValidatorFactory factory = config.buildValidatorFactory(); validator = factory.getValidator(); }
public void prepareAttributes() throws XPathException { AttributeCollection atts = getAttributeList(); String nameAtt = null; String namespaceAtt = null; String selectAtt = null; String separatorAtt = null; String validationAtt = null; String typeAtt = null; for (int a = 0; a < atts.getLength(); a++) { int nc = atts.getNameCode(a); String f = getNamePool().getClarkName(nc); if (f == StandardNames.NAME) { nameAtt = Whitespace.trim(atts.getValue(a)); } else if (f == StandardNames.NAMESPACE) { namespaceAtt = Whitespace.trim(atts.getValue(a)); } else if (f == StandardNames.SELECT) { selectAtt = atts.getValue(a); } else if (f == StandardNames.SEPARATOR) { separatorAtt = atts.getValue(a); } else if (f == StandardNames.VALIDATION) { validationAtt = Whitespace.trim(atts.getValue(a)); } else if (f == StandardNames.TYPE) { typeAtt = Whitespace.trim(atts.getValue(a)); } else { checkUnknownAttribute(nc); } } if (nameAtt == null) { reportAbsence("name"); return; } attributeName = makeAttributeValueTemplate(nameAtt); if (attributeName instanceof StringLiteral) { if (!getConfiguration() .getNameChecker() .isQName(((StringLiteral) attributeName).getStringValue())) { invalidAttributeName("Attribute name " + Err.wrap(nameAtt) + " is not a valid QName"); } if (nameAtt.equals("xmlns")) { if (namespace == null) { invalidAttributeName("Invalid attribute name: xmlns"); } } if (nameAtt.startsWith("xmlns:")) { if (namespaceAtt == null) { invalidAttributeName("Invalid attribute name: " + Err.wrap(nameAtt)); } else { // ignore the prefix "xmlns" nameAtt = nameAtt.substring(6); attributeName = new StringLiteral(nameAtt); } } } if (namespaceAtt != null) { namespace = makeAttributeValueTemplate(namespaceAtt); if (namespace instanceof StringLiteral) { if (!AnyURIValue.isValidURI(((StringLiteral) namespace).getStringValue())) { compileError("The value of the namespace attribute must be a valid URI", "XTDE0865"); } } } if (selectAtt != null) { select = makeExpression(selectAtt); } if (separatorAtt == null) { if (selectAtt == null) { separator = new StringLiteral(StringValue.EMPTY_STRING); } else { separator = new StringLiteral(StringValue.SINGLE_SPACE); } } else { separator = makeAttributeValueTemplate(separatorAtt); } if (validationAtt != null) { validationAction = Validation.getCode(validationAtt); if (validationAction != Validation.STRIP && !getExecutable().isSchemaAware()) { validationAction = Validation.STRIP; compileError("To perform validation, a schema-aware XSLT processor is needed", "XTSE1660"); } if (validationAction == Validation.INVALID) { compileError("Invalid value of validation attribute", "XTSE0020"); validationAction = getContainingStylesheet().getDefaultValidation(); } } else { validationAction = getContainingStylesheet().getDefaultValidation(); } if (typeAtt != null) { if (!getExecutable().isSchemaAware()) { compileError( "The @type attribute is available only with a schema-aware XSLT processor", "XTSE1660"); } else { SchemaType type = getSchemaType(typeAtt); if (type == null) { compileError("Unknown attribute type " + typeAtt, "XTSE1520"); } else { if (type.isSimpleType()) { schemaType = (SimpleType) type; } else { compileError("Type annotation for attributes must be a simple type", "XTSE1530"); type = null; } } validationAction = Validation.BY_TYPE; } } if (typeAtt != null && validationAtt != null) { compileError("The validation and type attributes are mutually exclusive", "XTSE1505"); validationAction = getContainingStylesheet().getDefaultValidation(); schemaType = null; } }
public class QueryParser { private static final Logger logger = LoggerFactory.getLogger(QueryParser.class); private static final Validator VALIDATOR = Validation.byProvider(ApacheValidationProvider.class) .configure() .buildValidatorFactory() .getValidator(); private AggregatorFactory m_aggregatorFactory; private QueryPluginFactory m_pluginFactory; private GroupByFactory m_groupByFactory; private Map<Class, Map<String, PropertyDescriptor>> m_descriptorMap; private final Object m_descriptorMapLock = new Object(); private Gson m_gson; @Inject public QueryParser( AggregatorFactory aggregatorFactory, GroupByFactory groupByFactory, QueryPluginFactory pluginFactory) { m_aggregatorFactory = aggregatorFactory; m_groupByFactory = groupByFactory; m_pluginFactory = pluginFactory; m_descriptorMap = new HashMap<Class, Map<String, PropertyDescriptor>>(); GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapterFactory(new LowercaseEnumTypeAdapterFactory()); builder.registerTypeAdapter(TimeUnit.class, new TimeUnitDeserializer()); builder.registerTypeAdapter(DateTimeZone.class, new DateTimeZoneDeserializer()); builder.registerTypeAdapter(Metric.class, new MetricDeserializer()); builder.registerTypeAdapter(SetMultimap.class, new SetMultimapDeserializer()); builder.registerTypeAdapter(RelativeTime.class, new RelativeTimeSerializer()); builder.registerTypeAdapter(SetMultimap.class, new SetMultimapSerializer()); builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); m_gson = builder.create(); } public Gson getGson() { return m_gson; } private PropertyDescriptor getPropertyDescriptor(Class objClass, String property) throws IntrospectionException { synchronized (m_descriptorMapLock) { Map<String, PropertyDescriptor> propMap = m_descriptorMap.get(objClass); if (propMap == null) { propMap = new HashMap<String, PropertyDescriptor>(); m_descriptorMap.put(objClass, propMap); BeanInfo beanInfo = Introspector.getBeanInfo(objClass); PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor descriptor : descriptors) { propMap.put(getUnderscorePropertyName(descriptor.getName()), descriptor); } } return (propMap.get(property)); } } public static String getUnderscorePropertyName(String camelCaseName) { StringBuilder sb = new StringBuilder(); for (char c : camelCaseName.toCharArray()) { if (Character.isUpperCase(c)) sb.append('_').append(Character.toLowerCase(c)); else sb.append(c); } return (sb.toString()); } private void validateObject(Object object) throws BeanValidationException { validateObject(object, null); } private void validateObject(Object object, String context) throws BeanValidationException { // validate object using the bean validation framework Set<ConstraintViolation<Object>> violations = VALIDATOR.validate(object); if (!violations.isEmpty()) { throw new BeanValidationException(violations, context); } } public List<QueryMetric> parseQueryMetric(String json) throws QueryException, BeanValidationException { JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(json).getAsJsonObject(); return parseQueryMetric(obj); } private List<QueryMetric> parseQueryMetric(JsonObject obj) throws QueryException, BeanValidationException { return parseQueryMetric(obj, ""); } private List<QueryMetric> parseQueryMetric(JsonObject obj, String contextPrefix) throws QueryException, BeanValidationException { List<QueryMetric> ret = new ArrayList<QueryMetric>(); Query query; try { query = m_gson.fromJson(obj, Query.class); validateObject(query); } catch (ContextualJsonSyntaxException e) { throw new BeanValidationException( new SimpleConstraintViolation(e.getContext(), e.getMessage()), "query"); } JsonArray metricsArray = obj.getAsJsonArray("metrics"); if (metricsArray == null) { throw new BeanValidationException( new SimpleConstraintViolation("metric[]", "must have a size of at least 1"), contextPrefix + "query"); } for (int I = 0; I < metricsArray.size(); I++) { String context = (!contextPrefix.isEmpty() ? contextPrefix + "." : contextPrefix) + "query.metric[" + I + "]"; try { Metric metric = m_gson.fromJson(metricsArray.get(I), Metric.class); validateObject(metric, context); long startTime = getStartTime(query, context); QueryMetric queryMetric = new QueryMetric(startTime, query.getCacheTime(), metric.getName()); queryMetric.setExcludeTags(metric.isExcludeTags()); queryMetric.setLimit(metric.getLimit()); long endTime = getEndTime(query); if (endTime > -1) queryMetric.setEndTime(endTime); if (queryMetric.getEndTime() < startTime) throw new BeanValidationException( new SimpleConstraintViolation("end_time", "must be greater than the start time"), context); queryMetric.setCacheString(query.getCacheString() + metric.getCacheString()); JsonObject jsMetric = metricsArray.get(I).getAsJsonObject(); JsonElement group_by = jsMetric.get("group_by"); if (group_by != null) { JsonArray groupBys = group_by.getAsJsonArray(); parseGroupBy(context, queryMetric, groupBys); } JsonElement aggregators = jsMetric.get("aggregators"); if (aggregators != null) { JsonArray asJsonArray = aggregators.getAsJsonArray(); if (asJsonArray.size() > 0) parseAggregators(context, queryMetric, asJsonArray, query.getTimeZone()); } JsonElement plugins = jsMetric.get("plugins"); if (plugins != null) { JsonArray pluginArray = plugins.getAsJsonArray(); if (pluginArray.size() > 0) parsePlugins(context, queryMetric, pluginArray); } JsonElement order = jsMetric.get("order"); if (order != null) queryMetric.setOrder(Order.fromString(order.getAsString(), context)); queryMetric.setTags(metric.getTags()); ret.add(queryMetric); } catch (ContextualJsonSyntaxException e) { throw new BeanValidationException( new SimpleConstraintViolation(e.getContext(), e.getMessage()), context); } } return (ret); } public List<RollupTask> parseRollupTasks(String json) throws BeanValidationException, QueryException { List<RollupTask> tasks = new ArrayList<RollupTask>(); JsonParser parser = new JsonParser(); JsonArray rollupTasks = parser.parse(json).getAsJsonArray(); for (int i = 0; i < rollupTasks.size(); i++) { JsonObject taskObject = rollupTasks.get(i).getAsJsonObject(); RollupTask task = parseRollupTask(taskObject, "tasks[" + i + "]"); task.addJson(taskObject.toString().replaceAll("\\n", "")); tasks.add(task); } return tasks; } public RollupTask parseRollupTask(String json) throws BeanValidationException, QueryException { JsonParser parser = new JsonParser(); JsonObject taskObject = parser.parse(json).getAsJsonObject(); RollupTask task = parseRollupTask(taskObject, ""); task.addJson(taskObject.toString().replaceAll("\\n", "")); return task; } public RollupTask parseRollupTask(JsonObject rollupTask, String context) throws BeanValidationException, QueryException { RollupTask task = m_gson.fromJson(rollupTask.getAsJsonObject(), RollupTask.class); validateObject(task); JsonArray rollups = rollupTask.getAsJsonObject().getAsJsonArray("rollups"); if (rollups != null) { for (int j = 0; j < rollups.size(); j++) { JsonObject rollupObject = rollups.get(j).getAsJsonObject(); Rollup rollup = m_gson.fromJson(rollupObject, Rollup.class); context = context + "rollup[" + j + "]"; validateObject(rollup, context); JsonObject queryObject = rollupObject.getAsJsonObject("query"); List<QueryMetric> queries = parseQueryMetric(queryObject, context); for (int k = 0; k < queries.size(); k++) { QueryMetric query = queries.get(k); context += ".query[" + k + "]"; validateHasRangeAggregator(query, context); // Add aggregators needed for rollups SaveAsAggregator saveAsAggregator = (SaveAsAggregator) m_aggregatorFactory.createAggregator("save_as"); saveAsAggregator.setMetricName(rollup.getSaveAs()); TrimAggregator trimAggregator = (TrimAggregator) m_aggregatorFactory.createAggregator("trim"); trimAggregator.setTrim(TrimAggregator.Trim.LAST); query.addAggregator(saveAsAggregator); query.addAggregator(trimAggregator); } rollup.addQueries(queries); task.addRollup(rollup); } } return task; } private void validateHasRangeAggregator(QueryMetric query, String context) throws BeanValidationException { boolean hasRangeAggregator = false; for (Aggregator aggregator : query.getAggregators()) { if (aggregator instanceof RangeAggregator) { hasRangeAggregator = true; break; } } if (!hasRangeAggregator) { throw new BeanValidationException( new SimpleConstraintViolation( "aggregator", "At least one aggregator must be a range aggregator"), context); } } private void parsePlugins(String context, QueryMetric queryMetric, JsonArray plugins) throws BeanValidationException, QueryException { for (int I = 0; I < plugins.size(); I++) { JsonObject pluginJson = plugins.get(I).getAsJsonObject(); JsonElement name = pluginJson.get("name"); if (name == null || name.getAsString().isEmpty()) throw new BeanValidationException( new SimpleConstraintViolation("plugins[" + I + "]", "must have a name"), context); String pluginContext = context + ".plugins[" + I + "]"; String pluginName = name.getAsString(); QueryPlugin plugin = m_pluginFactory.createQueryPlugin(pluginName); if (plugin == null) throw new BeanValidationException( new SimpleConstraintViolation(pluginName, "invalid query plugin name"), pluginContext); deserializeProperties(pluginContext, pluginJson, pluginName, plugin); validateObject(plugin, pluginContext); queryMetric.addPlugin(plugin); } } private void parseAggregators( String context, QueryMetric queryMetric, JsonArray aggregators, DateTimeZone timeZone) throws QueryException, BeanValidationException { for (int J = 0; J < aggregators.size(); J++) { JsonObject jsAggregator = aggregators.get(J).getAsJsonObject(); JsonElement name = jsAggregator.get("name"); if (name == null || name.getAsString().isEmpty()) throw new BeanValidationException( new SimpleConstraintViolation("aggregators[" + J + "]", "must have a name"), context); String aggContext = context + ".aggregators[" + J + "]"; String aggName = name.getAsString(); Aggregator aggregator = m_aggregatorFactory.createAggregator(aggName); if (aggregator == null) throw new BeanValidationException( new SimpleConstraintViolation(aggName, "invalid aggregator name"), aggContext); // If it is a range aggregator we will default the start time to // the start of the query. if (aggregator instanceof RangeAggregator) { RangeAggregator ra = (RangeAggregator) aggregator; ra.setStartTime(queryMetric.getStartTime()); } if (aggregator instanceof TimezoneAware) { TimezoneAware ta = (TimezoneAware) aggregator; ta.setTimeZone(timeZone); } if (aggregator instanceof GroupByAware) { GroupByAware groupByAware = (GroupByAware) aggregator; groupByAware.setGroupBys(queryMetric.getGroupBys()); } deserializeProperties(aggContext, jsAggregator, aggName, aggregator); validateObject(aggregator, aggContext); queryMetric.addAggregator(aggregator); } } private void parseGroupBy(String context, QueryMetric queryMetric, JsonArray groupBys) throws QueryException, BeanValidationException { for (int J = 0; J < groupBys.size(); J++) { String groupContext = "group_by[" + J + "]"; JsonObject jsGroupBy = groupBys.get(J).getAsJsonObject(); JsonElement nameElement = jsGroupBy.get("name"); if (nameElement == null || nameElement.getAsString().isEmpty()) throw new BeanValidationException( new SimpleConstraintViolation(groupContext, "must have a name"), context); String name = nameElement.getAsString(); GroupBy groupBy = m_groupByFactory.createGroupBy(name); if (groupBy == null) throw new BeanValidationException( new SimpleConstraintViolation(groupContext + "." + name, "invalid group_by name"), context); deserializeProperties(context + "." + groupContext, jsGroupBy, name, groupBy); validateObject(groupBy, context + "." + groupContext); groupBy.setStartDate(queryMetric.getStartTime()); queryMetric.addGroupBy(groupBy); } } private void deserializeProperties( String context, JsonObject jsonObject, String name, Object object) throws QueryException, BeanValidationException { Set<Map.Entry<String, JsonElement>> props = jsonObject.entrySet(); for (Map.Entry<String, JsonElement> prop : props) { String property = prop.getKey(); if (property.equals("name")) continue; PropertyDescriptor pd = null; try { pd = getPropertyDescriptor(object.getClass(), property); } catch (IntrospectionException e) { logger.error("Introspection error on " + object.getClass(), e); } if (pd == null) { String msg = "Property '" + property + "' was specified for object '" + name + "' but no matching setter was found on '" + object.getClass() + "'"; throw new QueryException(msg); } Class propClass = pd.getPropertyType(); Object propValue; try { propValue = m_gson.fromJson(prop.getValue(), propClass); validateObject(propValue, context + "." + property); } catch (ContextualJsonSyntaxException e) { throw new BeanValidationException( new SimpleConstraintViolation(e.getContext(), e.getMessage()), context); } catch (NumberFormatException e) { throw new BeanValidationException( new SimpleConstraintViolation(property, e.getMessage()), context); } Method method = pd.getWriteMethod(); if (method == null) { String msg = "Property '" + property + "' was specified for object '" + name + "' but no matching setter was found on '" + object.getClass().getName() + "'"; throw new QueryException(msg); } try { method.invoke(object, propValue); } catch (Exception e) { logger.error("Invocation error: ", e); String msg = "Call to " + object.getClass().getName() + ":" + method.getName() + " failed with message: " + e.getMessage(); throw new QueryException(msg); } } } private long getStartTime(Query request, String context) throws BeanValidationException { if (request.getStartAbsolute() != null) { return request.getStartAbsolute(); } else if (request.getStartRelative() != null) { return request.getStartRelative().getTimeRelativeTo(System.currentTimeMillis()); } else { throw new BeanValidationException( new SimpleConstraintViolation("start_time", "relative or absolute time must be set"), context); } } private long getEndTime(Query request) { if (request.getEndAbsolute() != null) return request.getEndAbsolute(); else if (request.getEndRelative() != null) return request.getEndRelative().getTimeRelativeTo(System.currentTimeMillis()); return -1; } // =========================================================================== private static class Metric { @NotNull @NotEmpty() @SerializedName("name") private String name; @SerializedName("tags") private SetMultimap<String, String> tags; @SerializedName("exclude_tags") private boolean exclude_tags; @SerializedName("limit") private int limit; public Metric(String name, boolean exclude_tags, TreeMultimap<String, String> tags) { this.name = name; this.tags = tags; this.exclude_tags = exclude_tags; this.limit = 0; } public String getName() { return name; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } private boolean isExcludeTags() { return exclude_tags; } public String getCacheString() { StringBuilder sb = new StringBuilder(); sb.append(name).append(":"); for (Map.Entry<String, String> tagEntry : tags.entries()) { sb.append(tagEntry.getKey()).append("="); sb.append(tagEntry.getValue()).append(":"); } return (sb.toString()); } public SetMultimap<String, String> getTags() { if (tags != null) { return tags; } else { return HashMultimap.create(); } } } // =========================================================================== private static class Query { @SerializedName("start_absolute") private Long m_startAbsolute; @SerializedName("end_absolute") private Long m_endAbsolute; @Min(0) @SerializedName("cache_time") private int cache_time; @Valid @SerializedName("start_relative") private RelativeTime start_relative; @Valid @SerializedName("end_relative") private RelativeTime end_relative; @Valid @SerializedName("time_zone") private DateTimeZone m_timeZone; // = DateTimeZone.UTC;; public Long getStartAbsolute() { return m_startAbsolute; } public Long getEndAbsolute() { return m_endAbsolute; } public int getCacheTime() { return cache_time; } public RelativeTime getStartRelative() { return start_relative; } public RelativeTime getEndRelative() { return end_relative; } public DateTimeZone getTimeZone() { return m_timeZone; } public String getCacheString() { StringBuilder sb = new StringBuilder(); if (m_startAbsolute != null) sb.append(m_startAbsolute).append(":"); if (start_relative != null) sb.append(start_relative.toString()).append(":"); if (m_endAbsolute != null) sb.append(m_endAbsolute).append(":"); if (end_relative != null) sb.append(end_relative.toString()).append(":"); return (sb.toString()); } @Override public String toString() { return "Query{" + "startAbsolute='" + m_startAbsolute + '\'' + ", endAbsolute='" + m_endAbsolute + '\'' + ", cache_time=" + cache_time + ", startRelative=" + start_relative + ", endRelative=" + end_relative + '}'; } } // =========================================================================== private static class LowercaseEnumTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { @SuppressWarnings("unchecked") Class<T> rawType = (Class<T>) type.getRawType(); if (!rawType.isEnum()) { return null; } final Map<String, T> lowercaseToConstant = new HashMap<String, T>(); for (T constant : rawType.getEnumConstants()) { lowercaseToConstant.put(toLowercase(constant), constant); } return new TypeAdapter<T>() { public void write(JsonWriter out, T value) throws IOException { if (value == null) { out.nullValue(); } else { out.value(toLowercase(value)); } } public T read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } else { return lowercaseToConstant.get(reader.nextString()); } } }; } private String toLowercase(Object o) { return o.toString().toLowerCase(Locale.US); } } // =========================================================================== private class TimeUnitDeserializer implements JsonDeserializer<TimeUnit> { public TimeUnit deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { String unit = json.getAsString(); TimeUnit tu; try { tu = TimeUnit.from(unit); } catch (IllegalArgumentException e) { throw new ContextualJsonSyntaxException( unit, "is not a valid time unit, must be one of " + TimeUnit.toValueNames()); } return tu; } } // =========================================================================== private class DateTimeZoneDeserializer implements JsonDeserializer<DateTimeZone> { public DateTimeZone deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (json.isJsonNull()) return null; String tz = json.getAsString(); if (tz.isEmpty()) // defaults to UTC return DateTimeZone.UTC; DateTimeZone timeZone; try { // check if time zone is valid timeZone = DateTimeZone.forID(tz); } catch (IllegalArgumentException e) { throw new ContextualJsonSyntaxException( tz, "is not a valid time zone, must be one of " + DateTimeZone.getAvailableIDs()); } return timeZone; } } // =========================================================================== private class MetricDeserializer implements JsonDeserializer<Metric> { @Override public Metric deserialize( JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject jsonObject = jsonElement.getAsJsonObject(); String name = null; if (jsonObject.get("name") != null) name = jsonObject.get("name").getAsString(); boolean exclude_tags = false; if (jsonObject.get("exclude_tags") != null) exclude_tags = jsonObject.get("exclude_tags").getAsBoolean(); TreeMultimap<String, String> tags = TreeMultimap.create(); JsonElement jeTags = jsonObject.get("tags"); if (jeTags != null) { JsonObject joTags = jeTags.getAsJsonObject(); int count = 0; for (Map.Entry<String, JsonElement> tagEntry : joTags.entrySet()) { String context = "tags[" + count + "]"; if (tagEntry.getKey().isEmpty()) throw new ContextualJsonSyntaxException(context, "name must not be empty"); if (tagEntry.getValue().isJsonArray()) { for (JsonElement element : tagEntry.getValue().getAsJsonArray()) { if (element.isJsonNull() || element.getAsString().isEmpty()) throw new ContextualJsonSyntaxException( context + "." + tagEntry.getKey(), "value must not be null or empty"); tags.put(tagEntry.getKey(), element.getAsString()); } } else { if (tagEntry.getValue().isJsonNull() || tagEntry.getValue().getAsString().isEmpty()) throw new ContextualJsonSyntaxException( context + "." + tagEntry.getKey(), "value must not be null or empty"); tags.put(tagEntry.getKey(), tagEntry.getValue().getAsString()); } count++; } } Metric ret = new Metric(name, exclude_tags, tags); JsonElement limit = jsonObject.get("limit"); if (limit != null) ret.setLimit(limit.getAsInt()); return (ret); } } // =========================================================================== private static class ContextualJsonSyntaxException extends RuntimeException { private String context; private ContextualJsonSyntaxException(String context, String msg) { super(msg); this.context = context; } private String getContext() { return context; } } // =========================================================================== public static class SimpleConstraintViolation implements ConstraintViolation<Object> { private String message; private String context; public SimpleConstraintViolation(String context, String message) { this.message = message; this.context = context; } @Override public String getMessage() { return message; } @Override public String getMessageTemplate() { return null; } @Override public Object getRootBean() { return null; } @Override public Class<Object> getRootBeanClass() { return null; } @Override public Object getLeafBean() { return null; } @Override public Path getPropertyPath() { return new SimplePath(context); } @Override public Object getInvalidValue() { return null; } @Override public ConstraintDescriptor<?> getConstraintDescriptor() { return null; } } private static class SimplePath implements Path { private String context; private SimplePath(String context) { this.context = context; } @Override public Iterator<Node> iterator() { return null; } @Override public String toString() { return context; } } }
/** * Cassandra implementation of the user repository. * * @author Julien Dubois */ @Repository public class CassandraUserRepository implements UserRepository { private final Log log = LogFactory.getLog(CassandraUserRepository.class); @Inject private EntityManagerImpl em; @Inject private Keyspace keyspaceOperator; @Inject private CounterRepository counterRepository; private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); private static Validator validator = factory.getValidator(); @Override @CacheEvict(value = "user-cache", key = "#user.login") public void createUser(User user) { if (log.isDebugEnabled()) { log.debug("Creating user : "******"user-cache", key = "#user.login", beforeInvocation = true) public void updateUser(User user) throws ConstraintViolationException, IllegalArgumentException { if (log.isDebugEnabled()) { log.debug("Updating user : "******"user-cache", key = "#user.login") public void deleteUser(User user) { if (log.isDebugEnabled()) { log.debug("Deleting user : "******"user-cache") public User findUserByLogin(String login) { User user = null; try { user = em.find(User.class, login); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Exception while looking for user " + login + " : " + e.toString()); } return null; } if (user != null) { user.setStatusCount(counterRepository.getStatusCounter(login)); user.setFollowersCount(counterRepository.getFollowersCounter(login)); user.setFriendsCount(counterRepository.getFriendsCounter(login)); } return user; } }
@BeforeClass public static void init() { vf = Validation.buildDefaultValidatorFactory(); validator = vf.getValidator(); }
/** * Set default response 3D EPSG code from settings * * @param epsgCode3D 3D EPSG code from settings * @throws ConfigurationException If an error occurs */ @Setting(FeatureQuerySettingsProvider.DEFAULT_RESPONSE_3D_EPSG) public void setDefaultResponse3DEpsg(final int epsgCode3D) throws ConfigurationException { Validation.greaterZero("Storage 3D EPSG Code", epsgCode3D); defaultResponse3DEPSG = epsgCode3D; addToSupportedCrs(epsgCode3D); }
public void testLibrariesExist() throws Exception { IWARProduct product = createBasicProductWithLibraries(); Validator validator = new Validator(product); Validation validation = validator.validate(); assertTrue(validation.isValid()); }
@Setting(FeatureQuerySettingsProvider.AUTHORITY) public void setAuthority(final String authority) { Validation.notNull("The CRS authority", authority); this.authority = authority; }