use of org.hisp.dhis.dxf2.importsummary.ImportStatus.ERROR in project dhis2-core by dhis2.
the class SyncUtils method isRemoteServerAvailable.
/**
* Checks the availability of remote server
*
* @param systemSettingManager Reference to SystemSettingManager
* @param restTemplate Reference to RestTemplate
* @return AvailabilityStatus that says whether the server is available or
* not
*/
public static AvailabilityStatus isRemoteServerAvailable(SystemSettingManager systemSettingManager, RestTemplate restTemplate) {
if (!isRemoteServerConfigured(systemSettingManager)) {
return new AvailabilityStatus(false, "Remote server is not configured", HttpStatus.BAD_GATEWAY);
}
String url = systemSettingManager.getStringSetting(SettingKey.REMOTE_INSTANCE_URL) + PING_PATH;
String username = systemSettingManager.getStringSetting(SettingKey.REMOTE_INSTANCE_USERNAME);
String password = systemSettingManager.getStringSetting(SettingKey.REMOTE_INSTANCE_PASSWORD);
log.debug(String.format("Remote server ping URL: %s, username: %s", url, username));
HttpEntity<String> request = getBasicAuthRequestEntity(username, password);
ResponseEntity<String> response = null;
HttpStatus sc = null;
String st = null;
AvailabilityStatus status = null;
try {
response = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
sc = response.getStatusCode();
} catch (HttpClientErrorException | HttpServerErrorException ex) {
sc = ex.getStatusCode();
st = ex.getStatusText();
} catch (ResourceAccessException ex) {
return new AvailabilityStatus(false, "Network is unreachable", HttpStatus.BAD_GATEWAY);
}
log.debug("Response status code: " + sc);
if (HttpStatus.OK.equals(sc)) {
status = new AvailabilityStatus(true, "Authentication was successful", sc);
} else if (HttpStatus.FOUND.equals(sc)) {
status = new AvailabilityStatus(false, "No authentication was provided", sc);
} else if (HttpStatus.UNAUTHORIZED.equals(sc)) {
status = new AvailabilityStatus(false, "Authentication failed", sc);
} else if (HttpStatus.INTERNAL_SERVER_ERROR.equals(sc)) {
status = new AvailabilityStatus(false, "Remote server experienced an internal error", sc);
} else {
status = new AvailabilityStatus(false, "Server is not available: " + st, sc);
}
log.info("Status: " + status);
return status;
}
use of org.hisp.dhis.dxf2.importsummary.ImportStatus.ERROR in project dhis2-core by dhis2.
the class DataValueSetServiceTest method testImportDataValueSetXml.
// -------------------------------------------------------------------------
// Tests
// -------------------------------------------------------------------------
@Test
void testImportDataValueSetXml() throws Exception {
in = new ClassPathResource("datavalueset/dataValueSetA.xml").getInputStream();
ImportSummary summary = dataValueSetService.importDataValueSetXml(in);
assertNotNull(summary);
assertNotNull(summary.getImportCount());
assertEquals(ImportStatus.SUCCESS, summary.getStatus());
assertHasNoConflicts(summary);
Collection<DataValue> dataValues = mockDataValueBatchHandler.getInserts();
Collection<DataValueAudit> auditValues = mockDataValueAuditBatchHandler.getInserts();
assertNotNull(dataValues);
assertEquals(3, dataValues.size());
assertTrue(dataValues.contains(new DataValue(deA, peA, ouA, ocDef, ocDef)));
assertEquals("10002", ((List<DataValue>) dataValues).get(1).getValue());
assertEquals("10003", ((List<DataValue>) dataValues).get(2).getValue());
assertEquals(0, auditValues.size());
// TODO This throw an error : "org.postgresql.util.PSQLException: ERROR:
// cannot execute UPDATE in a read-only transaction"
// Need to investigate
CompleteDataSetRegistration registration = registrationService.getCompleteDataSetRegistration(dsA, peA, ouA, ocDef);
assertNotNull(registration);
assertEquals(dsA, registration.getDataSet());
assertEquals(peA, registration.getPeriod());
assertEquals(ouA, registration.getSource());
assertEquals(getDate(2012, 1, 9), registration.getDate());
}
use of org.hisp.dhis.dxf2.importsummary.ImportStatus.ERROR in project dhis2-core by dhis2.
the class UserController method resendInvite.
@PostMapping(value = "/{id}" + INVITE_PATH)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void resendInvite(@PathVariable String id, HttpServletRequest request) throws Exception {
User user = userService.getUser(id);
if (user == null) {
throw new WebMessageException(conflict("User not found: " + id));
}
if (!user.isInvitation()) {
throw new WebMessageException(conflict("User account is not an invitation: " + id));
}
String valid = securityService.validateRestore(user);
if (valid != null) {
throw new WebMessageException(conflict(valid));
}
boolean isInviteUsername = securityService.isInviteUsername(user.getUsername());
RestoreOptions restoreOptions = isInviteUsername ? RestoreOptions.INVITE_WITH_USERNAME_CHOICE : RestoreOptions.INVITE_WITH_DEFINED_USERNAME;
if (!securityService.sendRestoreOrInviteMessage(user, ContextUtils.getContextPath(request), restoreOptions)) {
throw new WebMessageException(error("Failed to send invite message"));
}
}
use of org.hisp.dhis.dxf2.importsummary.ImportStatus.ERROR in project dhis2-core by dhis2.
the class AccountController method createAccount.
@RequestMapping(method = RequestMethod.POST)
public void createAccount(@RequestParam String username, @RequestParam String firstName, @RequestParam String surname, @RequestParam String password, @RequestParam String email, @RequestParam String phoneNumber, @RequestParam String employer, @RequestParam(required = false) String inviteUsername, @RequestParam(required = false) String inviteToken, @RequestParam(required = false) String inviteCode, @RequestParam(value = "recaptcha_challenge_field", required = false) String recapChallenge, @RequestParam(value = "recaptcha_response_field", required = false) String recapResponse, HttpServletRequest request, HttpServletResponse response) throws WebMessageException {
UserCredentials credentials = null;
boolean invitedByEmail = (inviteUsername != null && !inviteUsername.isEmpty());
boolean canChooseUsername = true;
if (invitedByEmail) {
credentials = userService.getUserCredentialsByUsername(inviteUsername);
if (credentials == null) {
throw new WebMessageException(WebMessageUtils.badRequest("Invitation link not valid"));
}
boolean canRestore = securityService.canRestore(credentials, inviteToken, inviteCode, RestoreType.INVITE);
if (!canRestore) {
throw new WebMessageException(WebMessageUtils.badRequest("Invitation code not valid"));
}
RestoreOptions restoreOptions = securityService.getRestoreOptions(inviteToken);
canChooseUsername = restoreOptions.isUsernameChoice();
} else {
boolean allowed = configurationService.getConfiguration().selfRegistrationAllowed();
if (!allowed) {
throw new WebMessageException(WebMessageUtils.badRequest("User self registration is not allowed"));
}
}
// ---------------------------------------------------------------------
// Trim input
// ---------------------------------------------------------------------
username = StringUtils.trimToNull(username);
firstName = StringUtils.trimToNull(firstName);
surname = StringUtils.trimToNull(surname);
password = StringUtils.trimToNull(password);
email = StringUtils.trimToNull(email);
phoneNumber = StringUtils.trimToNull(phoneNumber);
employer = StringUtils.trimToNull(employer);
recapChallenge = StringUtils.trimToNull(recapChallenge);
recapResponse = StringUtils.trimToNull(recapResponse);
CredentialsInfo credentialsInfo = new CredentialsInfo(username, password, email, true);
if (username == null || username.trim().length() > MAX_LENGTH) {
throw new WebMessageException(WebMessageUtils.badRequest("User name is not specified or invalid"));
}
UserCredentials usernameAlreadyTakenCredentials = userService.getUserCredentialsByUsername(username);
if (canChooseUsername && usernameAlreadyTakenCredentials != null) {
throw new WebMessageException(WebMessageUtils.badRequest("User name is already taken"));
}
if (firstName == null || firstName.trim().length() > MAX_LENGTH) {
throw new WebMessageException(WebMessageUtils.badRequest("First name is not specified or invalid"));
}
if (surname == null || surname.trim().length() > MAX_LENGTH) {
throw new WebMessageException(WebMessageUtils.badRequest("Last name is not specified or invalid"));
}
if (password == null) {
throw new WebMessageException(WebMessageUtils.badRequest("Password is not specified"));
}
PasswordValidationResult result = passwordValidationService.validate(credentialsInfo);
if (!result.isValid()) {
throw new WebMessageException(WebMessageUtils.badRequest(result.getErrorMessage()));
}
if (email == null || !ValidationUtils.emailIsValid(email)) {
throw new WebMessageException(WebMessageUtils.badRequest("Email is not specified or invalid"));
}
if (phoneNumber == null || phoneNumber.trim().length() > MAX_PHONE_NO_LENGTH) {
throw new WebMessageException(WebMessageUtils.badRequest("Phone number is not specified or invalid"));
}
if (employer == null || employer.trim().length() > MAX_LENGTH) {
throw new WebMessageException(WebMessageUtils.badRequest("Employer is not specified or invalid"));
}
if (!systemSettingManager.selfRegistrationNoRecaptcha()) {
if (recapChallenge == null) {
throw new WebMessageException(WebMessageUtils.badRequest("Recaptcha challenge must be specified"));
}
if (recapResponse == null) {
throw new WebMessageException(WebMessageUtils.badRequest("Recaptcha response must be specified"));
}
// ---------------------------------------------------------------------
// Check result from API, return 500 if not
// ---------------------------------------------------------------------
String[] results = checkRecaptcha(KEY, request.getRemoteAddr(), recapChallenge, recapResponse);
if (results == null || results.length == 0) {
throw new WebMessageException(WebMessageUtils.error("Captcha could not be verified due to a server error"));
}
if (!TRUE.equalsIgnoreCase(results[0])) {
log.info("Recaptcha failed with code: " + (results.length > 0 ? results[1] : ""));
throw new WebMessageException(WebMessageUtils.badRequest("The characters you entered did not match the word verification, try again"));
}
}
if (invitedByEmail) {
boolean restored = securityService.restore(credentials, inviteToken, inviteCode, password, RestoreType.INVITE);
if (!restored) {
log.info("Invite restore failed for: " + inviteUsername);
throw new WebMessageException(WebMessageUtils.badRequest("Unable to create invited user account"));
}
User user = credentials.getUserInfo();
user.setFirstName(firstName);
user.setSurname(surname);
user.setEmail(email);
user.setPhoneNumber(phoneNumber);
user.setEmployer(employer);
if (canChooseUsername) {
credentials.setUsername(username);
} else {
username = credentials.getUsername();
}
userService.encodeAndSetPassword(credentials, password);
userService.updateUser(user);
userService.updateUserCredentials(credentials);
log.info("User " + username + " accepted invitation for " + inviteUsername);
} else {
UserAuthorityGroup userRole = configurationService.getConfiguration().getSelfRegistrationRole();
OrganisationUnit orgUnit = configurationService.getConfiguration().getSelfRegistrationOrgUnit();
User user = new User();
user.setFirstName(firstName);
user.setSurname(surname);
user.setEmail(email);
user.setPhoneNumber(phoneNumber);
user.setEmployer(employer);
user.getOrganisationUnits().add(orgUnit);
user.getDataViewOrganisationUnits().add(orgUnit);
credentials = new UserCredentials();
credentials.setUsername(username);
userService.encodeAndSetPassword(credentials, password);
credentials.setSelfRegistered(true);
credentials.setUserInfo(user);
credentials.getUserAuthorityGroups().add(userRole);
user.setUserCredentials(credentials);
userService.addUser(user);
userService.addUserCredentials(credentials);
log.info("Created user with username: " + username);
}
Set<GrantedAuthority> authorities = getAuthorities(credentials.getUserAuthorityGroups());
authenticate(username, password, authorities, request);
webMessageService.send(WebMessageUtils.ok("Account created"), response, request);
}
use of org.hisp.dhis.dxf2.importsummary.ImportStatus.ERROR in project dhis2-core by dhis2.
the class DefaultDataValueSetService method saveDataValueSetCsv.
@Override
public ImportSummary saveDataValueSetCsv(InputStream in, ImportOptions importOptions, TaskId id) {
try {
in = StreamUtils.wrapAndCheckCompressionFormat(in);
DataValueSet dataValueSet = new StreamingCsvDataValueSet(new CsvReader(in, Charset.forName("UTF-8")));
return saveDataValueSet(importOptions, id, dataValueSet);
} catch (Exception ex) {
log.error(DebugUtils.getStackTrace(ex));
notifier.clear(id).notify(id, ERROR, "Process failed: " + ex.getMessage(), true);
return new ImportSummary(ImportStatus.ERROR, "The import process failed: " + ex.getMessage());
}
}
Aggregations