use of javax.json.JsonArrayBuilder in project dataverse by IQSS.
the class Admin method builtin2shib.
/**
* This is used in testing via AdminIT.java but we don't expect sysadmins to
* use this.
*/
@Path("authenticatedUsers/convert/builtin2shib")
@PUT
public Response builtin2shib(String content) {
logger.info("entering builtin2shib...");
try {
AuthenticatedUser userToRunThisMethod = findAuthenticatedUserOrDie();
if (!userToRunThisMethod.isSuperuser()) {
return error(Response.Status.FORBIDDEN, "Superusers only.");
}
} catch (WrappedResponse ex) {
return error(Response.Status.FORBIDDEN, "Superusers only.");
}
boolean disabled = false;
if (disabled) {
return error(Response.Status.BAD_REQUEST, "API endpoint disabled.");
}
AuthenticatedUser builtInUserToConvert = null;
String emailToFind;
String password;
// could let people specify id on authuser table. probably better to let them tell us their
String authuserId = "0";
String newEmailAddressToUse;
try {
String[] args = content.split(":");
emailToFind = args[0];
password = args[1];
newEmailAddressToUse = args[2];
// authuserId = args[666];
} catch (ArrayIndexOutOfBoundsException ex) {
return error(Response.Status.BAD_REQUEST, "Problem with content <<<" + content + ">>>: " + ex.toString());
}
AuthenticatedUser existingAuthUserFoundByEmail = shibService.findAuthUserByEmail(emailToFind);
String existing = "NOT FOUND";
if (existingAuthUserFoundByEmail != null) {
builtInUserToConvert = existingAuthUserFoundByEmail;
existing = existingAuthUserFoundByEmail.getIdentifier();
} else {
long longToLookup = Long.parseLong(authuserId);
AuthenticatedUser specifiedUserToConvert = authSvc.findByID(longToLookup);
if (specifiedUserToConvert != null) {
builtInUserToConvert = specifiedUserToConvert;
} else {
return error(Response.Status.BAD_REQUEST, "No user to convert. We couldn't find a *single* existing user account based on " + emailToFind + " and no user was found using specified id " + longToLookup);
}
}
String shibProviderId = ShibAuthenticationProvider.PROVIDER_ID;
Map<String, String> randomUser = authTestDataService.getRandomUser();
// String eppn = UUID.randomUUID().toString().substring(0, 8);
String eppn = randomUser.get("eppn");
String idPEntityId = randomUser.get("idp");
String notUsed = null;
String separator = "|";
UserIdentifier newUserIdentifierInLookupTable = new UserIdentifier(idPEntityId + separator + eppn, notUsed);
String overwriteFirstName = randomUser.get("firstName");
String overwriteLastName = randomUser.get("lastName");
String overwriteEmail = randomUser.get("email");
overwriteEmail = newEmailAddressToUse;
logger.info("overwriteEmail: " + overwriteEmail);
boolean validEmail = EMailValidator.isEmailValid(overwriteEmail, null);
if (!validEmail) {
// See https://github.com/IQSS/dataverse/issues/2998
return error(Response.Status.BAD_REQUEST, "invalid email: " + overwriteEmail);
}
/**
* @todo If affiliation is not null, put it in RoleAssigneeDisplayInfo
* constructor.
*/
/**
* Here we are exercising (via an API test) shibService.getAffiliation
* with the TestShib IdP and a non-production DevShibAccountType.
*/
idPEntityId = ShibUtil.testShibIdpEntityId;
String overwriteAffiliation = shibService.getAffiliation(idPEntityId, ShibServiceBean.DevShibAccountType.RANDOM);
logger.info("overwriteAffiliation: " + overwriteAffiliation);
/**
* @todo Find a place to put "position" in the authenticateduser table:
* https://github.com/IQSS/dataverse/issues/1444#issuecomment-74134694
*/
String overwritePosition = "staff;student";
AuthenticatedUserDisplayInfo displayInfo = new AuthenticatedUserDisplayInfo(overwriteFirstName, overwriteLastName, overwriteEmail, overwriteAffiliation, overwritePosition);
JsonObjectBuilder response = Json.createObjectBuilder();
JsonArrayBuilder problems = Json.createArrayBuilder();
if (password != null) {
response.add("password supplied", password);
boolean knowsExistingPassword = false;
BuiltinUser oldBuiltInUser = builtinUserService.findByUserName(builtInUserToConvert.getUserIdentifier());
if (oldBuiltInUser != null) {
String usernameOfBuiltinAccountToConvert = oldBuiltInUser.getUserName();
response.add("old username", usernameOfBuiltinAccountToConvert);
AuthenticatedUser authenticatedUser = authSvc.canLogInAsBuiltinUser(usernameOfBuiltinAccountToConvert, password);
if (authenticatedUser != null) {
knowsExistingPassword = true;
AuthenticatedUser convertedUser = authSvc.convertBuiltInToShib(builtInUserToConvert, shibProviderId, newUserIdentifierInLookupTable);
if (convertedUser != null) {
/**
* @todo Display name is not being overwritten. Logic
* must be in Shib backing bean
*/
AuthenticatedUser updatedInfoUser = authSvc.updateAuthenticatedUser(convertedUser, displayInfo);
if (updatedInfoUser != null) {
response.add("display name overwritten with", updatedInfoUser.getName());
} else {
problems.add("couldn't update display info");
}
} else {
problems.add("unable to convert user");
}
}
} else {
problems.add("couldn't find old username");
}
if (!knowsExistingPassword) {
String message = "User doesn't know password.";
problems.add(message);
/**
* @todo Someday we should make a errorResponse method that
* takes JSON arrays and objects.
*/
return error(Status.BAD_REQUEST, problems.build().toString());
}
// response.add("knows existing password", knowsExistingPassword);
}
response.add("user to convert", builtInUserToConvert.getIdentifier());
response.add("existing user found by email (prompt to convert)", existing);
response.add("changing to this provider", shibProviderId);
response.add("value to overwrite old first name", overwriteFirstName);
response.add("value to overwrite old last name", overwriteLastName);
response.add("value to overwrite old email address", overwriteEmail);
if (overwriteAffiliation != null) {
response.add("affiliation", overwriteAffiliation);
}
response.add("problems", problems);
return ok(response);
}
use of javax.json.JsonArrayBuilder in project dataverse by IQSS.
the class Admin method listAuthenticatedUsers.
@Deprecated
@GET
@Path("authenticatedUsers")
public Response listAuthenticatedUsers() {
try {
AuthenticatedUser user = findAuthenticatedUserOrDie();
if (!user.isSuperuser()) {
return error(Response.Status.FORBIDDEN, "Superusers only.");
}
} catch (WrappedResponse ex) {
return error(Response.Status.FORBIDDEN, "Superusers only.");
}
JsonArrayBuilder userArray = Json.createArrayBuilder();
authSvc.findAllAuthenticatedUsers().stream().forEach((user) -> {
userArray.add(json(user));
});
return ok(userArray);
}
use of javax.json.JsonArrayBuilder in project dataverse by IQSS.
the class Admin method builtin2oauth.
/**
* This is used in testing via AdminIT.java but we don't expect sysadmins to
* use this.
*/
@Path("authenticatedUsers/convert/builtin2oauth")
@PUT
public Response builtin2oauth(String content) {
logger.info("entering builtin2oauth...");
try {
AuthenticatedUser userToRunThisMethod = findAuthenticatedUserOrDie();
if (!userToRunThisMethod.isSuperuser()) {
return error(Response.Status.FORBIDDEN, "Superusers only.");
}
} catch (WrappedResponse ex) {
return error(Response.Status.FORBIDDEN, "Superusers only.");
}
boolean disabled = false;
if (disabled) {
return error(Response.Status.BAD_REQUEST, "API endpoint disabled.");
}
AuthenticatedUser builtInUserToConvert = null;
String emailToFind;
String password;
// could let people specify id on authuser table. probably better to let them tell us their
String authuserId = "0";
String newEmailAddressToUse;
String newProviderId;
String newPersistentUserIdInLookupTable;
logger.info("content: " + content);
try {
String[] args = content.split(":");
emailToFind = args[0];
password = args[1];
newEmailAddressToUse = args[2];
newProviderId = args[3];
newPersistentUserIdInLookupTable = args[4];
// authuserId = args[666];
} catch (ArrayIndexOutOfBoundsException ex) {
return error(Response.Status.BAD_REQUEST, "Problem with content <<<" + content + ">>>: " + ex.toString());
}
AuthenticatedUser existingAuthUserFoundByEmail = shibService.findAuthUserByEmail(emailToFind);
String existing = "NOT FOUND";
if (existingAuthUserFoundByEmail != null) {
builtInUserToConvert = existingAuthUserFoundByEmail;
existing = existingAuthUserFoundByEmail.getIdentifier();
} else {
long longToLookup = Long.parseLong(authuserId);
AuthenticatedUser specifiedUserToConvert = authSvc.findByID(longToLookup);
if (specifiedUserToConvert != null) {
builtInUserToConvert = specifiedUserToConvert;
} else {
return error(Response.Status.BAD_REQUEST, "No user to convert. We couldn't find a *single* existing user account based on " + emailToFind + " and no user was found using specified id " + longToLookup);
}
}
// String shibProviderId = ShibAuthenticationProvider.PROVIDER_ID;
Map<String, String> randomUser = authTestDataService.getRandomUser();
// String eppn = UUID.randomUUID().toString().substring(0, 8);
String eppn = randomUser.get("eppn");
String idPEntityId = randomUser.get("idp");
String notUsed = null;
String separator = "|";
// UserIdentifier newUserIdentifierInLookupTable = new UserIdentifier(idPEntityId + separator + eppn, notUsed);
UserIdentifier newUserIdentifierInLookupTable = new UserIdentifier(newPersistentUserIdInLookupTable, notUsed);
String overwriteFirstName = randomUser.get("firstName");
String overwriteLastName = randomUser.get("lastName");
String overwriteEmail = randomUser.get("email");
overwriteEmail = newEmailAddressToUse;
logger.info("overwriteEmail: " + overwriteEmail);
boolean validEmail = EMailValidator.isEmailValid(overwriteEmail, null);
if (!validEmail) {
// See https://github.com/IQSS/dataverse/issues/2998
return error(Response.Status.BAD_REQUEST, "invalid email: " + overwriteEmail);
}
/**
* @todo If affiliation is not null, put it in RoleAssigneeDisplayInfo
* constructor.
*/
/**
* Here we are exercising (via an API test) shibService.getAffiliation
* with the TestShib IdP and a non-production DevShibAccountType.
*/
// idPEntityId = ShibUtil.testShibIdpEntityId;
// String overwriteAffiliation = shibService.getAffiliation(idPEntityId, ShibServiceBean.DevShibAccountType.RANDOM);
String overwriteAffiliation = null;
logger.info("overwriteAffiliation: " + overwriteAffiliation);
/**
* @todo Find a place to put "position" in the authenticateduser table:
* https://github.com/IQSS/dataverse/issues/1444#issuecomment-74134694
*/
String overwritePosition = "staff;student";
AuthenticatedUserDisplayInfo displayInfo = new AuthenticatedUserDisplayInfo(overwriteFirstName, overwriteLastName, overwriteEmail, overwriteAffiliation, overwritePosition);
JsonObjectBuilder response = Json.createObjectBuilder();
JsonArrayBuilder problems = Json.createArrayBuilder();
if (password != null) {
response.add("password supplied", password);
boolean knowsExistingPassword = false;
BuiltinUser oldBuiltInUser = builtinUserService.findByUserName(builtInUserToConvert.getUserIdentifier());
if (oldBuiltInUser != null) {
String usernameOfBuiltinAccountToConvert = oldBuiltInUser.getUserName();
response.add("old username", usernameOfBuiltinAccountToConvert);
AuthenticatedUser authenticatedUser = authSvc.canLogInAsBuiltinUser(usernameOfBuiltinAccountToConvert, password);
if (authenticatedUser != null) {
knowsExistingPassword = true;
AuthenticatedUser convertedUser = authSvc.convertBuiltInUserToRemoteUser(builtInUserToConvert, newProviderId, newUserIdentifierInLookupTable);
if (convertedUser != null) {
/**
* @todo Display name is not being overwritten. Logic
* must be in Shib backing bean
*/
AuthenticatedUser updatedInfoUser = authSvc.updateAuthenticatedUser(convertedUser, displayInfo);
if (updatedInfoUser != null) {
response.add("display name overwritten with", updatedInfoUser.getName());
} else {
problems.add("couldn't update display info");
}
} else {
problems.add("unable to convert user");
}
}
} else {
problems.add("couldn't find old username");
}
if (!knowsExistingPassword) {
String message = "User doesn't know password.";
problems.add(message);
/**
* @todo Someday we should make a errorResponse method that
* takes JSON arrays and objects.
*/
return error(Status.BAD_REQUEST, problems.build().toString());
}
// response.add("knows existing password", knowsExistingPassword);
}
response.add("user to convert", builtInUserToConvert.getIdentifier());
response.add("existing user found by email (prompt to convert)", existing);
response.add("changing to this provider", newProviderId);
response.add("value to overwrite old first name", overwriteFirstName);
response.add("value to overwrite old last name", overwriteLastName);
response.add("value to overwrite old email address", overwriteEmail);
if (overwriteAffiliation != null) {
response.add("affiliation", overwriteAffiliation);
}
response.add("problems", problems);
return ok(response);
}
use of javax.json.JsonArrayBuilder in project dataverse by IQSS.
the class BatchServiceBean method processFilePath.
@Asynchronous
public void processFilePath(String fileDir, String parentIdtf, DataverseRequest dataverseRequest, Dataverse owner, ImportUtil.ImportType importType, Boolean createDV) {
logger.info("BEGIN IMPORT");
PrintWriter validationLog = null;
PrintWriter cleanupLog = null;
try {
JsonArrayBuilder status = Json.createArrayBuilder();
Date timestamp = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
validationLog = new PrintWriter(new FileWriter("../logs/validationLog" + formatter.format(timestamp) + ".txt"));
cleanupLog = new PrintWriter(new FileWriter("../logs/cleanupLog" + formatter.format(timestamp) + ".txt"));
File dir = new File(fileDir);
if (dir.isDirectory()) {
for (File file : dir.listFiles()) {
if (!file.isHidden()) {
if (file.isDirectory()) {
try {
status.add(handleDirectory(dataverseRequest, file, importType, validationLog, cleanupLog, createDV));
} catch (ImportException e) {
logger.log(Level.SEVERE, "Exception in handleDirectory() for " + file.getName(), e);
}
} else {
try {
status.add(importService.handleFile(dataverseRequest, owner, file, importType, validationLog, cleanupLog));
} catch (ImportException e) {
logger.log(Level.SEVERE, "Exception in handleFile() for " + file.getName(), e);
}
}
}
}
} else {
status.add(importService.handleFile(dataverseRequest, owner, dir, importType, validationLog, cleanupLog));
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Exception in processFilePath()", e);
} finally {
validationLog.close();
cleanupLog.close();
}
logger.info("END IMPORT");
}
use of javax.json.JsonArrayBuilder in project dataverse by IQSS.
the class JsonParserTest method testparseFiles.
@Test
public void testparseFiles() throws JsonParseException {
JsonArrayBuilder metadatasJsonBuilder = Json.createArrayBuilder();
JsonObjectBuilder fileMetadataGood = Json.createObjectBuilder();
fileMetadataGood.add("label", "myLabel");
JsonObjectBuilder fileGood = Json.createObjectBuilder();
fileMetadataGood.add("dataFile", fileGood);
fileMetadataGood.add("categories", Json.createArrayBuilder().add("Documentation"));
JsonObjectBuilder fileMetadataBad = Json.createObjectBuilder();
fileMetadataBad.add("label", "bad");
JsonObjectBuilder fileBad = Json.createObjectBuilder();
fileMetadataBad.add("dataFile", fileBad);
fileMetadataBad.add("categories", Json.createArrayBuilder().add(BigDecimal.ONE));
metadatasJsonBuilder.add(fileMetadataGood);
metadatasJsonBuilder.add(fileMetadataBad);
JsonArray metadatasJson = metadatasJsonBuilder.build();
DatasetVersion dsv = new DatasetVersion();
Dataset dataset = new Dataset();
dsv.setDataset(dataset);
List<FileMetadata> fileMetadatas = new JsonParser().parseFiles(metadatasJson, dsv);
System.out.println("fileMetadatas: " + fileMetadatas);
assertEquals("myLabel", fileMetadatas.get(0).getLabel());
assertEquals("Documentation", fileMetadatas.get(0).getCategories().get(0).getName());
assertEquals(null, fileMetadatas.get(1).getCategories());
List<FileMetadata> codeCoverage = new JsonParser().parseFiles(Json.createArrayBuilder().add(Json.createObjectBuilder().add("label", "myLabel").add("dataFile", Json.createObjectBuilder().add("categories", JsonValue.NULL))).build(), dsv);
assertEquals(null, codeCoverage.get(0).getCategories());
}
Aggregations