Java Examples for javax.validation.constraints.NotNull
The following java examples will help you to understand the usage of javax.validation.constraints.NotNull. These source code samples are taken from different open source projects.
Example 1
| Project: actframework-master File: FindBy.java View source code |
@Override
protected void initialized() {
App app = App.instance();
rawType = spec.rawType();
notNull = spec.hasAnnotation(NotNull.class);
findOne = !(Collection.class.isAssignableFrom(rawType));
dao = app.dbServiceManager().dao(findOne ? rawType : (Class) spec.typeParams().get(0));
byId = (Boolean) options.get("byId");
resolver = app.resolverManager().resolver(byId ? dao.idType() : (Class) options.get("fieldType"));
if (null == resolver) {
throw new IllegalArgumentException("Cannot find String value resolver for type: " + dao.idType());
}
bindName = S.string(value());
if (S.blank(bindName)) {
bindName = ParamValueLoaderService.bindName(spec);
}
if (!byId) {
querySpec = S.string(options.get("value"));
if (S.blank(querySpec)) {
querySpec = bindName;
}
}
}Example 2
| Project: hot-reload-master File: FindBy.java View source code |
@Override
protected void initialized() {
App app = App.instance();
rawType = spec.rawType();
notNull = spec.hasAnnotation(NotNull.class);
findOne = !(Collection.class.isAssignableFrom(rawType));
dao = app.dbServiceManager().dao(findOne ? rawType : (Class) spec.typeParams().get(0));
byId = (Boolean) options.get("byId");
resolver = app.resolverManager().resolver(byId ? dao.idType() : (Class) options.get("fieldType"));
if (null == resolver) {
throw new IllegalArgumentException("Cannot find String value resolver for type: " + dao.idType());
}
bindName = S.string(value());
if (S.blank(bindName)) {
bindName = ParamValueLoaderService.bindName(spec);
}
if (!byId) {
querySpec = S.string(options.get("value"));
if (S.blank(querySpec)) {
querySpec = bindName;
}
}
}Example 3
| Project: aesop-master File: MapCodec.java View source code |
public byte[] encode(@NotNull Map<String, Object> object) throws IOException {
if (object == null) {
return null;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(object);
oos.flush();
} catch (IOException ex) {
throw new IllegalArgumentException("Failed to serialize object of type: " + object.getClass(), ex);
}
return baos.toByteArray();
}Example 4
| Project: chancery-master File: S3Archiver.java View source code |
@Override
protected void handleCallback(@NotNull CallbackPayload callbackPayload) throws Exception {
final String key = keyTemplate.evaluateForPayload(callbackPayload);
if (callbackPayload.isDeleted())
delete(key);
else {
final Path path;
final String hash = callbackPayload.getAfter();
final String owner = callbackPayload.getRepository().getOwner().getName();
final String repoName = callbackPayload.getRepository().getName();
path = ghClient.download(owner, repoName, hash);
upload(path.toFile(), key, callbackPayload);
try {
Files.delete(path);
} catch (IOException e) {
log.warn("Couldn't delete {}", path, e);
}
}
}Example 5
| Project: che-master File: SshKeyManagerPresenter.java View source code |
/**
* Remove failed key.
*
* @param key
* failed key
*/
private void removeFailedKey(@NotNull final SshPairDto key) {
service.deletePair(key.getService(), key.getName()).then(new Operation<Void>() {
@Override
public void apply(Void arg) throws OperationException {
refreshKeys();
}
}).catchError(new Operation<PromiseError>() {
@Override
public void apply(PromiseError arg) throws OperationException {
notificationManager.notify(constant.deleteSshKeyFailed(), FAIL, FLOAT_MODE);
refreshKeys();
}
});
}Example 6
| Project: DevTools-master File: SshKeyManagerPresenter.java View source code |
/**
* Remove failed key.
*
* @param key
* failed key
*/
private void removeFailedKey(@NotNull final SshPairDto key) {
service.deletePair(key.getService(), key.getName()).then(new Operation<Void>() {
@Override
public void apply(Void arg) throws OperationException {
refreshKeys();
}
}).catchError(new Operation<PromiseError>() {
@Override
public void apply(PromiseError arg) throws OperationException {
notificationManager.notify(constant.deleteSshKeyFailed(), FAIL, FLOAT_MODE);
refreshKeys();
}
});
}Example 7
| Project: dynamodb-connector-master File: TableSteps.java View source code |
@Given("I have a repository that is $state")
@Then("I have a repository that is $state")
public void haveRepository(@NotNull String state) {
try {
RepositoryFlows repositoryFlows = new RepositoryFlows();
repositoryFlows.stateShouldBe(state);
} catch (Exception e) {
String msg = "Failed to determine if the repository is " + state + ": " + e.getCause() + ", " + e.getMessage();
LOG.error(msg);
Assert.fail(msg);
}
}Example 8
| Project: ipt-master File: ResourceUtils.java View source code |
/** * Reconstruct published version, using version's Eml file, version history, etc. * * @param version version to assign to reconstructed resource * @param shortname shortname to assign to reconstructed resource * @param doi DOI to assign to reconstructed resource * @param organisation organisation to assign to reconstructed resource * @param versionHistory VersionHistory corresponding to resource version being reconstructed * @param versionEmlFile eml file corresponding to version of resource being reconstructed * @param key GBIF UUID to assign to reconstructed resource * * @return published version reconstructed */ public static Resource reconstructVersion(@NotNull BigDecimal version, @NotNull String shortname, @Nullable DOI doi, @Nullable Organisation organisation, @Nullable VersionHistory versionHistory, @Nullable File versionEmlFile, @Nullable UUID key) { Preconditions.checkNotNull(version); Preconditions.checkNotNull(shortname); if (organisation == null || versionHistory == null || versionEmlFile == null) { throw new IllegalArgumentException("Failed to reconstruct resource version because not all of organisation, version history, or version eml file were provided"); } // initiate new version, and set properties Resource resource = new Resource(); resource.setShortname(shortname); resource.setEmlVersion(version); resource.setDoi(doi); resource.setOrganisation(organisation); resource.setKey(key); resource.setStatus(versionHistory.getPublicationStatus()); resource.setIdentifierStatus(versionHistory.getStatus()); resource.setRecordsPublished(versionHistory.getRecordsPublished()); resource.setLastPublished(versionHistory.getReleased()); resource.setRecordsByExtension(versionHistory.getRecordsByExtension()); if (versionEmlFile.exists()) { Eml eml = EmlUtils.loadWithLocale(versionEmlFile, Locale.US); resource.setEml(eml); } else { throw new IllegalArgumentException("Failed to reconstruct resource: " + versionEmlFile.getAbsolutePath() + " not found!"); } return resource; }
Example 9
| Project: konik-master File: InvoiceTaxCompleter.java View source code |
@Override
public Invoice correct(@NotNull Invoice invoice) {
if (invoice != null && invoice.getTrade() != null && invoice.getTrade().getItems() != null) {
Trade trade = invoice.getTrade();
for (Item item : trade.getItems()) {
SpecifiedSettlement settlement = item.getSettlement();
if (settlement.getMonetarySummation() != null) {
Amount lineTotal = settlement.getMonetarySummation().getLineTotal();
if (lineTotal != null) {
if (settlement.getTradeTax() != null) {
for (ItemTax tax : settlement.getTradeTax()) {
if (tax.getPercentage() != null) {
BigDecimal value = lineTotal.getValue();
BigDecimal calculated = value.multiply(tax.getPercentage().divide(BigDecimal.valueOf(100))).setScale(2, RoundingMode.HALF_UP);
tax.setCalculated(new Amount(calculated, lineTotal.getCurrency()));
} else {
tax.setCalculated(Amounts.zero(lineTotal.getCurrency()));
}
}
}
} else {
if (settlement.getTradeTax() != null) {
settlement.getTradeTax().clear();
}
}
}
}
}
return invoice;
}Example 10
| Project: magma-master File: BinaryVariableSummary.java View source code |
private void add(@NotNull ValueTable table, @NotNull ValueSource variableValueSource) { //noinspection ConstantConditions Preconditions.checkArgument(table != null, "table cannot be null"); //noinspection ConstantConditions Preconditions.checkArgument(variableValueSource != null, "variableValueSource cannot be null"); if (!variableValueSource.supportVectorSource()) return; for (Value value : variableValueSource.asVectorSource().getValues(summary.getFilteredVariableEntities(table))) { add(value); } }
Example 11
| Project: transgalactica-master File: DaoHangarService.java View source code |
@Override
@Secured({ "ROLE_GESTIONNAIRE", "ROLE_SUPER_GESTIONNAIRE" })
@Transactional
public void affecterVaisseauAuHangar(@NotNull VaisseauEntity vaisseau, @NotNull HangarEntity hangar) {
// reste t'il des places dans le Hangar cible
int nbVaisseaux = vaisseauDao.countByHangar(hangar);
if (nbVaisseaux >= hangar.getNombreEmplacements()) {
throw new BusinessException("HANGAR_VALIDATION_4");
}
// le vaisseau était'il parqué dans un hangar.
HangarEntity fromHangar = vaisseau.getHangar();
if (fromHangar != null && !fromHangar.equals(hangar)) {
fromHangar.remove(vaisseau);
hangarDao.save(fromHangar);
}
hangar.add(vaisseau);
hangarDao.save(hangar);
}Example 12
| Project: gwt-bootstrap-master File: ValidationErrorsActivity.java View source code |
@Override
public Map<String, Object> getAttributes() {
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("message", "{javax.validation.constraints.NotNull.message}");
attributes.put("payload", new java.lang.Class[] {});
attributes.put("groups", new java.lang.Class[] { javax.validation.groups.Default.class });
return attributes;
}Example 13
| Project: valdr-bean-validation-master File: ConstraintParserTest.java View source code |
/**
* See method name.
*/
@Test
public void shouldReturnDefaultMessage() {
// given
parserConfiguredFor(Lists.newArrayList(TestModelWithASingleAnnotatedMember.class.getPackage().getName()), emptyStringList());
// when
String json = parser.parse();
// then
String expected = "{" + LS + " \"" + TestModelWithASingleAnnotatedMember.class.getSimpleName() + "\" : {" + LS + " \"notNullString\" : {" + LS + " \"required\" : {" + LS + " \"message\" : \"{javax.validation.constraints.NotNull.message}\"" + LS + " }" + LS + " }" + LS + " }" + LS + "}";
assertThat(json, is(expected));
}Example 14
| Project: hibernate-validator-master File: TypeAnnotationMetaDataRetrievalTest.java View source code |
@Test
public void testFieldTypeArgument() throws Exception {
BeanConfiguration<A> beanConfiguration = provider.getBeanConfiguration(A.class);
ConstrainedField field = findConstrainedField(beanConfiguration, A.class, "names");
assertThat(field.getTypeArgumentConstraints().size()).isEqualTo(2);
assertThat(getAnnotationsTypes(field.getTypeArgumentConstraints())).contains(NotNull.class, NotBlank.class);
}Example 15
| Project: Advanced-Public-Transport-Timetables-master File: InputChecker.java View source code |
/**
* String to Date
*
* @param time String to evaluate (HH:mm)
* @param timeZone The timezone the given time is in
* @return a date with the given time within the last 2 and the next 22hours (or if no String got delivered, null)
*/
@NotNull
public static Date getAndValidateTime(String time, TimeZone timeZone) throws WrongParameterException {
//if nothing got delivered, return the current time
if (time == null || time.trim().length() == 0) {
return new Date();
}
//remove spaces from the input
time = time.trim();
//fix issues with only hour given
if (time.length() == 1)
time = "0" + time + ":00";
if (time.length() == 2)
time = time + ":00";
//fix issue with missing hours and minutes separator like "815" or "0815" (to "08:15")
if (time.matches("\\d{3,4}"))
time = time.replaceFirst("(\\d{1,2})(\\d{2})", "$1:$2");
//fix issue with missing minutes like "08:" (to "08:00")
if (time.length() == 3 && time.matches("\\d\\d[^\\d]"))
time = time + "00";
//fix issue with hours like "8:15" (to "08:15")
if (time.length() == 4)
time = "0" + time;
if (time.length() == 5) {
//fix issues with "24:XY" (to "00:XY"
if (time.startsWith("24"))
time = "00" + time.substring(3, 2);
//Guarantee legal values for the time
if (time.matches("(([01][0-9])|(2[0-3])).[0123456][0-9]")) {
Calendar now = new GregorianCalendar();
//create the date (as a Calendar)
Calendar c = new GregorianCalendar(timeZone);
c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time.substring(0, 2)));
c.set(Calendar.MINUTE, Integer.parseInt(time.substring(3, 5)));
//within how many hours in the past is ok?
int hours = 2;
//check if it leads to a selection of yesterday
if (now.get(Calendar.HOUR_OF_DAY) < hours && (c.get(Calendar.HOUR_OF_DAY) * 60 + c.get(Calendar.MINUTE)) > ((now.get(Calendar.HOUR_OF_DAY) + 24 - hours) * 60 + now.get(Calendar.MINUTE))) {
c.add(Calendar.DAY_OF_YEAR, -1);
} else //or to a selection of tomorrow
if ((now.get(Calendar.HOUR_OF_DAY) - hours) * 60 + now.get(Calendar.MINUTE) > c.get(Calendar.HOUR_OF_DAY) * 60 + c.get(Calendar.MINUTE)) {
c.add(Calendar.DAY_OF_YEAR, 1);
}
return c.getTime();
}
}
throw new WrongParameterException("Falsches Zeitformat. Zeit angeben in HH:MM.");
}Example 16
| Project: beanvalidation-tck-master File: MethodValidationTest.java View source code |
@Test
@SpecAssertions({ @SpecAssertion(section = Sections.CONSTRAINTMETADATA_CONSTRAINTDESCRIPTOR, id = "a"), @SpecAssertion(section = Sections.XML_MAPPING_CONSTRAINTDECLARATIONINXML_METHODLEVELOVERRIDING, id = "h") })
public void testConstraintOnMethodReturnValueAndParameter() throws Exception {
MethodDescriptor descriptor = TestUtil.getMethodDescriptor(CustomerRepository.class, "notifyCustomer", Customer.class, String.class);
assertNotNull(descriptor, "the specified method should be configured in xml");
ReturnValueDescriptor returnValueDescriptor = descriptor.getReturnValueDescriptor();
Set<ConstraintDescriptor<?>> constraintDescriptors = returnValueDescriptor.getConstraintDescriptors();
assertTrue(constraintDescriptors.size() == 1);
ConstraintDescriptor<?> constraintDescriptor = constraintDescriptors.iterator().next();
assertEquals(constraintDescriptor.getAnnotation().annotationType(), NotNull.class, "Unexpected constraint type");
List<ParameterDescriptor> parameterDescriptors = descriptor.getParameterDescriptors();
assertTrue(parameterDescriptors.size() == 2);
ParameterDescriptor parameterDescriptor = parameterDescriptors.get(0);
constraintDescriptors = parameterDescriptor.getConstraintDescriptors();
assertTrue(constraintDescriptors.size() == 1);
constraintDescriptor = constraintDescriptors.iterator().next();
assertEquals(constraintDescriptor.getAnnotation().annotationType(), NotNull.class, "Unexpected constraint type");
}Example 17
| Project: build-monitor-master File: ArtifactTransporter.java View source code |
public Path get(@NotNull String groupName, @NotNull String artifactName, @NotNull String version, @NotNull String artifactFileExtension) { Artifact artifact = new DefaultArtifact(groupName, artifactName, artifactFileExtension, version); RepositorySystem system = newRepositorySystem(); RepositorySystemSession session = newRepositorySystemSession(system); ArtifactRequest request = new ArtifactRequest(); request.setArtifact(artifact); request.setRepositories(repositories(system, session)); try { ArtifactResult artifactResult = system.resolveArtifact(session, request); artifact = artifactResult.getArtifact(); Log.info(artifact + " resolved to " + artifact.getFile()); return artifact.getFile().toPath(); } catch (ArtifactResolutionException e) { throw new RuntimeException(format("Couldn't resolve a '%s' artifact for '%s:%s:%s'", artifactFileExtension, groupName, artifactName, version), e); } }
Example 18
| Project: cargotracker-ddd-master File: GraphTraversalService.java View source code |
@GET
@Path("/shortest-path")
@Produces({ "application/json", "application/xml; qs=.75" })
public // TODO Add internationalized messages for constraints.
List<TransitPath> findShortestPath(@NotNull @Size(min = 5, max = 5) @QueryParam("origin") String originUnLocode, @NotNull @Size(min = 5, max = 5) @QueryParam("destination") String destinationUnLocode, @QueryParam("deadline") String deadline) {
Date date = nextDate(new Date());
List<String> allVertices = dao.listLocations();
allVertices.remove(originUnLocode);
allVertices.remove(destinationUnLocode);
int candidateCount = getRandomNumberOfCandidates();
List<TransitPath> candidates = new ArrayList<>(candidateCount);
for (int i = 0; i < candidateCount; i++) {
allVertices = getRandomChunkOfLocations(allVertices);
List<TransitEdge> transitEdges = new ArrayList<>(allVertices.size() - 1);
String firstLegTo = allVertices.get(0);
Date fromDate = nextDate(date);
Date toDate = nextDate(fromDate);
date = nextDate(toDate);
transitEdges.add(new TransitEdge(dao.getVoyageNumber(originUnLocode, firstLegTo), originUnLocode, firstLegTo, fromDate, toDate));
for (int j = 0; j < allVertices.size() - 1; j++) {
String current = allVertices.get(j);
String next = allVertices.get(j + 1);
fromDate = nextDate(date);
toDate = nextDate(fromDate);
date = nextDate(toDate);
transitEdges.add(new TransitEdge(dao.getVoyageNumber(current, next), current, next, fromDate, toDate));
}
String lastLegFrom = allVertices.get(allVertices.size() - 1);
fromDate = nextDate(date);
toDate = nextDate(fromDate);
transitEdges.add(new TransitEdge(dao.getVoyageNumber(lastLegFrom, destinationUnLocode), lastLegFrom, destinationUnLocode, fromDate, toDate));
candidates.add(new TransitPath(transitEdges));
}
return candidates;
}Example 19
| Project: cargotracker-master File: GraphTraversalService.java View source code |
@GET
@Path("/shortest-path")
@Produces({ "application/json", "application/xml; qs=.75" })
public // TODO Add internationalized messages for constraints.
List<TransitPath> findShortestPath(@NotNull @Size(min = 5, max = 5) @QueryParam("origin") String originUnLocode, @NotNull @Size(min = 5, max = 5) @QueryParam("destination") String destinationUnLocode, @QueryParam("deadline") String deadline) {
Date date = nextDate(new Date());
List<String> allVertices = dao.listLocations();
allVertices.remove(originUnLocode);
allVertices.remove(destinationUnLocode);
int candidateCount = getRandomNumberOfCandidates();
List<TransitPath> candidates = new ArrayList<>(candidateCount);
for (int i = 0; i < candidateCount; i++) {
allVertices = getRandomChunkOfLocations(allVertices);
List<TransitEdge> transitEdges = new ArrayList<>(allVertices.size() - 1);
String firstLegTo = allVertices.get(0);
Date fromDate = nextDate(date);
Date toDate = nextDate(fromDate);
date = nextDate(toDate);
transitEdges.add(new TransitEdge(dao.getVoyageNumber(originUnLocode, firstLegTo), originUnLocode, firstLegTo, fromDate, toDate));
for (int j = 0; j < allVertices.size() - 1; j++) {
String current = allVertices.get(j);
String next = allVertices.get(j + 1);
fromDate = nextDate(date);
toDate = nextDate(fromDate);
date = nextDate(toDate);
transitEdges.add(new TransitEdge(dao.getVoyageNumber(current, next), current, next, fromDate, toDate));
}
String lastLegFrom = allVertices.get(allVertices.size() - 1);
fromDate = nextDate(date);
toDate = nextDate(fromDate);
transitEdges.add(new TransitEdge(dao.getVoyageNumber(lastLegFrom, destinationUnLocode), lastLegFrom, destinationUnLocode, fromDate, toDate));
candidates.add(new TransitPath(transitEdges));
}
return candidates;
}Example 20
| Project: celements-core-master File: CelementsWebService.java View source code |
@Override @NotNull public synchronized XWikiUser createNewUser(@NotNull Map<String, String> userData, @NotNull String possibleLogins, boolean validate) throws UserCreateException { String accountName = ""; String accountFullName = null; if (userData.containsKey("xwikiname")) { accountName = userData.get("xwikiname"); userData.remove("xwikiname"); } else { while (accountName.equals("") || getContext().getWiki().exists(webUtilsService.resolveDocumentReference(accountFullName), getContext())) { accountName = getContext().getWiki().generateRandomString(12); accountFullName = "XWiki." + accountName; } } String validkey = ""; int success = -1; try { if (areIdentifiersUnique(userData, possibleLogins, getContext())) { if (!userData.containsKey("password")) { String password = getContext().getWiki().generateRandomString(8); userData.put("password", password); } if (!userData.containsKey("validkey")) { validkey = new NewCelementsTokenForUserCommand().getUniqueValidationKey(getContext()); userData.put("validkey", validkey); } else { validkey = userData.get("validkey"); } if (!userData.containsKey("active")) { userData.put("active", "0"); } String content = "#includeForm(\"XWiki.XWikiUserSheet\")"; success = getContext().getWiki().createUser(accountName, userData, webUtilsService.resolveDocumentReference("XWiki.XWikiUsers"), content, null, "edit", getContext()); } } catch (XWikiException excp) { _LOGGER.error("Exception while creating a new user", excp); throw new UserCreateException(excp); } XWikiUser newUser = null; if (success == 1) { setRightsOnUserDoc(accountFullName); newUser = new XWikiUser(accountFullName); if (validate) { _LOGGER.info("send account validation mail with data: accountname='" + accountName + "', email='" + userData.get("email") + "', validkey='" + validkey + "'"); try { new PasswordRecoveryAndEmailValidationCommand().sendValidationMessage(userData.get("email"), validkey, webUtilsService.resolveDocumentReference("Tools.AccountActivationMail"), webUtilsService.getDefaultAdminLanguage()); } catch (XWikiException e) { _LOGGER.error("Exception while sending validation mail to '" + userData.get("email") + "'", e); throw new UserCreateException(e); } } } if (newUser == null) { throw new UserCreateException("Failed to create a new user"); } return newUser; }
Example 21
| Project: che-plugins-master File: RecipeEditorPanel.java View source code |
private void initializeEditor(@NotNull final VirtualFile file) {
FileType fileType = fileTypeRegistry.getFileTypeByFile(file);
editor = getEditor();
editor.activate();
editor.onOpen();
view.showEditor(editor);
// wait when editor is initialized
editor.addPropertyListener(new PropertyListener() {
@Override
public void propertyChanged(PartPresenter source, int propId) {
switch(propId) {
case PROP_INPUT:
setReadOnlyProperty(file);
view.showEditor(editor);
break;
case PROP_DIRTY:
if (validateUndoOperation()) {
setEnableSaveAndCancelButtons(true);
}
break;
default:
}
}
});
try {
editor.init(new RecipeEditorInput(fileType, file));
} catch (EditorInitException e) {
Log.error(getClass(), e);
}
}Example 22
| Project: DLect-master File: LoginImpl.java View source code |
public boolean doLoginImpl(@NotNull UniversityActionProvider prov, @NotNull University u, @NotNull String username, @NotNull String password, @NotNull LoginCredentialBean loginCredentials) throws DLectException { loginCredentials.clear(); LoginActionProvider loginProv = prov.getLoginActionProvider(); if (loginProv == null) { throw getIllegalReturnTypeException("Provider gave a null login action provider", prov, loginProv); } // Always copy university. boolean result = loginProv.doLoginFor(u.copyOf(), username, password); if (!result) { throw getOnFailContractBreachException("doLoginFor", loginProv); } loginCredentials.updateFrom(prov, u, username, password); return result; }
Example 23
| Project: formio-master File: AbstractFormElement.java View source code |
private boolean isRequiredByAnnotations(Annotation[] annots, int level) {
boolean required = false;
if (level < 2) {
if (annots != null) {
for (Annotation ann : annots) {
if (ann instanceof Size) {
Size s = (Size) ann;
if (s.min() > 0) {
required = true;
break;
}
} else if (ann instanceof NotNull) {
required = true;
break;
} else if (ann instanceof NotEmpty) {
required = true;
break;
} else {
if (isRequiredByAnnotations(ann.annotationType().getAnnotations(), level + 1)) {
required = true;
break;
}
}
}
}
}
return required;
}Example 24
| Project: gazpachoquest-master File: QuestionnaireResource.java View source code |
@GET
@Path("/{questionnaireId}/definition")
@ApiOperation(value = "Get questionnaire definition", notes = "More notes about this method", response = QuestionnaireDefinitionDTO.class)
@ApiResponses(value = { @ApiResponse(code = 404, message = "Invalid invitation token supplied"), @ApiResponse(code = 200, message = "questionnaires available") })
public Response getDefinition(@NotNull @PathParam("questionnaireId") @ApiParam(value = "Questionnaire id", required = true) Integer questionnaireId) {
Subject subject = SecurityUtils.getSubject();
User principal = (User) SecurityUtils.getSubject().getPrincipal();
subject.checkPermission("questionnaire:read:" + questionnaireId);
logger.debug("Fetching Questionnaire Definition {} for user {}", questionnaireId, principal.getFullName());
QuestionnaireDefinitionDTO questionnaireDefinitionDTO = questionnaireFacade.getDefinition(questionnaireId);
return Response.ok(questionnaireDefinitionDTO).build();
}Example 25
| Project: javaee7-samples-master File: ConstructorParametersConstraintsTest.java View source code |
@Test
public void constructorViolationsWhenNullParameters() throws NoSuchMethodException, SecurityException {
final MyParameter parameter = new MyParameter();
ExecutableValidator methodValidator = validator.forExecutables();
Constructor<MyBean2> constructor = MyBean2.class.getConstructor(parameter.getClass());
Set<ConstraintViolation<MyBean2>> constraints = methodValidator.validateConstructorParameters(constructor, new Object[] { parameter });
ConstraintViolation<MyBean2> violation = constraints.iterator().next();
assertThat(constraints.size(), equalTo(1));
assertThat(violation.getMessageTemplate(), equalTo("{javax.validation.constraints.NotNull.message}"));
assertThat(violation.getPropertyPath().toString(), equalTo("MyBean2.arg0.value"));
}Example 26
| Project: JavaIncrementalParser-master File: ConstructorParametersConstraintsTest.java View source code |
@Test
public void constructorViolationsWhenNullParameters() throws NoSuchMethodException, SecurityException {
final MyParameter parameter = new MyParameter();
ExecutableValidator methodValidator = validator.forExecutables();
Constructor<MyBean2> constructor = MyBean2.class.getConstructor(parameter.getClass());
Set<ConstraintViolation<MyBean2>> constraints = methodValidator.validateConstructorParameters(constructor, new Object[] { parameter });
ConstraintViolation<MyBean2> violation = constraints.iterator().next();
assertThat(constraints.size(), equalTo(1));
assertThat(violation.getMessageTemplate(), equalTo("{javax.validation.constraints.NotNull.message}"));
assertThat(violation.getPropertyPath().toString(), equalTo("MyBean2.arg0.value"));
}Example 27
| Project: javalab-master File: Executor.java View source code |
public String execCommand(@NotNull String command, File folder) {
try {
String[] cmdAsTokens = command.split(" ");
Process process;
if (folder == null) {
process = new ProcessBuilder(cmdAsTokens).redirectErrorStream(true).start();
} else {
process = new ProcessBuilder(cmdAsTokens).directory(folder).redirectErrorStream(true).start();
}
boolean finished = process.waitFor(TIMEOUT_VALUE, TimeUnit.SECONDS);
if (finished) {
String stdOut = getStreamAsString(process.getInputStream());
tracer.info("OUT: \n" + stdOut);
return stdOut;
} else {
process.destroyForcibly();
return TIMEOUT_MESSAGE_ERROR;
}
} catch (InterruptedExceptionIOException | e) {
tracer.log(Level.SEVERE, e, e::getMessage);
throw new NotRunnableCodeException(e);
}
}Example 28
| Project: jenkins-build-monitor-plugin-master File: ArtifactTransporter.java View source code |
public Path get(@NotNull String groupName, @NotNull String artifactName, @NotNull String version, @NotNull String artifactFileExtension) { Artifact artifact = new DefaultArtifact(groupName, artifactName, artifactFileExtension, version); RepositorySystem system = newRepositorySystem(); RepositorySystemSession session = newRepositorySystemSession(system); ArtifactRequest request = new ArtifactRequest(); request.setArtifact(artifact); request.setRepositories(repositories(system, session)); try { ArtifactResult artifactResult = system.resolveArtifact(session, request); artifact = artifactResult.getArtifact(); Log.info(artifact + " resolved to " + artifact.getFile()); return artifact.getFile().toPath(); } catch (ArtifactResolutionException e) { throw new RuntimeException(format("Couldn't resolve a '%s' artifact for '%s:%s:%s'", artifactFileExtension, groupName, artifactName, version), e); } }
Example 29
| Project: JMobster-master File: NotNullValidatorTest.java View source code |
@Test
public void testWrite_Middle() throws Exception {
NotNullValidator validator = new NotNullValidator();
JavaScriptContext context = createAndInjectContext(validator, ItemStatuses.notFirstNorLast());
validator.write(mock(NotNull.class));
context.getWriter().close();
assertThat(context.getWriter().toString(), is(output + ",\n"));
}Example 30
| Project: JSR303ClientValidationLibrary-master File: ConstraintConverterFactoryImplTest.java View source code |
/**
* Test method for
* {@link com.yannart.validation.converter.impl.ConstraintConverterFactoryImpl#getConverterMapByAnnotationClass(java.lang.Class)}
* .
*/
@Test
public void testGetConverterMapByAnnotationClass() {
Set<JSR303ConstraintConverter> converterSet = factory.getConverterMapByAnnotationClass(Size.class);
assertEquals(1, converterSet.size());
for (JSR303ConstraintConverter converter : converterSet) {
assertTrue(converter instanceof SizeConverter);
}
converterSet = factory.getConverterMapByAnnotationClass(Max.class);
assertEquals(1, converterSet.size());
for (JSR303ConstraintConverter converter : converterSet) {
assertTrue(converter instanceof MaxConverter);
}
converterSet = factory.getConverterMapByAnnotationClass(Min.class);
assertEquals(1, converterSet.size());
for (JSR303ConstraintConverter converter : converterSet) {
assertTrue(converter instanceof MinConverter);
}
converterSet = factory.getConverterMapByAnnotationClass(NotNull.class);
assertEquals(1, converterSet.size());
for (JSR303ConstraintConverter converter : converterSet) {
assertTrue(converter instanceof RequiredConverter);
}
}Example 31
| Project: myfaces-ext-cdi-master File: CodiNotNullConstraintValidator.java View source code |
@Override
public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) {
boolean isValid = super.isValid(object, constraintValidatorContext);
if (/*ProjectStage.Development.equals(this.projectStage) &&*/
!isValid) {
String message = "violation found - constraint: @" + NotNull.class.getSimpleName() + " detected by: " + getClass().getName();
this.facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, message));
}
return isValid;
}Example 32
| Project: Restfull-Pickelink-Angular.js-master File: RegistrationService.java View source code |
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response createMember(@NotNull Registration request) {
if (!request.getPassword().equals(request.getPasswordConfirmation())) {
return MessageBuilder.badRequest().message("Password mismatch.").build();
}
MessageBuilder message;
try {
// if there is no user with the provided e-mail, perform registration
if (this.identityModelManager.findByLoginName(request.getEmail()) == null) {
MyUser newUser = this.identityModelManager.createAccount(request);
this.identityModelManager.grantRole(newUser, USER);
String activationCode = newUser.getActivationCode();
sendNotification(request, activationCode);
message = MessageBuilder.ok().activationCode(activationCode);
} else {
message = MessageBuilder.badRequest().message("This username is already in use. Try another one.");
}
} catch (Exception e) {
message = MessageBuilder.badRequest().message(e.getMessage());
}
return message.build();
}Example 33
| Project: AngularBeans-master File: BeanValidationProcessor.java View source code |
public void processBeanValidationParsing(Method method) {
String modelName = CommonUtils.obtainFieldNameFromAccessor(method.getName());
Annotation[] scannedAnnotations = method.getAnnotations();
buffer.append("\nif (modelName === '").append(modelName).append("') {");
for (Annotation a : scannedAnnotations) {
if (!validationAnnotations.contains(a.annotationType())) {
continue;
}
String name = (a.annotationType().getName());
switch(name) {
case "javax.validation.constraints.NotNull":
buffer.append("\nentries[e].setAttribute('required', 'true');");
break;
case "org.hibernate.validator.constraints.Email":
buffer.append("\nentries[e].setAttribute('type', 'email');");
break;
case "javax.validation.constraints.Pattern":
String regex = ((Pattern) a).regexp();
buffer.append("\nentries[e].setAttribute('ng-pattern', '").append(regex).append("');");
break;
case "javax.validation.constraints.Size":
buffer.append("\nentries[e].setAttribute('required', 'true');");
Size sizeConstraint = (Size) a;
int maxLength = sizeConstraint.max();
int minLength = sizeConstraint.min();
if (minLength < 0) {
throw new IllegalArgumentException("The min parameter cannot be negative.");
}
if (maxLength < 0) {
throw new IllegalArgumentException("The max parameter cannot be negative.");
}
if (minLength > 0) {
buffer.append("\nentries[e].setAttribute('ng-minlength', '").append(minLength).append("');");
}
if (maxLength < Integer.MAX_VALUE) {
buffer.append("\nentries[e].setAttribute('ng-maxlength', '").append(maxLength).append("');");
}
break;
case "javax.validation.constraints.DecimalMin":
String dMin = ((DecimalMin) a).value();
buffer.append("\nentries[e].setAttribute('min', '").append(dMin).append("');");
break;
case "javax.validation.constraints.DecimalMax":
String dMax = ((DecimalMax) a).value();
buffer.append("\nentries[e].setAttribute('max', '").append(dMax).append("');");
break;
case "javax.validation.constraints.Min":
long min = ((Min) a).value();
buffer.append("\nentries[e].setAttribute('min', '").append(min).append("');");
break;
case "javax.validation.constraints.Max":
long max = ((Max) a).value();
buffer.append("\nentries[e].setAttribute('max', '").append(max).append("');");
break;
default:
break;
}
}
buffer.append("\n}");
}Example 34
| Project: AIDR-master File: DocumentController.java View source code |
@RequestMapping(value = "/import/training-set", method = { RequestMethod.POST })
public String importTrainingData(@RequestParam @NotNull Long targetCollectionId, @RequestParam Long sourceCollectionId, @RequestParam Long attributeId) {
if (targetCollectionId == null || sourceCollectionId == null || attributeId == null || targetCollectionId == 0 || sourceCollectionId == 0 || attributeId == 0 || targetCollectionId == -1 || sourceCollectionId == -1 || attributeId == -1) {
return "FAILURE";
}
documentService.importTrainingData(targetCollectionId, sourceCollectionId, attributeId);
return "SUCCESS";
}Example 35
| Project: billy-master File: GenerateHash.java View source code |
public static String generateHash(@NotNull PrivateKey privateKey, @NotNull PublicKey publicKey, @NotNull Date invoiceDate, @NotNull Date systemEntryDate, @NotNull String invoiceNumber, @NotNull BigDecimal grossTotal, String previousInvoiceHash) throws DocumentIssuingException { try { String sourceString = GenerateHash.generateSourceHash(invoiceDate, systemEntryDate, invoiceNumber, grossTotal, previousInvoiceHash); CertificationManager certificationManager = new CertificationManager(); certificationManager.setAutoVerifyHash(true); certificationManager.setPrivateKey(privateKey); certificationManager.setPublicKey(publicKey); return certificationManager.getHashBase64(sourceString); } catch (Throwable e) { throw new DocumentIssuingException(e); } }
Example 36
| Project: checker-framework-master File: AliasedAnnotations.java View source code |
void useNonNullAnnotations() {
//:: error: (assignment.type.incompatible)
@org.checkerframework.checker.nullness.qual.NonNull Object nn1 = null;
//:: error: (assignment.type.incompatible)
@com.sun.istack.internal.NotNull Object nn2 = null;
//:: error: (assignment.type.incompatible)
@edu.umd.cs.findbugs.annotations.NonNull Object nn3 = null;
//:: error: (assignment.type.incompatible)
@javax.annotation.Nonnull Object nn4 = null;
// Invalid location for NonNull :: error: (assignment.type.incompatible)
// @javax.validation.constraints.NotNull Object nn5 = null;
//:: error: (assignment.type.incompatible)
@org.eclipse.jdt.annotation.NonNull Object nn6 = null;
//:: error: (assignment.type.incompatible)
@org.jetbrains.annotations.NotNull Object nn7 = null;
//:: error: (assignment.type.incompatible)
@org.netbeans.api.annotations.common.NonNull Object nn8 = null;
//:: error: (assignment.type.incompatible)
@org.jmlspecs.annotation.NonNull Object nn9 = null;
}Example 37
| Project: coner-master File: HandicapGroupSetsResource.java View source code |
@POST
@UnitOfWork
@ApiOperation(value = "Add a new Handicap Group Set", notes = "Optionally include a set of Handicap Group entities with ID to associate them")
@ApiResponses({ @ApiResponse(code = HttpStatus.CREATED_201, message = ApiResponseConstants.Created.MESSAGE, responseHeaders = { @ResponseHeader(name = ApiResponseConstants.Created.Headers.NAME, description = ApiResponseConstants.Created.Headers.DESCRIPTION, response = String.class) }), @ApiResponse(code = HttpStatus.UNPROCESSABLE_ENTITY_422, message = "Failed validation", response = ValidationErrorMessage.class) })
public Response add(@Valid @NotNull @ApiParam(value = "Handicap Group Set") AddHandicapGroupSetRequest request) throws AddEntityException {
HandicapGroupSetAddPayload addPayload = handicapGroupSetMapper.toDomainAddPayload(request);
HandicapGroupSet domainEntity = handicapGroupSetService.add(addPayload);
HandicapGroupSetApiEntity entity = handicapGroupSetMapper.toApiEntity(domainEntity);
return Response.created(UriBuilder.fromPath("/handicapGroups/sets/{handicapGroupSetId}").build(entity.getId())).build();
}Example 38
| Project: devicehive-java-server-master File: NetworkDaoRiakImpl.java View source code |
@Override
public void persist(@NotNull NetworkVO newNetwork) {
if (newNetwork.getId() == null) {
newNetwork.setId(getId(COUNTERS_LOCATION));
}
RiakNetwork network = RiakNetwork.convert(newNetwork);
Location location = new Location(NETWORK_NS, String.valueOf(network.getId()));
StoreValue storeOp = new StoreValue.Builder(network).withLocation(location).withOption(quorum.getWriteQuorumOption(), quorum.getWriteQuorum()).build();
try {
client.execute(storeOp);
} catch (ExecutionExceptionInterruptedException | e) {
throw new HivePersistenceLayerException("Can't execute store operation on network network", e);
}
}Example 39
| Project: event-collector-master File: TestServerConfig.java View source code |
@Test
public void testValidations() {
assertFailsValidation(new ServerConfig().setCombinerStartDaysAgo(1).setCombinerEndDaysAgo(1), "combinerStartEndDaysSane", "must be true", AssertTrue.class);
assertFailsValidation(new ServerConfig().setCombinerGroupId(null), "combinerGroupId", "may not be null", NotNull.class);
assertFailsValidation(new ServerConfig().setCombinerGroupId(""), "combinerGroupId", "must be non-empty", Size.class);
assertFailsValidation(new ServerConfig().setCombinerThreadCount(0), "combinerThreadCount", "must be greater than or equal to 1", Min.class);
assertFailsValidation(new ServerConfig().setCombinerHighPriorityEventTypes(ImmutableSet.of("TypeA", "TypeB")).setCombinerLowPriorityEventTypes(ImmutableSet.of("TypeB", "TypeC")), "highAndLowPriorityEventTypesDisjoint", "High- and Low-Priority event type lists must be disjoint.", AssertTrue.class);
assertValidates(new ServerConfig().setLocalStagingDirectory(new File("testdir")).setAwsAccessKey("my-access-key").setAwsSecretKey("my-secret-key").setS3StagingLocation("s3://example-staging/").setS3DataLocation("s3://example-data/").setS3MetadataLocation("s3://example-metadata/").setCombinerGroupId("someGroupId"));
}Example 40
| Project: genie-master File: PingFederateJWTTokenServices.java View source code |
private OAuth2Request getOAuth2Request(@NotNull final JwtClaims claims) throws MalformedClaimException, InvalidTokenException {
final String clientId = claims.getClaimValue("client_id", String.class);
@SuppressWarnings("unchecked") final Set<String> scopes = Sets.newHashSet(claims.getClaimValue("scope", Collection.class));
final Set<SimpleGrantedAuthority> authorities = scopes.stream().map( scope -> {
if (scope.startsWith(GENIE_SCOPE_PREFIX)) {
scope = scope.substring(GENIE_SCOPE_PREFIX_LENGTH);
}
return new SimpleGrantedAuthority(ROLE + scope.toUpperCase());
}).collect(Collectors.toSet());
if (authorities.isEmpty()) {
throw new InvalidTokenException("No scopes found. Unable to authorize");
}
// Assume a user is a subset of admin so always grant admin user the role user as well
if (authorities.contains(ADMIN)) {
authorities.add(USER);
}
return new OAuth2Request(null, clientId, authorities, true, scopes, null, null, null, null);
}Example 41
| Project: hibernate-orm-master File: BeanValidationGroupsTest.java View source code |
@Test
public void testListeners() {
CupHolder ch = new CupHolder();
ch.setRadius(new BigDecimal("12"));
Session s = openSession();
Transaction tx = s.beginTransaction();
try {
s.persist(ch);
s.flush();
} catch (ConstraintViolationException e) {
fail("invalid object should not be validated");
}
try {
ch.setRadius(null);
s.flush();
} catch (ConstraintViolationException e) {
fail("invalid object should not be validated");
}
try {
s.delete(ch);
s.flush();
fail("invalid object should not be persisted");
} catch (ConstraintViolationException e) {
assertEquals(1, e.getConstraintViolations().size());
Annotation annotation = e.getConstraintViolations().iterator().next().getConstraintDescriptor().getAnnotation();
assertEquals(NotNull.class, annotation.annotationType());
}
tx.rollback();
s.close();
}Example 42
| Project: ja-micro-master File: Topic.java View source code |
public static Topic serviceInbox(@NotNull String serviceName, String inboxName) {
StringBuilder topic = new StringBuilder();
topic.append("inbox");
if (!Strings.isNullOrEmpty(inboxName)) {
topic.append("_");
topic.append(inboxName);
}
if (Strings.isNullOrEmpty(serviceName)) {
throw new IllegalArgumentException("service name must not be null or empty");
}
topic.append("-");
topic.append(serviceName);
return new Topic(topic.toString());
}Example 43
| Project: jsonschema2pojo-master File: RequiredArrayRuleTest.java View source code |
@Test
public void shouldUpdateAnnotations() throws JClassAlreadyExistsException {
setupRuleFactoryToIncludeJsr303();
JDefinedClass jclass = new JCodeModel()._class(TARGET_CLASS_NAME);
jclass.field(JMod.PRIVATE, jclass.owner().ref(String.class), "fooBar");
jclass.field(JMod.PRIVATE, jclass.owner().ref(String.class), "foo");
ObjectMapper mapper = new ObjectMapper();
ArrayNode requiredNode = mapper.createArrayNode().add("foo_bar");
rule.apply("Class", requiredNode, jclass, new Schema(null, requiredNode, requiredNode));
Collection<JAnnotationUse> fooBarAnnotations = jclass.fields().get("fooBar").annotations();
Collection<JAnnotationUse> fooAnnotations = jclass.fields().get("foo").annotations();
assertThat(fooBarAnnotations.size(), is(1));
assertThat(fooBarAnnotations.iterator().next().getAnnotationClass().name(), is(NotNull.class.getSimpleName()));
assertThat(fooAnnotations.size(), is(0));
}Example 44
| Project: mayocat-shop-master File: ConfigurationJsonMerger.java View source code |
private HashMap<String, Serializable> merge(@NotNull final Map<String, Serializable> global, @Nullable final Map<String, Serializable> local) {
// Copy the global object
HashMap<String, Serializable> result = Maps.newHashMap(global);
// Iterate over all configuration keys, and merge with tenant configuration
for (String key : result.keySet()) {
Object value = global.get(key);
if (value != null) {
try {
Map<String, Serializable> valueAsMap = (Map<String, Serializable>) value;
if (isConfigurableEntry(valueAsMap)) {
// We have a configurable
Boolean isConfigurable = (Boolean) valueAsMap.get(CONFIGURABLE_KEY);
if (isConfigurable && local != null && local.containsKey(key)) {
valueAsMap.put(VALUE_KEY, local.get(key));
} else {
// Either their is no local configuration override, or overriding
// is not permitted for this entry : we set the default value as value
valueAsMap.put(VALUE_KEY, valueAsMap.get(DEFAULT_KEY));
}
} else {
// We need to go deeper
Map<String, Serializable> localSubMap = null;
if (local != null && local.get(key) != null) {
try {
localSubMap = (Map<String, Serializable>) local.get(key);
} catch (ClassCastException e) {
}
}
HashMap<String, Serializable> mergedValue = this.merge(valueAsMap, localSubMap);
result.put(key, mergedValue);
}
} catch (ClassCastException e) {
}
// TODO add support for list of values
// i.e. try to cast to List<Object> etc.
}
}
return result;
}Example 45
| Project: methodvalidation-integration-master File: DynamicProxyMethodValidationTest.java View source code |
@BeforeClass
public static void setUpMethodValidator() {
ResourceBundle bundle = ResourceBundle.getBundle("org.hibernate.validator.ValidationMessages");
notNullMessage = bundle.getString("javax.validation.constraints.NotNull.message");
validator = Validation.byProvider(HibernateValidator.class).configure().buildValidatorFactory().getValidator().unwrap(MethodValidator.class);
}Example 46
| Project: nazgul_core-master File: MappedSchemaResourceResolver.java View source code |
/**
* Adds a mapping between the supplied namespace and the given xmlSchemaSnippet.
*
* @param namespace The non-null namespace which should be mapped.
* @param xmlSchemaSnippet The non-empty xml Schema snippet which should be mapped.
*/
public void addNamespace2SchemaEntry(@NotNull final String namespace, @NotNull @Size(min = 1) final String xmlSchemaSnippet) {
// Check sanity
Validate.notNull(namespace, "namespace");
Validate.notEmpty(xmlSchemaSnippet, "xmlSchemaSnippet");
Validate.isTrue(!namespace2SchemaSnippetMap.containsKey(namespace), "Cannot overwrite namespace [" + namespace + "]. Known namespaces: " + namespace2SchemaSnippetMap.keySet().stream().reduce(( l, r) -> l + ", " + r).orElse("<none>"));
// Add the mapping.
namespace2SchemaSnippetMap.put(namespace, xmlSchemaSnippet);
}Example 47
| Project: osiris-master File: SearchResourceImpl.java View source code |
@Override
@POST
@ValidationRequired(processor = RestViolationProcessor.class)
@ApiOperation(value = "Get features according to query", httpMethod = "POST", response = FeatureDTO.class, responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Features were found", response = FeatureDTO.class), @ApiResponse(code = 400, message = "Invalid input parameter (header)"), @ApiResponse(code = 400, message = "Query is not correct") })
public Response getFeaturesByQuery(@Auth BasicAuth principal, @ApiParam(value = "Application identifier", required = true) @NotBlank @NotNull @HeaderParam("api_key") String appIdentifier, @ApiParam(value = "Query", required = true) @NotBlank @NotNull String query, @ApiParam(required = false, value = "Layer", allowableValues = "ALL,MAP,FEATURES", defaultValue = "ALL") @QueryParam("layer") @DefaultValue("ALL") LayerDTO layer, @ApiParam(required = false, value = "Index of page", defaultValue = "0") @QueryParam("pageIndex") @DefaultValue("0") Integer pageIndex, @ApiParam(required = false, value = "Size of page", defaultValue = "20") @QueryParam("pageSize") @DefaultValue("20") Integer pageSize, @ApiParam(required = false, value = "Order field") @QueryParam("orderField") String orderField, @ApiParam(required = false, value = "Order", allowableValues = "ASC,DESC") @DefaultValue("ASC") @QueryParam("order") String order) throws AssemblyException, QueryException {
validations.checkIsNotNullAndNotBlank(appIdentifier, query);
validations.checkIsNotNull(layer);
validations.checkMin(0, pageIndex);
validations.checkMin(1, pageSize);
Collection<Feature> features = null;
if (StringUtils.isEmpty(orderField)) {
features = searchManager.getFeaturesByQuery(appIdentifier, query, layer, pageIndex, pageSize);
} else {
features = searchManager.getFeaturesByQuery(appIdentifier, query, layer, pageIndex, pageSize, orderField, order);
}
Collection<FeatureDTO> collectionFeatureDTO = featureAssembler.createDataTransferObjects(features);
return Response.ok(collectionFeatureDTO).build();
}Example 48
| Project: podcastpedia-master File: SearchResource.java View source code |
@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response getSearches(@QueryParam("searchTarget") String searchTarget, @QueryParam("mediaType") org.podcastpedia.common.types.MediaType mediaType, @QueryParam("orderBy") OrderByOption orderBy, @QueryParam("searchMode") String searchMode, @NotNull @QueryParam("numberResultsPerPage") Integer numberResultsPerPage, @NotNull @QueryParam("currentPage") Integer currentPage, @QueryParam("categId") List<Integer> categoryId, @QueryParam("tagId") Integer tagId, @QueryParam("queryText") String queryText, @QueryParam("anyOfTheseWords") String anyOfTheseWords, @QueryParam("allTheseWords") String allTheseWords, @QueryParam("exactPhrase") String exactPhrase, @QueryParam("noneOfTheseWords") String noneOfTheseWords) throws BusinessException, UnsupportedEncodingException {
SearchData searchData = new SearchData.Builder().searchTarget(searchTarget).queryText(queryText).mediaType(mediaType).orderBy(orderBy).searchMode(searchMode).numberResultsPerPage(numberResultsPerPage).currentPage(currentPage).tagId(tagId).categId(categoryId).anyOfTheseWords(anyOfTheseWords).allTheseWords(allTheseWords).noneOfTheseWords(noneOfTheseWords).exactPhrase(exactPhrase).build();
SearchResult searchResult = searchService.getResultsForSearchCriteria(searchData);
return Response.status(200).entity(searchResult).build();
}Example 49
| Project: podcastpedia-web-master File: SearchResource.java View source code |
@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response getSearches(@QueryParam("searchTarget") String searchTarget, @QueryParam("mediaType") org.podcastpedia.common.types.MediaType mediaType, @QueryParam("orderBy") OrderByOption orderBy, @QueryParam("searchMode") String searchMode, @NotNull @QueryParam("numberResultsPerPage") Integer numberResultsPerPage, @NotNull @QueryParam("currentPage") Integer currentPage, @QueryParam("categId") List<Integer> categoryId, @QueryParam("tagId") Integer tagId, @QueryParam("queryText") String queryText, @QueryParam("anyOfTheseWords") String anyOfTheseWords, @QueryParam("allTheseWords") String allTheseWords, @QueryParam("exactPhrase") String exactPhrase, @QueryParam("noneOfTheseWords") String noneOfTheseWords) throws BusinessException, UnsupportedEncodingException {
SearchData searchData = new SearchData.Builder().searchTarget(searchTarget).queryText(queryText).mediaType(mediaType).orderBy(orderBy).searchMode(searchMode).numberResultsPerPage(numberResultsPerPage).currentPage(currentPage).tagId(tagId).categId(categoryId).anyOfTheseWords(anyOfTheseWords).allTheseWords(allTheseWords).noneOfTheseWords(noneOfTheseWords).exactPhrase(exactPhrase).build();
SearchResult searchResult = searchService.getResultsForSearchCriteria(searchData);
return Response.status(200).entity(searchResult).build();
}Example 50
| Project: presto-riak-master File: Coverage.java View source code |
@NotNull
public void plan() {
try {
//conn.ping();
this.coveragePlan = conn.getCoveragePlan(9979);
log.debug("got coverage plan; %s", coveragePlan);
} catch (java.io.IOException e) {
log.debug("%d\n", e);
} catch (com.ericsson.otp.erlang.OtpAuthException e) {
log.debug("%d\n", e);
} catch (com.ericsson.otp.erlang.OtpErlangExit e) {
log.debug("%d\n", e);
}
}Example 51
| Project: raml-for-jax-rs-master File: Jsr303ExtensionTest.java View source code |
@Test
public void forDouble() throws Exception {
setupNumberFacets();
Jsr303Extension ext = new Jsr303Extension();
FieldSpec.Builder builder = FieldSpec.builder(ClassName.get(Double.class), "champ", Modifier.PUBLIC);
ext.onFieldImplementation(null, builder, number);
assertEquals(1, builder.build().annotations.size());
assertEquals(NotNull.class.getName(), builder.build().annotations.get(0).type.toString());
}Example 52
| Project: airlift-master File: TestHttpClientConfig.java View source code |
@Test
public void testValidations() {
assertFailsValidation(new HttpClientConfig().setConnectTimeout(null), "connectTimeout", "may not be null", NotNull.class);
assertFailsValidation(new HttpClientConfig().setRequestTimeout(null), "requestTimeout", "may not be null", NotNull.class);
assertFailsValidation(new HttpClientConfig().setIdleTimeout(null), "idleTimeout", "may not be null", NotNull.class);
}Example 53
| Project: alexandria-master File: ResourcesEndpoint.java View source code |
@POST
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation("create new Resource")
public Response createResource(@NotNull @Valid @WithoutId ResourcePrototype protoType) {
// Log.trace("protoType=[{}]", protoType);
protoType.setState(AlexandriaState.TENTATIVE);
final ResourceCreationRequest request = requestBuilder.build(protoType);
AlexandriaResource resource = request.execute(service);
if (request.wasExecutedAsIs()) {
return noContent();
}
return created(resource);
}Example 54
| Project: clinic-softacad-master File: BeanValidationGroupsTest.java View source code |
@Test
public void testListeners() {
CupHolder ch = new CupHolder();
ch.setRadius(new BigDecimal("12"));
Session s = openSession();
Transaction tx = s.beginTransaction();
try {
s.persist(ch);
s.flush();
} catch (ConstraintViolationException e) {
fail("invalid object should not be validated");
}
try {
ch.setRadius(null);
s.flush();
} catch (ConstraintViolationException e) {
fail("invalid object should not be validated");
}
try {
s.delete(ch);
s.flush();
fail("invalid object should not be persisted");
} catch (ConstraintViolationException e) {
assertEquals(1, e.getConstraintViolations().size());
Annotation annotation = (Annotation) e.getConstraintViolations().iterator().next().getConstraintDescriptor().getAnnotation();
assertEquals(NotNull.class, annotation.annotationType());
}
tx.rollback();
s.close();
}Example 55
| Project: cyclop-master File: FileStorage.java View source code |
public void store(@NotNull UserIdentifier userId, @NotNull Object entity) throws ServiceException { LOG.debug("Storing file for {}", userId); Path histPath = getPath(userId, entity.getClass()); try (FileChannel channel = openForWrite(histPath)) { String jsonText = jsonMarshaller.marshal(entity); ByteBuffer buf = encoder.get().encode(CharBuffer.wrap(jsonText)); int written = channel.write(buf); channel.truncate(written); } catch (IOExceptionSecurityException | IllegalStateException | e) { throw new ServiceException("Error storing query history in:" + histPath + " - " + e.getClass() + " - " + e.getMessage(), e); } LOG.trace("File has been sotred {}", entity); }
Example 56
| Project: disconf-master File: ConfigUpdateController.java View source code |
/**
* �置文件的更新(文本修改)
*
* @param configId
* @param fileContent
*
* @return
*/
@ResponseBody
@RequestMapping(value = "/filetext/{configId}", method = RequestMethod.PUT)
public JsonObjectBase updateFileWithText(@PathVariable long configId, @NotNull String fileContent) {
//
// æ›´æ–°
//
String emailNotification = "";
try {
String str = new String(fileContent.getBytes(), "UTF-8");
LOG.info("receive file: " + str);
emailNotification = configMgr.updateItemValue(configId, str);
LOG.info("update " + configId + " ok");
} catch (Exception e) {
throw new FileUploadException("upload.file.error", e);
}
//
// 通知ZK
//
configMgr.notifyZookeeper(configId);
return buildSuccess(emailNotification);
}Example 57
| Project: discovery-master File: TestDynamicAnnouncement.java View source code |
@Test
public void testValidatesNestedServiceAnnouncements() {
DynamicAnnouncement announcement = new DynamicAnnouncement("testing", "pool", "/location", ImmutableSet.of(new DynamicServiceAnnouncement(null, "type", Collections.<String, String>emptyMap())));
assertFailsValidation(announcement, "serviceAnnouncements[].id", "may not be null", NotNull.class);
}Example 58
| Project: elpaaso-core-master File: FieldFeedbackDecorator.java View source code |
public void beforeRender(Component component) {
FormComponent<?> fc = (FormComponent<?>) component;
Response r = component.getResponse();
String label = (fc.getLabel() != null) ? fc.getLabel().getObject() : null;
if (label != null) {
r.write("<span class=\"param\">");
r.write("<label for=\"");
r.write(fc.getMarkupId());
r.write("\"");
if (!fc.isValid()) {
r.write(" class=\"error\"");
}
r.write(" />");
r.write(Strings.escapeMarkup(label));
r.write("</label>");
r.write("</span>");
NotNull clazz;
try {
Field field = fc.getForm().getModelObject().getClass().getDeclaredField(fc.getInputName());
clazz = field.getAnnotation(NotNull.class);
} catch (NoSuchFieldException e) {
clazz = null;
}
if (clazz != null || fc.isRequired()) {
r.write("<span class=\"required\" title=\"");
r.write(fc.getString("portal.error.required.field.title"));
r.write("\">");
r.write(fc.getString("portal.required.field") + "</span>");
} else {
r.write("<span class=\"notrequired\"></span>");
}
r.write("<span class=\"value\">");
}
super.beforeRender(component);
}Example 59
| Project: GamificationEngine-Kinben-master File: RoleApi.java View source code |
/**
* With this method the name field of one role can be changed. For this the id of the role, the API key of the
* specific organisation, the name of the field and the new value are needed.
* If the API key is not valid an analogous message is returned.
*
*
* @param id
* The id of the role that should be changed. This parameter is required.
* @param attribute
* The name of the attribute which should be changed. This parameter is required.
* The following names of attributes can be used to change the associated field:
* "name".
* @param value
* The new value of the attribute. This parameter is required.
* @param apiKey
* The valid query parameter API key affiliated to one specific organisation,
* to which this role belongs to.
* @return Response of Role in JSON.
*/
@PUT
@Path("/{id}/attributes")
@TypeHint(Role.class)
public Response changeAttributes(@PathParam("id") @NotNull @ValidPositiveDigit String id, @QueryParam("attribute") @NotNull String attribute, @QueryParam("value") @NotNull String value, @QueryParam("apiKey") @ValidApiKey String apiKey) {
LOGGER.debug("change Attribute of Role");
int roleId = ValidateUtils.requireGreaterThanZero(id);
Role role = roleDao.getRole(roleId, apiKey);
ValidateUtils.requireNotNull(roleId, role);
switch(attribute) {
case "name":
role.setName(value);
break;
}
roleDao.insert(role);
return ResponseSurrogate.updated(role);
}Example 60
| Project: hibernate-core-ogm-master File: BeanValidationGroupsTest.java View source code |
@Test
public void testListeners() {
CupHolder ch = new CupHolder();
ch.setRadius(new BigDecimal("12"));
Session s = openSession();
Transaction tx = s.beginTransaction();
try {
s.persist(ch);
s.flush();
} catch (ConstraintViolationException e) {
fail("invalid object should not be validated");
}
try {
ch.setRadius(null);
s.flush();
} catch (ConstraintViolationException e) {
fail("invalid object should not be validated");
}
try {
s.delete(ch);
s.flush();
fail("invalid object should not be persisted");
} catch (ConstraintViolationException e) {
assertEquals(1, e.getConstraintViolations().size());
Annotation annotation = (Annotation) e.getConstraintViolations().iterator().next().getConstraintDescriptor().getAnnotation();
assertEquals(NotNull.class, annotation.annotationType());
}
tx.rollback();
s.close();
}Example 61
| Project: JaxRs2Retrofit-master File: RetrofitMethodBuilderTest.java View source code |
@Test
public void testAddAnnotation() {
AnnotationSpec annotation = AnnotationSpec.builder(ClassName.get(NotNull.class)).build();
Collection<MethodSpec> methodSpecs = createBuilder(new GeneratorSettings(null, null, true, false, false, null)).addAnnotation(annotation).build().values();
Assert.assertEquals(1, methodSpecs.size());
MethodSpec method = methodSpecs.iterator().next();
Assert.assertEquals(1, method.annotations.size());
Assert.assertEquals(annotation, method.annotations.get(0));
}Example 62
| Project: jeeshop-master File: MailTemplates.java View source code |
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed(ADMIN)
@Path("test/{recipient}")
public void sendTestEmail(Object properties, @NotNull @QueryParam("templateName") String templateName, @NotNull @QueryParam("locale") String locale, @NotNull @PathParam("recipient") String recipient) {
MailTemplate existingTpl = mailTemplateFinder.findByNameAndLocale(templateName, locale);
if (existingTpl == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
try {
sendMail(existingTpl, recipient, properties);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}Example 63
| Project: lorsource-master File: ProfileDao.java View source code |
@Nonnull
public Profile readProfile(@NotNull User user) {
List<Profile> profiles = jdbcTemplate.query("SELECT settings, main FROM user_settings WHERE id=?", ( resultSet, i) -> {
Array boxes = resultSet.getArray("main");
if (boxes != null) {
return new Profile(new ProfileHashtable(DefaultProfile.getDefaultProfile(), (Map<String, String>) resultSet.getObject("settings")), Arrays.asList((String[]) boxes.getArray()));
} else {
return new Profile(new ProfileHashtable(DefaultProfile.getDefaultProfile(), (Map<String, String>) resultSet.getObject("settings")), null);
}
}, user.getId());
if (profiles.isEmpty()) {
return new Profile(new ProfileHashtable(DefaultProfile.getDefaultProfile(), new HashMap<>()), null);
} else {
return profiles.get(0);
}
}Example 64
| Project: metadict-master File: RegistrationResource.java View source code |
/**
* Register a new user account. The given {@link RegistrationRequestData} must be valid, i.e. matching bean
* constraints or the registration will be blocked.
*
* @param registrationRequestData
* The registration request.
* @return Either a response with {@link javax.ws.rs.core.Response.Status#ACCEPTED} if the registration was
* successful or either 422 if any validation errors occurred or {@link javax.ws.rs.core.Response.Status#CONFLICT}
* if the user already exists. If the registration was successful, the user will also be logged in automatically.
*/
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response register(@Valid @NotNull RegistrationRequestData registrationRequestData) {
Optional<User> newUser = this.userService.createNewUser(registrationRequestData.getName(), registrationRequestData.getPassword());
Response.ResponseBuilder responseBuilder;
if (!newUser.isPresent()) {
responseBuilder = Response.status(Response.Status.CONFLICT).entity(ResponseContainer.withStatus(ResponseStatus.DUPLICATE));
} else {
Optional<User> user = this.userService.authenticateWithPassword(registrationRequestData.getName(), registrationRequestData.getPassword());
if (user.isPresent() && Objects.equals(newUser.get(), user.get())) {
responseBuilder = Response.accepted(ResponseContainer.withStatus(ResponseStatus.OK));
} else {
// This should never happen
responseBuilder = Response.serverError();
LOGGER.error("User authentication after registration failed");
}
}
return responseBuilder.build();
}Example 65
| Project: Nin-master File: ServletCookieHelper.java View source code |
public static ninja.Cookie convertServletCookieToNinjaCookie(@NotNull Cookie cookie) {
ninja.Cookie.Builder ninjaCookieBuilder = ninja.Cookie.builder(cookie.getName(), cookie.getValue());
ninjaCookieBuilder.setMaxAge(cookie.getMaxAge());
if (cookie.getComment() != null) {
ninjaCookieBuilder.setComment(cookie.getComment());
}
if (cookie.getDomain() != null) {
ninjaCookieBuilder.setDomain(cookie.getDomain());
}
ninjaCookieBuilder.setSecure(cookie.getSecure());
if (cookie.getPath() != null) {
ninjaCookieBuilder.setPath(cookie.getPath());
}
boolean isHttpOnly = SERVLET_COOKIE_FALLBACK_HANDLER.isHttpOnly(cookie);
ninjaCookieBuilder.setHttpOnly(isHttpOnly);
return ninjaCookieBuilder.build();
}Example 66
| Project: Ninja-master File: ServletCookieHelper.java View source code |
public static ninja.Cookie convertServletCookieToNinjaCookie(@NotNull Cookie cookie) {
ninja.Cookie.Builder ninjaCookieBuilder = ninja.Cookie.builder(cookie.getName(), cookie.getValue());
ninjaCookieBuilder.setMaxAge(cookie.getMaxAge());
if (cookie.getComment() != null) {
ninjaCookieBuilder.setComment(cookie.getComment());
}
if (cookie.getDomain() != null) {
ninjaCookieBuilder.setDomain(cookie.getDomain());
}
ninjaCookieBuilder.setSecure(cookie.getSecure());
if (cookie.getPath() != null) {
ninjaCookieBuilder.setPath(cookie.getPath());
}
boolean isHttpOnly = SERVLET_COOKIE_FALLBACK_HANDLER.isHttpOnly(cookie);
ninjaCookieBuilder.setHttpOnly(isHttpOnly);
return ninjaCookieBuilder.build();
}Example 67
| Project: nuxeo-master File: RequestValidator.java View source code |
@NotNull
public String getTypes(String indices, String types) {
Set<String> validTypes = new HashSet<>();
for (String index : indices.split(",")) {
validTypes.addAll(indexTypes.get(index));
}
if (types == null || "*".equals(types) || "_all".equals(types)) {
return StringUtils.join(validTypes, ',');
}
for (String type : types.split(",")) {
if (!validTypes.contains(type)) {
throw new IllegalArgumentException("Invalid index type: " + type);
}
}
return types;
}Example 68
| Project: obiba-commons-master File: KeyStoreRepository.java View source code |
public void saveKeyStore(@NotNull KeyStoreManager keyStore) {
try {
Path keyStorePath = getKeystoreFile(keyStore.getName()).toPath();
Files.write(keyStorePath, getKeyStoreByteArray(keyStore), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
} catch (IOException e) {
throw new RuntimeException(e);
}
}Example 69
| Project: pinot-master File: OverrideConfigResource.java View source code |
@GET
@Path("/override-config/view")
public List<OverrideConfigDTO> viewOverrideConfig(@NotNull @QueryParam("startTime") long startTimeMillis, @NotNull @QueryParam("endTime") long endTimeMillis, @QueryParam("targetEntity") String targetEntity) {
OverrideConfigManager overrideConfigDAO = DAO_REGISTRY.getOverrideConfigDAO();
if (StringUtils.isEmpty(targetEntity)) {
return overrideConfigDAO.findAllConflict(startTimeMillis, endTimeMillis);
} else {
return overrideConfigDAO.findAllConflictByTargetType(targetEntity, startTimeMillis, endTimeMillis);
}
}Example 70
| Project: presto-master File: TestLdapConfig.java View source code |
@Test
public void testValidation() {
assertValidates(new LdapConfig().setLdapUrl("ldaps://localhost").setUserBindSearchPattern("uid=${USER},ou=org,dc=test,dc=com").setUserBaseDistinguishedName("dc=test,dc=com").setGroupAuthorizationSearchPattern("&(objectClass=user)(memberOf=cn=group)(user=username)"));
assertFailsValidation(new LdapConfig().setLdapUrl("ldap://"), "ldapUrl", "LDAP without SSL/TLS unsupported. Expected ldaps://", Pattern.class);
assertFailsValidation(new LdapConfig().setLdapUrl("localhost"), "ldapUrl", "LDAP without SSL/TLS unsupported. Expected ldaps://", Pattern.class);
assertFailsValidation(new LdapConfig().setLdapUrl("ldaps:/localhost"), "ldapUrl", "LDAP without SSL/TLS unsupported. Expected ldaps://", Pattern.class);
assertFailsValidation(new LdapConfig(), "ldapUrl", "may not be null", NotNull.class);
assertFailsValidation(new LdapConfig(), "userBindSearchPattern", "may not be null", NotNull.class);
}Example 71
| Project: rebase-server-master File: UserResource.java View source code |
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response register(@NotNull @Valid User user) {
long level = MongoDBs.users().count();
if (level > Globals.LIMIT_REGISTER) {
return Response.status(Response.Status.FORBIDDEN).entity(new Failure("Rebase suspends the registration service currently")).build();
}
Document document = new Document(User.USERNAME, user.username).append(User.PASSWORD, Hashes.sha1(user.password)).append(User.NAME, user.name).append(User.EMAIL, user.email).append(User.DESCRIPTION, user.description).append(User.AUTHORIZATION, Authorizations.newInstance(user.username)).append(User.CREATED_AT, new Date());
MongoDBs.users().insertOne(document);
Document result = new Document(document);
result.remove(User.PASSWORD);
return Response.created(URIs.create("users", user.username)).entity(result).build();
}Example 72
| Project: Repository-master File: ValidationModule.java View source code |
@Provides
@Singleton
ValidatorFactory validatorFactory(ConstraintValidatorFactory constraintValidatorFactory) {
ClassLoader tccl = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(HibernateValidator.class.getClassLoader());
ValidatorFactory factory = Validation.byDefaultProvider().configure().constraintValidatorFactory(constraintValidatorFactory).parameterNameProvider(new AopAwareParanamerParameterNameProvider()).traversableResolver(new AlwaysTraversableResolver()).buildValidatorFactory();
// FIXME: Install custom MessageInterpolator that can properly find/merge ValidationMessages.properties for bundles
// exercise interpolator to preload elements (avoids issues later when TCCL might be different)
factory.getValidator().validate(new Object() {
// minimal token message
@NotNull(message = "${0}")
String empty;
});
return factory;
} finally {
Thread.currentThread().setContextClassLoader(tccl);
}
}Example 73
| Project: sigmah-master File: SpreadsheetDataUtil.java View source code |
@NotNull
public static LogFrameExportData prepareLogFrameData(final Project project, final Exporter exporter) throws Throwable {
// TODO [INDICATORS] A major redesign of the indicators is in progress...
final LogFrameExportData data = new LogFrameExportData(project, exporter);
// Get indicators from CommandHanler (only for the purpose to get aggregated(current) values of indicators).
final IndicatorListResult indicators = exporter.execute(new GetIndicators(project.getId()));
for (final IndicatorDTO dto : indicators.getData()) {
data.getIndMap().put(dto.getId(), dto);
}
return data;
}Example 74
| Project: xapi-master File: EventManager.java View source code |
public boolean fireEvent(@NotNull IsEvent<?> event) {
IntTo<EventHandler<?, ?>> handles = handlers.get(event.getTypeString());
if (handles.isEmpty()) {
handles = handlers.get(EventTypes.Unhandled.getEventType());
}
boolean allow = true;
for (EventHandler handle : handles.forEach()) {
allow = handle.handleEvent(event);
if (!allow) {
return false;
}
}
return true;
}Example 75
| Project: jaxb-facets-master File: ValidationFacetsFilter.java View source code |
/**
* Process a MinOccurs annotation.
* @param original Existing MinOccurs annotation or null.
* @param info Source for validation constraints.
* @return Processed Annotation or null if no information available.
*/
private MinOccurs filterMinOccurs(MinOccurs original, AnnotationSource info) {
Map<String, Object> annoValues = new HashMap<String, Object>(AnnotationUtils.getAnnotationValues(MinOccurs.class, original));
if (original == null && info.readAnnotation(NotNull.class) != null) {
annoValues.put("value", 1L);
return AnnotationUtils.createAnnotationProxy(MinOccurs.class, annoValues);
} else {
return original;
}
}Example 76
| Project: abiquo-master File: NodeResource.java View source code |
/**
* Returns the physical information of a remote node.
*
* @return a {@link HostDto} instance
* @throws NoHypervisorException
* @throws CollectorException
* @throws LoginException
* @throws ConnectionException
*/
@GET
@Path(HOST)
public HostDto getHostInfo(@PathParam("ip") @NotNull @Ip final String ip, @QueryParam("hyp") @NotNull final String hypervisorType, @QueryParam("user") @NotNull final String user, @QueryParam("passwd") @NotNull final String password, @QueryParam(AIMPORT) @DefaultValue("8889") @Port final Integer aimport) throws NodecollectorException {
Long time = System.currentTimeMillis();
HypervisorType hypType;
try {
hypType = HypervisorType.fromValue(hypervisorType);
} catch (IllegalArgumentException e) {
throw new BadRequestException(MessageValues.UNKNOWN_HYPERVISOR);
}
HostDto dto = hostService.getHostInfo(ip, hypType, user, password, aimport);
time = System.currentTimeMillis() - time;
LOGGER.debug("Retrieving host '" + dto.getName() + " (" + ip + ")' took " + time + " miliseconds.");
return dto;
}Example 77
| Project: AIR-master File: ExecutionClient.java View source code |
@Override
public void onFailure(@NotNull Throwable t) {
if (t instanceof ExecutionFailureException) {
ExecutionFailureException e = (ExecutionFailureException) t;
Job j = e.getJob();
j.setState(JobState.FAILED);
if (j.getError() == null) {
j.setError(new QueryError(e.getMessage(), null, -1, null, null, null, null));
}
jobFinished(j);
}
}Example 78
| Project: airpal-master File: ExecutionClient.java View source code |
@Override
public void onFailure(@NotNull Throwable t) {
if (t instanceof ExecutionFailureException) {
ExecutionFailureException e = (ExecutionFailureException) t;
Job j = e.getJob();
j.setState(JobState.FAILED);
if (j.getError() == null) {
j.setError(new QueryError(e.getMessage(), null, -1, null, null, null, null));
}
jobFinished(j);
}
}Example 79
| Project: cas-mfa-master File: DefaultRegisteredServiceMfaRoleProcessorImpl.java View source code |
/**
* Resolves the authn_method for a given service if it supports mfa_role and the user has the appropriate attribute.
*
* @param authentication the user authentication object
* @param targetService the target service being tested
* @return a list (usually one) mfa authn request context.
*/
public List<MultiFactorAuthenticationRequestContext> resolve(@NotNull final Authentication authentication, @NotNull final WebApplicationService targetService) {
String authenticationMethodAttributeName = null;
final List<MultiFactorAuthenticationRequestContext> list = new ArrayList<>();
if (authentication != null && targetService != null) {
final ServiceMfaData serviceMfaData = getServicesAuthenticationData(targetService);
if (serviceMfaData == null || !serviceMfaData.isValid()) {
logger.debug("No specific mfa role service attributes found");
return list;
}
logger.debug("Found MFA Role: {}", serviceMfaData);
authenticationMethodAttributeName = serviceMfaData.attributeName;
final Object mfaAttributeValueAsObject = authentication.getPrincipal().getAttributes().get(serviceMfaData.attributeName);
if (mfaAttributeValueAsObject != null) {
if (mfaAttributeValueAsObject instanceof String) {
final String mfaAttributeValue = mfaAttributeValueAsObject.toString();
final MultiFactorAuthenticationRequestContext ctx = getMfaRequestContext(serviceMfaData, mfaAttributeValue, targetService);
if (ctx != null) {
list.add(ctx);
}
} else if (mfaAttributeValueAsObject instanceof List) {
final List<String> mfaAttributeValues = (List<String>) mfaAttributeValueAsObject;
for (final String mfaAttributeValue : mfaAttributeValues) {
final MultiFactorAuthenticationRequestContext ctx = getMfaRequestContext(serviceMfaData, mfaAttributeValue, targetService);
if (ctx != null) {
list.add(ctx);
}
}
} else if (mfaAttributeValueAsObject instanceof Collection) {
final Collection mfaAttributeValues = (Collection) mfaAttributeValueAsObject;
for (final Object mfaAttributeValue : mfaAttributeValues) {
final MultiFactorAuthenticationRequestContext ctx = getMfaRequestContext(serviceMfaData, String.valueOf(mfaAttributeValue), targetService);
if (ctx != null) {
list.add(ctx);
}
}
} else {
logger.debug("No MFA attribute found.");
}
}
}
if (list.isEmpty()) {
logger.debug("No multifactor authentication requests could be resolved based on [{}].", authenticationMethodAttributeName);
return null;
}
return list;
}Example 80
| Project: ebean-master File: AnnotationAssocOnes.java View source code |
private void readAssocOne(DeployBeanPropertyAssocOne<?> prop) {
ManyToOne manyToOne = get(prop, ManyToOne.class);
if (manyToOne != null) {
readManyToOne(manyToOne, prop);
}
OneToOne oneToOne = get(prop, OneToOne.class);
if (oneToOne != null) {
readOneToOne(oneToOne, prop);
}
Embedded embedded = get(prop, Embedded.class);
if (embedded != null) {
readEmbedded(prop, embedded);
}
EmbeddedId emId = get(prop, EmbeddedId.class);
if (emId != null) {
prop.setEmbedded();
prop.setId();
prop.setNullable(false);
}
Column column = get(prop, Column.class);
if (column != null && !isEmpty(column.name())) {
// have this in for AssocOnes used on
// Sql based beans...
prop.setDbColumn(column.name());
}
// May as well check for Id. Makes sense to me.
Id id = get(prop, Id.class);
if (id != null) {
prop.setEmbedded();
prop.setId();
prop.setNullable(false);
}
Where where = get(prop, Where.class);
if (where != null) {
// not expecting this to be used on assoc one properties
prop.setExtraWhere(where.clause());
}
if (validationAnnotations) {
NotNull notNull = get(prop, NotNull.class);
if (notNull != null && isEbeanValidationGroups(notNull.groups())) {
prop.setNullable(false);
// overrides optional attribute of ManyToOne etc
prop.getTableJoin().setType(SqlJoinType.INNER);
}
}
// check for manually defined joins
BeanTable beanTable = prop.getBeanTable();
for (JoinColumn joinColumn : getAll(prop, JoinColumn.class)) {
prop.getTableJoin().addJoinColumn(false, joinColumn, beanTable);
if (!joinColumn.updatable()) {
prop.setDbUpdateable(false);
}
if (!joinColumn.nullable()) {
prop.setNullable(false);
}
}
JoinTable joinTable = get(prop, JoinTable.class);
if (joinTable != null) {
for (JoinColumn joinColumn : joinTable.joinColumns()) {
prop.getTableJoin().addJoinColumn(false, joinColumn, beanTable);
if (!joinColumn.updatable()) {
prop.setDbUpdateable(false);
}
if (!joinColumn.nullable()) {
prop.setNullable(false);
}
}
}
info.setBeanJoinType(prop, prop.isNullable());
if (!prop.getTableJoin().hasJoinColumns() && beanTable != null) {
//noinspection StatementWithEmptyBody
if (prop.getMappedBy() != null) {
// the join is derived by reversing the join information
// from the mapped by property.
// Refer BeanDescriptorManager.readEntityRelationships()
} else {
// use naming convention to define join.
NamingConvention nc = factory.getNamingConvention();
String fkeyPrefix = null;
if (nc.isUseForeignKeyPrefix()) {
fkeyPrefix = nc.getColumnFromProperty(beanType, prop.getName());
}
beanTable.createJoinColumn(fkeyPrefix, prop.getTableJoin(), true, prop.getSqlFormulaSelect());
}
}
}Example 81
| Project: graylog2-server-master File: RestTools.java View source code |
public static String buildEndpointUri(@NotNull HttpHeaders httpHeaders, @NotNull URI defaultEndpointUri) { Optional<String> endpointUri = Optional.empty(); final List<String> headers = httpHeaders.getRequestHeader("X-Graylog-Server-URL"); if (headers != null && !headers.isEmpty()) { endpointUri = headers.stream().filter( s -> { try { if (Strings.isNullOrEmpty(s)) { return false; } final URI uri = new URI(s); if (!uri.isAbsolute()) { return true; } switch(uri.getScheme()) { case "http": case "https": return true; } return false; } catch (URISyntaxException e) { return false; } }).findFirst(); } return endpointUri.orElse(defaultEndpointUri.toString()); }
Example 82
| Project: jarchetypes-master File: InputTextScanner.java View source code |
public void scanForRequired(Class<?> archetype, Member member, WidgetDescriptor descriptor) {
boolean required = false;
try {
boolean isMethodAndHasNotNullAnnotation = member instanceof Method && (((Method) member).isAnnotationPresent(NotNull.class));
boolean isGetterAndFieldHasNotNullAnnotation = member instanceof Method && ArchetypesUtils.isGetter(member.getName()) && ArchetypesUtils.getField(archetype, ArchetypesUtils.getFieldName(member)).isAnnotationPresent(NotNull.class);
required = isMethodAndHasNotNullAnnotation || isGetterAndFieldHasNotNullAnnotation;
} catch (Exception e) {
e.printStackTrace();
}
descriptor.setAttribute("required", required + "");
}Example 83
| Project: java-sproc-wrapper-master File: ValidationExecutorWrapper.java View source code |
private void validateParameters(final InvocationContext invocationContext, final Validator validator, final Object[] originalArgs, final Set<ConstraintViolation<?>> constraintViolations) {
if (originalArgs != null) {
Invokable<?, Object> invokable = Invokable.from(invocationContext.getMethod());
for (int i = 0; i < originalArgs.length; i++) {
Object arg = originalArgs[i];
if (!NOT_NULL_VALIDATOR.isValid(arg, null)) {
// JSR 303 doesn't support method level validation
// we should provide at least a dummy implementation to detect @NotNull annotations
// we should migrate our implementation to bean validation 1.1 when possible
final Parameter parameter = invokable.getParameters().get(i);
final NotNull annotation = parameter.getAnnotation(NotNull.class);
if (annotation != null) {
final String parameterName = "arg" + i;
final ConstraintDescriptor<NotNull> descriptor = new SimpleConstraintDescriptor<NotNull>(annotation, ImmutableSet.<Class<?>>of(Default.class), ImmutableList.<Class<? extends ConstraintValidator<NotNull, ?>>>of(NotNullValidator.class), null);
final ConstraintViolation<Object> violation = new MethodConstraintValidationHolder<Object>(// message
"may not be null", // messageTemplate
annotation.message(), // rootBean
invocationContext.getProxy(), // leafBean (the object the method is executed on)
invocationContext.getProxy(), // propertyPath
SimplePath.createPathForMethodParameter(invocationContext.getMethod(), parameterName), // invalidValue
null, // constraintDescriptor
descriptor, // elementType
ElementType.PARAMETER, // method
invocationContext.getMethod(), // parameterIndex
i, // parameterName
parameterName);
constraintViolations.add(violation);
}
} else {
constraintViolations.addAll(validator.validate(arg));
}
}
}
}Example 84
| Project: joda-beans-ui-master File: MetaUIFactory.java View source code |
/**
* Builds the mandatory flag for the component.
*
* @param comp the component, not null
*/
protected void buildMandatory(MetaUIComponent comp) {
if (comp.getMetaProperty().propertyType().isPrimitive()) {
comp.setMandatory(true);
}
PropertyDefinition propAnno = findAnnotation(comp, PropertyDefinition.class);
if (propAnno != null) {
if (propAnno.validate().equals("notNull") || propAnno.validate().equals("notEmpty")) {
comp.setMandatory(true);
}
}
NotNull nnAnno = findAnnotation(comp, NotNull.class);
if (nnAnno != null) {
comp.setMandatory(true);
}
}Example 85
| Project: molgenis-master File: MolgenisMenuController.java View source code |
@RequestMapping("/{menuId}")
public String forwardMenuDefaultPlugin(@Valid @NotNull @PathVariable String menuId, Model model) {
MolgenisUiMenu menu = molgenisUi.getMenu(menuId);
if (menu == null)
throw new RuntimeException("menu with id [" + menuId + "] does not exist");
model.addAttribute(KEY_MENU_ID, menuId);
MolgenisUiMenuItem activeItem = menu.getActiveItem();
String pluginId = activeItem != null ? activeItem.getId() : VoidPluginController.ID;
String contextUri = new StringBuilder(URI).append('/').append(menuId).append('/').append(pluginId).toString();
model.addAttribute(KEY_CONTEXT_URL, contextUri);
model.addAttribute(KEY_MOLGENIS_VERSION, molgenisVersion);
model.addAttribute(KEY_MOLGENIS_BUILD_DATE, molgenisBuildData);
return getForwardPluginUri(pluginId, null);
}Example 86
| Project: rakam-master File: DynamodbConfigManager.java View source code |
@Override
public <T> T setConfigOnce(String project, String configName, @NotNull T value) {
try {
dynamoDBClient.putItem(new PutItemRequest().withTableName(tableConfig.getTableName()).withExpected(of("id", new ExpectedAttributeValue(false), "project", new ExpectedAttributeValue(false))).withItem(of("project", new AttributeValue(project), "id", new AttributeValue(configName), "value", new AttributeValue(JsonHelper.encode(value)))));
return value;
} catch (Exception e) {
return getConfig(project, configName, (Class<T>) value.getClass());
}
}Example 87
| Project: randi2-master File: AbstractDomainObjectTest.java View source code |
@Test
public void testGetRequieredFields() {
AbstractDomainObject object = new AbstractDomainObject() {
@NotNull
private String newField;
};
assertNotNull(object.getRequiredFields());
Map<String, Boolean> requiredFields = object.getRequiredFields();
for (String key : requiredFields.keySet()) {
if (key.equals("newField")) {
assertTrue(requiredFields.get(key));
} else if (key.equals("this$0")) {
assertFalse(requiredFields.get(key));
} else
fail(key + " not checked");
}
}Example 88
| Project: schema-registry-master File: SubjectsResource.java View source code |
@POST
@Path("/{subject}")
@PerformanceMetric("subjects.get-schema")
public void lookUpSchemaUnderSubject(@Suspended final AsyncResponse asyncResponse, @HeaderParam("Content-Type") final String contentType, @HeaderParam("Accept") final String accept, @PathParam("subject") String subject, @QueryParam("deleted") boolean lookupDeletedSchema, @NotNull RegisterSchemaRequest request) {
// returns version if the schema exists. Otherwise returns 404
Map<String, String> headerProperties = new HashMap<String, String>();
headerProperties.put("Content-Type", contentType);
headerProperties.put("Accept", accept);
Schema schema = new Schema(subject, 0, 0, request.getSchema());
io.confluent.kafka.schemaregistry.client.rest.entities.Schema matchingSchema = null;
try {
if (!schemaRegistry.listSubjects().contains(subject)) {
throw Errors.subjectNotFoundException();
}
matchingSchema = schemaRegistry.lookUpSchemaUnderSubject(subject, schema, lookupDeletedSchema);
} catch (SchemaRegistryException e) {
throw Errors.schemaRegistryException("Error while looking up schema under subject " + subject, e);
}
if (matchingSchema == null) {
throw Errors.schemaNotFoundException();
}
asyncResponse.resume(matchingSchema);
}Example 89
| Project: seed-master File: Node.java View source code |
private Map<String, PropertyInfo> buildPropertyInfo() {
Map<String, PropertyInfo> result = new HashMap<>();
ResourceBundle bundle = null;
try {
bundle = ResourceBundle.getBundle(outermostClass.getName());
} catch (MissingResourceException e) {
}
Object defaultInstance = null;
try {
defaultInstance = Utils.instantiateDefault(configClass);
} catch (Exception e) {
}
for (Field field : configClass.getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
if (field.getType().isAnnotationPresent(Config.class)) {
continue;
}
PropertyInfo propertyInfo = new PropertyInfo();
Config configAnnotation = field.getAnnotation(Config.class);
String name;
if (configAnnotation != null) {
name = configAnnotation.value();
} else {
name = field.getName();
}
field.setAccessible(true);
propertyInfo.setName(name);
propertyInfo.setShortDescription(getMessage(bundle, "No description.", buildKey(name)));
propertyInfo.setLongDescription(getMessage(bundle, null, buildKey(name, "long")));
propertyInfo.setType(Utils.getSimpleTypeName(field.getGenericType()));
propertyInfo.setSingleValue(field.isAnnotationPresent(SingleValue.class));
if (defaultInstance != null) {
try {
propertyInfo.setDefaultValue(field.get(defaultInstance));
} catch (IllegalAccessException e) {
}
}
propertyInfo.setMandatory(propertyInfo.getDefaultValue() == null && Annotations.on(field).includingMetaAnnotations().find(NotNull.class).isPresent());
result.put(name, propertyInfo);
}
return result;
}Example 90
| Project: shop-repo-master File: BestellungServiceImpl.java View source code |
@Override
@NotNull(message = "{bestellung.notFound.id}")
public Bestellung findBestellungById(Long id, FetchType fetch) {
if (id == null) {
return null;
}
Bestellung bestellung;
EntityGraph<?> entityGraph;
Map<String, Object> props;
switch(fetch) {
case NUR_BESTELLUNG:
bestellung = em.find(Bestellung.class, id);
break;
case MIT_LIEFERUNGEN:
entityGraph = em.getEntityGraph(Bestellung.GRAPH_LIEFERUNGEN);
props = ImmutableMap.of(LOADGRAPH, (Object) entityGraph);
bestellung = em.find(Bestellung.class, id, props);
break;
default:
bestellung = em.find(Bestellung.class, id);
break;
}
return bestellung;
}Example 91
| Project: spring-js-master File: ValidatorFactoryTests.java View source code |
@Test
public void testSimpleValidation() throws Exception {
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.afterPropertiesSet();
ValidPerson person = new ValidPerson();
Set<ConstraintViolation<ValidPerson>> result = validator.validate(person);
assertEquals(2, result.size());
for (ConstraintViolation<ValidPerson> cv : result) {
String path = cv.getPropertyPath().toString();
if ("name".equals(path) || "address.street".equals(path)) {
assertTrue(cv.getConstraintDescriptor().getAnnotation() instanceof NotNull);
} else {
fail("Invalid constraint violation with path '" + path + "'");
}
}
}Example 92
| Project: spring4-sandbox-master File: TaskController.java View source code |
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<TaskDetails> getTask(@PathVariable("id") @NotNull Long id) {
Task task = taskRepository.findOne(id);
if (task == null) {
throw new TaskNotFoundException(id);
}
TaskDetails details = new TaskDetails();
details.setId(task.getId());
details.setName(task.getName());
details.setDescription(task.getDescription());
details.setCreatedDate(task.getCreatedDate());
details.setLastModifiedDate(task.getLastModifiedDate());
log.debug("task details@" + details);
return new ResponseEntity<>(details, HttpStatus.OK);
}Example 93
| Project: storm-data-contracts-master File: ContractsBoltReflector.java View source code |
private void checkAnnotations(Class<?> contractClass) {
Field[] fields = contractClass.getFields();
for (Field field : fields) {
Class fieldType = field.getType();
if (Optional.class.isAssignableFrom(fieldType)) {
checkAnnotation(contractClass, field, UnwrapValidatedValue.class);
checkNoAnnotation(contractClass, field, NotNull.class);
} else {
checkNoAnnotation(contractClass, field, UnwrapValidatedValue.class);
checkAnnotation(contractClass, field, NotNull.class);
}
}
for (Method method : contractClass.getMethods()) {
if (method.isAnnotationPresent(AssertTrue.class) || method.isAnnotationPresent(AssertFalse.class)) {
if (method.getReturnType() != boolean.class && method.getReturnType() != Boolean.class) {
throw new IllegalStateException("AssertTrue or AssertFalse annotations must be placed above methods that return boolean value");
}
if (!method.getName().startsWith("is")) {
throw new IllegalStateException("Methods annotated with AssertTrue or AssertFalse must start with \"is\"");
}
}
}
}Example 94
| Project: viritin-master File: MBeanFieldGroupTest.java View source code |
@Test
public void validateOnlyBoundFields() {
Tester2 tester = new Tester2();
//sets only one of NotNull values
tester.setDefaultMessage("test");
TesterForm form = new TesterForm();
MBeanFieldGroup<Tester2> fieldGroup = BeanBinder.bind(tester, form);
Assert.assertTrue(fieldGroup.isValid());
//tells that all properties should be validated
fieldGroup.setValidateOnlyBoundFields(false);
Assert.assertFalse(fieldGroup.isValid());
}Example 95
| Project: visural-wicket-master File: JSR303AnnotatedPropertyModelBehavior.java View source code |
private boolean addValidators(Component component) {
if (FormComponent.class.isAssignableFrom(component.getClass())) {
FormComponent fc = (FormComponent) component;
Object model = component.getDefaultModel();
if (model != null) {
if (AbstractPropertyModel.class.isAssignableFrom(model.getClass())) {
AbstractPropertyModel apm = (AbstractPropertyModel) model;
if (apm.getPropertyField() != null) {
Annotation[] annots = apm.getPropertyField().getAnnotations();
Long min = null;
Long max = null;
for (Annotation a : annots) {
if (a.annotationType().getName().equals("javax.validation.constraints.NotNull")) {
IValidator v = newNotNullValidator();
if (v == null) {
fc.setRequired(true);
} else {
fc.add(v);
}
} else if (a.annotationType().getName().equals("javax.validation.constraints.Min")) {
min = ((Min) a).value();
} else if (a.annotationType().getName().equals("javax.validation.constraints.Max")) {
max = ((Max) a).value();
} else if (a.annotationType().getName().equals("javax.validation.constraints.Past")) {
fc.add(newPastValidator());
} else if (a.annotationType().getName().equals("javax.validation.constraints.Future")) {
fc.add(newFutureValidator());
} else if (a.annotationType().getName().equals("javax.validation.constraints.Pattern")) {
Pattern pattern = (Pattern) a;
fc.add(newPatternValidator(pattern.regexp()));
} else if (a.annotationType().getName().equals("javax.validation.constraints.Size")) {
Size size = (Size) a;
fc.add(newSizeValidator(size.min(), size.max()));
} else if (a.annotationType().getName().equals(getEmailAnnotationClassName())) {
fc.add(newEmailValidator());
}
}
if (max != null || min != null) {
fc.add(newMinMaxValidator(min, max));
}
}
}
return true;
}
}
return false;
}Example 96
| Project: civilization-boardgame-rest-master File: AuthResource.java View source code |
@POST
@Consumes(value = MediaType.APPLICATION_FORM_URLENCODED)
@Produces(value = MediaType.APPLICATION_JSON)
@Path("/login")
public Response login(@FormParam("username") @NotNull String username, @FormParam("password") @NotNull String password) {
Preconditions.checkNotNull(username);
Preconditions.checkNotNull(password);
CivAuthenticator auth = new CivAuthenticator(db);
Optional<Player> playerOptional = auth.authenticate(new BasicCredentials(username, password));
if (playerOptional.isPresent()) {
Player player = playerOptional.get();
URI games = uriInfo.getBaseUriBuilder().path("/player/").path(player.getId()).path("/games").build();
player.setPassword("");
return Response.ok().entity(player).location(games).build();
}
return Response.status(Response.Status.FORBIDDEN).build();
}Example 97
| Project: cxf-master File: JaxRs2Extension.java View source code |
/**
* This is essentially a duplicate of {@link io.swagger.jackson.ModelResolver.applyBeanValidatorAnnotations}.
*
* @param parameter
* @param annotations
*/
private void applyBeanValidatorAnnotations(final Parameter parameter, final List<Annotation> annotations) {
Map<String, Annotation> annos = new HashMap<>();
if (annotations != null) {
for (Annotation annotation : annotations) {
annos.put(annotation.annotationType().getName(), annotation);
}
}
if (annos.containsKey(NotNull.class.getName())) {
parameter.setRequired(true);
}
if (parameter instanceof AbstractSerializableParameter) {
AbstractSerializableParameter<?> serializable = (AbstractSerializableParameter<?>) parameter;
if (annos.containsKey(Min.class.getName())) {
Min min = (Min) annos.get(Min.class.getName());
serializable.setMinimum(BigDecimal.valueOf(min.value()));
}
if (annos.containsKey(Max.class.getName())) {
Max max = (Max) annos.get(Max.class.getName());
serializable.setMaximum(BigDecimal.valueOf(max.value()));
}
if (annos.containsKey(Size.class.getName())) {
Size size = (Size) annos.get(Size.class.getName());
serializable.setMinimum(BigDecimal.valueOf(size.min()));
serializable.setMaximum(BigDecimal.valueOf(size.max()));
serializable.setMinItems(size.min());
serializable.setMaxItems(size.max());
}
if (annos.containsKey(DecimalMin.class.getName())) {
DecimalMin min = (DecimalMin) annos.get(DecimalMin.class.getName());
if (min.inclusive()) {
serializable.setMinimum(BigDecimal.valueOf(new Double(min.value())));
} else {
serializable.setExclusiveMinimum(!min.inclusive());
}
}
if (annos.containsKey(DecimalMax.class.getName())) {
DecimalMax max = (DecimalMax) annos.get(DecimalMax.class.getName());
if (max.inclusive()) {
serializable.setMaximum(BigDecimal.valueOf(new Double(max.value())));
} else {
serializable.setExclusiveMaximum(!max.inclusive());
}
}
if (annos.containsKey(Pattern.class.getName())) {
Pattern pattern = (Pattern) annos.get(Pattern.class.getName());
serializable.setPattern(pattern.regexp());
}
}
}Example 98
| Project: ddf-master File: LogoutMessageImpl.java View source code |
public SignableSAMLObject extractXmlObject(@NotNull String samlLogoutResponse) throws WSSecurityException, XMLStreamException {
Document responseDoc = StaxUtils.read(new ByteArrayInputStream(samlLogoutResponse.getBytes(StandardCharsets.UTF_8)));
XMLObject xmlObject = OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());
if (xmlObject instanceof SignableSAMLObject) {
return (SignableSAMLObject) xmlObject;
}
return null;
}Example 99
| Project: errai-master File: DynamicValidationIntegrationTest.java View source code |
public void testNotNullValidator() throws Exception {
final DynamicValidator validator = IOC.getBeanManager().lookupBean(DynamicValidator.class).getInstance();
assertFalse(validator.validate(NotNull.class, Collections.emptyMap(), null).isEmpty());
assertTrue(validator.validate(NotNull.class, Collections.emptyMap(), new Object()).isEmpty());
assertTrue(validator.validate(NotNull.class, Collections.emptyMap(), "foo").isEmpty());
}Example 100
| Project: fabric8-master File: UserConfigurationCompare.java View source code |
/**
* Compares 2 instances of the given Kubernetes DTO class to see if the user has changed their configuration.
* <p/>
* This method will ignore properties {@link #ignoredProperties} such as status or timestamp properties
*/
protected static boolean configEqualKubernetesDTO(@NotNull Object entity1, @NotNull Object entity2, @NotNull Class<?> clazz) {
// lets iterate through the objects making sure we've not
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo(clazz);
} catch (IntrospectionException e) {
LOG.warn("Failed to get beanInfo for " + clazz.getName() + ". " + e, e);
return false;
}
try {
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
String name = propertyDescriptor.getName();
if (ignoredProperties.contains(name)) {
continue;
}
Method readMethod = propertyDescriptor.getReadMethod();
if (readMethod != null) {
Object value1 = invokeMethod(entity1, readMethod);
Object value2 = invokeMethod(entity2, readMethod);
if (!configEqual(value1, value2)) {
return false;
}
}
}
return true;
} catch (Exception e) {
return false;
}
}Example 101
| Project: gbif-api-master File: DOI.java View source code |
/**
* If the doi is encoded as a URL this method strips the resolver and decodes the URL encoded string entities.
* @param doi not null doi represented as a String
* @return the path part if the doi is a URL otherwise the doi is returned as is.
* @throws IllegalArgumentException
*/
private static String decodeUrl(@NotNull String doi) {
Matcher m = HTTP.matcher(doi);
if (m.find()) {
// strip resolver incl potentially starting paths using a badly encoded urn:doi
// (the colon would need to be encoded in a proper URL)
doi = m.replaceFirst("");
// will just be a path
return URI.create(doi).getPath();
}
return doi;
}