Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow search via post #1176

Open
wants to merge 28 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
10e25c3
allow search via post
hilpitome Nov 16, 2022
9cc4010
rename test methods
hilpitome Nov 16, 2022
93abcba
apply formating
hilpitome Nov 17, 2022
db87055
rename searchByPath methods
hilpitome Nov 23, 2022
87c1806
fix codacy issues
hilpitome Nov 23, 2022
6e72c94
revert deleted exportEventDataMapper
hilpitome Nov 23, 2022
c98a3d1
use SearchService#searchGlobalClient instead of searchClient method
hilpitome Dec 22, 2022
0327bc4
get json string values as null instead of empty string
hilpitome Dec 22, 2022
5739e75
extract out duplicates in old search method
hilpitome Dec 23, 2022
7b80ee6
Trigger checks
hilpitome Dec 23, 2022
11d8a05
update codacy suggestions
hilpitome Jan 9, 2023
92098c9
reduce NPath complexity
hilpitome Jan 9, 2023
451dad7
deduplicate setCoreFilters
hilpitome Jan 9, 2023
b7e27a0
deduplicate setcorefilters
hilpitome Jan 12, 2023
69de169
Trigger checks
hilpitome Jan 13, 2023
042c9a1
fix nullpointerexception from Utils class
hilpitome Jan 13, 2023
4df76a4
use valid opensrp-server-core version
hilpitome Jan 13, 2023
a5b90a5
codacy fixe
hilpitome Jan 16, 2023
a7638bb
apply openmrs formatter
hilpitome Jan 17, 2023
ae921d4
initialize variable
hilpitome Jan 17, 2023
e2004db
fix codacy issue
hilpitome Jan 20, 2023
1fdcb9f
revert to clientService methods without acl
hilpitome Jan 20, 2023
19aaee8
create alpha snapshot for testing
hilpitome Jan 23, 2023
8d879be
version as alpha
hilpitome Jan 23, 2023
d7c6e72
bump up version
hilpitome Mar 7, 2023
17942f6
add logging
hilpitome Mar 8, 2023
4bdc8d8
Merge branch '1172-master-allow-search-via-post' of github.com:opensr…
hilpitome Mar 8, 2023
b229f88
refactor getStringFilter mthd
hilpitome Mar 9, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
369 changes: 187 additions & 182 deletions src/main/java/org/opensrp/web/rest/RestUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.joda.time.DateTime;
import org.json.JSONObject;
import org.keycloak.KeycloakPrincipal;
import org.keycloak.KeycloakSecurityContext;
import org.keycloak.representations.AccessToken;
Expand All @@ -30,101 +31,108 @@
import java.util.zip.ZipOutputStream;

public class RestUtils {
public static final String DATE_FORMAT = "dd-MM-yyyy";
public static final SimpleDateFormat SDF = new SimpleDateFormat("dd-MM-yyyy");
public static final String DATETIME_FORMAT = "dd-MM-yyyy HH:mm";
public static final SimpleDateFormat SDTF = new SimpleDateFormat("dd-MM-yyyy HH:mm");

private static final Logger logger = LogManager.getLogger(RestUtils.class.toString());


public static String getStringFilter(String filter, HttpServletRequest req)
{
return StringUtils.isBlank(req.getParameter(filter)) ? null : req.getParameter(filter);
}

@SuppressWarnings({ "unchecked", "rawtypes" })
public static Enum getEnumFilter(String filter, Class cls, HttpServletRequest req)
{
String filterVal = getStringFilter(filter, req);
if (filterVal != null) {
return Enum.valueOf(cls, filterVal);
}
return null;
}

public static Integer getIntegerFilter(String filter, HttpServletRequest req)
{
String strval = getStringFilter(filter, req);
return strval == null ? null : Integer.parseInt(strval);
}

public static Float getFloatFilter(String filter, HttpServletRequest req)
{
String strval = getStringFilter(filter, req);
return strval == null ? null : Float.parseFloat(strval);
}

public static DateTime getDateFilter(String filter, HttpServletRequest req) throws ParseException
{
String strval = getStringFilter(filter, req);
return strval == null ? null : new DateTime(strval);
}

public static DateTime[] getDateRangeFilter(String filter, HttpServletRequest req) throws ParseException {
String strval = getStringFilter(filter, req);
if (strval == null) {
return null;
}
if (!strval.contains(":")) {
return new DateTime[] { new DateTime(strval), new DateTime(strval) };
}
DateTime d1 = new DateTime(strval.substring(0, strval.indexOf(":")));
DateTime d2 = new DateTime(strval.substring(strval.indexOf(":") + 1));
return new DateTime[] { d1, d2 };
}

public static boolean getBooleanFilter(String filter, HttpServletRequest req) {
String stringFilter = getStringFilter(filter, req);
return Boolean.parseBoolean(stringFilter);
}

public static void main(String[] args) {
System.out.println(new DateTime("​1458932400000"));
}

public static synchronized String setDateFilter(Date date) throws ParseException
{
return date == null ? null : SDF.format(date);
}

public static <T> void verifyRequiredProperties(List<String> properties, T entity) {
if(properties != null)
for (String p : properties) {
Field[] aaa = entity.getClass().getDeclaredFields();
for (Field field : aaa) {
if(field.getName().equals(p)){
field.setAccessible(true);
try {
if(field.get(entity) == null || field.get(entity).toString().trim().equalsIgnoreCase("")){
throw new RuntimeException("A required field "+p+" was found empty");
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw new RuntimeException("A required field "+p+" was not found in resource class");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}

public static HttpHeaders getJSONUTF8Headers() {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "application/json; charset=utf-8");
return responseHeaders;
}
public static final String DATE_FORMAT = "dd-MM-yyyy";
public static final SimpleDateFormat SDF = new SimpleDateFormat("dd-MM-yyyy");
public static final String DATETIME_FORMAT = "dd-MM-yyyy HH:mm";
public static final SimpleDateFormat SDTF = new SimpleDateFormat("dd-MM-yyyy HH:mm");

private static final Logger logger = LogManager.getLogger(RestUtils.class.toString());


public static String getStringFilter(String filter, HttpServletRequest req) {
return StringUtils.isBlank(req.getParameter(filter)) ? null : req.getParameter(filter);
}

@SuppressWarnings({"unchecked", "rawtypes"})
public static Enum getEnumFilter(String filter, Class cls, HttpServletRequest req) {
String filterVal = getStringFilter(filter, req);
if (filterVal != null) {
return Enum.valueOf(cls, filterVal);
}
return null;
}

public static Integer getIntegerFilter(String filter, HttpServletRequest req) {
String strval = getStringFilter(filter, req);
return strval == null ? null : Integer.parseInt(strval);
}

public static Float getFloatFilter(String filter, HttpServletRequest req) {
String strval = getStringFilter(filter, req);
return strval == null ? null : Float.parseFloat(strval);
}

public static DateTime getDateFilter(String filter, HttpServletRequest req) throws ParseException {
String strval = getStringFilter(filter, req);
return strval == null ? null : new DateTime(strval);
}

public static DateTime[] getDateRangeFilter(String filter, HttpServletRequest req) throws ParseException {
String strval = getStringFilter(filter, req);
if (strval == null) {
return null;
}
if (!strval.contains(":")) {
return new DateTime[]{new DateTime(strval), new DateTime(strval)};
}
DateTime d1 = new DateTime(strval.substring(0, strval.indexOf(":")));
DateTime d2 = new DateTime(strval.substring(strval.indexOf(":") + 1));
return new DateTime[]{d1, d2};
}

public static DateTime[] getDateRangeFilter(String filter, JSONObject jsonObject) throws ParseException {
String strval = jsonObject.optString(filter);
if (strval.equals("")) {
return null;
}
if (!strval.contains(":")) {
return new DateTime[]{new DateTime(strval), new DateTime(strval)};
}
DateTime d1 = new DateTime(strval.substring(0, strval.indexOf(":")));
DateTime d2 = new DateTime(strval.substring(strval.indexOf(":") + 1));
return new DateTime[]{d1, d2};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we handle cases of an invalid format for strval?

}

public static boolean getBooleanFilter(String filter, HttpServletRequest req) {
String stringFilter = getStringFilter(filter, req);
return Boolean.parseBoolean(stringFilter);
}

public static void main(String[] args) {
System.out.println(new DateTime("​1458932400000"));
}

public static synchronized String setDateFilter(Date date) throws ParseException {
return date == null ? null : SDF.format(date);
}

public static <T> void verifyRequiredProperties(List<String> properties, T entity) {
if (properties != null)
for (String p : properties) {
Field[] aaa = entity.getClass().getDeclaredFields();
for (Field field : aaa) {
if (field.getName().equals(p)) {
field.setAccessible(true);
try {
if (field.get(entity) == null || field.get(entity).toString().trim().equalsIgnoreCase("")) {
throw new RuntimeException("A required field " + p + " was found empty");
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw new RuntimeException("A required field " + p + " was not found in resource class");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}

public static HttpHeaders getJSONUTF8Headers() {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "application/json; charset=utf-8");
return responseHeaders;
}

/**
* Zips multimedia files and writes content to {@param zipOutputStream}
Expand All @@ -133,92 +141,89 @@ public static HttpHeaders getJSONUTF8Headers() {
* @param multimediaFiles
* @throws IOException
*/
public static void zipFiles(ZipOutputStream zipOutputStream, List<Multimedia> multimediaFiles, MultimediaFileManager fileManager) throws
IOException {
for (Multimedia multiMedia : multimediaFiles) {
FileInputStream inputStream;
File file = fileManager.retrieveFile(multiMedia.getFilePath());
if (file != null) {
logger.info("Adding " + file.getName());
zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
try {
inputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
logger.warn("Could not find file " + file.getAbsolutePath());
continue;
}

// Write the contents of the file
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
int data;
while ((data = bufferedInputStream.read()) != -1) {
zipOutputStream.write(data);
}
bufferedInputStream.close();
zipOutputStream.closeEntry();
logger.info("Done downloading file " + file.getName());

// clean up temp files (may want to cache in future)
if (fileManager instanceof S3MultimediaFileManager) {
file.delete();
}
}
}
}

public static User currentUser(Authentication authentication) {
if (authentication != null && authentication.getPrincipal() instanceof KeycloakPrincipal) {
@SuppressWarnings("unchecked")
KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>) authentication
.getPrincipal();
AccessToken token = kp.getKeycloakSecurityContext().getToken();
User user = new User(authentication.getName());
user.setPreferredName(token.getName());
user.setUsername(token.getPreferredUsername());
List<String> authorities = authentication.getAuthorities().stream().map(e -> e.getAuthority())
.collect(Collectors.toList());
user.setAttributes(token.getOtherClaims());
user.setRoles(authorities);
user.setPermissions(authorities);
return user;
}
return null;
}

public static void writeToZipFile(String fileName, ZipOutputStream zipStream, String filePath) throws IOException {
File aFile;
FileInputStream fis = null;
ZipEntry zipEntry;
String tempDirectory = System.getProperty("java.io.tmpdir");
try{
if(StringUtils.isNotBlank(fileName)) {
aFile = new File(StringUtils.isNotBlank(filePath) ? filePath : fileName);
fis = new FileInputStream(aFile);
zipEntry = new ZipEntry(StringUtils.isNotBlank(filePath) ? filePath.replace(tempDirectory, "") : fileName);
logger.info("Writing file : '" + fileName + "' to zip file");
}
else {
fis = new FileInputStream(filePath);
zipEntry = new ZipEntry(filePath);
logger.info("Writing file : '" + filePath + "' to zip file");
}
zipStream.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipStream.write(bytes, 0, length);
}

zipStream.closeEntry();
}
catch (IOException e) {
logger.error("IO Exception occurred: " + e.getMessage());
}
finally {
if (fis != null) {
fis.close();
}
}
}
public static void zipFiles(ZipOutputStream zipOutputStream, List<Multimedia> multimediaFiles, MultimediaFileManager fileManager) throws
IOException {
for (Multimedia multiMedia : multimediaFiles) {
FileInputStream inputStream;
File file = fileManager.retrieveFile(multiMedia.getFilePath());
if (file != null) {
logger.info("Adding " + file.getName());
zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
try {
inputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
logger.warn("Could not find file " + file.getAbsolutePath());
continue;
}

// Write the contents of the file
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
int data;
while ((data = bufferedInputStream.read()) != -1) {
zipOutputStream.write(data);
}
bufferedInputStream.close();
zipOutputStream.closeEntry();
logger.info("Done downloading file " + file.getName());

// clean up temp files (may want to cache in future)
if (fileManager instanceof S3MultimediaFileManager) {
file.delete();
}
}
}
}

public static User currentUser(Authentication authentication) {
if (authentication != null && authentication.getPrincipal() instanceof KeycloakPrincipal) {
@SuppressWarnings("unchecked")
KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>) authentication
.getPrincipal();
AccessToken token = kp.getKeycloakSecurityContext().getToken();
User user = new User(authentication.getName());
user.setPreferredName(token.getName());
user.setUsername(token.getPreferredUsername());
List<String> authorities = authentication.getAuthorities().stream().map(e -> e.getAuthority())
.collect(Collectors.toList());
user.setAttributes(token.getOtherClaims());
user.setRoles(authorities);
user.setPermissions(authorities);
return user;
}
return null;
}

public static void writeToZipFile(String fileName, ZipOutputStream zipStream, String filePath) throws IOException {
File aFile;
FileInputStream fis = null;
ZipEntry zipEntry;
String tempDirectory = System.getProperty("java.io.tmpdir");
try {
if (StringUtils.isNotBlank(fileName)) {
aFile = new File(StringUtils.isNotBlank(filePath) ? filePath : fileName);
fis = new FileInputStream(aFile);
zipEntry = new ZipEntry(StringUtils.isNotBlank(filePath) ? filePath.replace(tempDirectory, "") : fileName);
logger.info("Writing file : '" + fileName + "' to zip file");
} else {
fis = new FileInputStream(filePath);
zipEntry = new ZipEntry(filePath);
logger.info("Writing file : '" + filePath + "' to zip file");
}
zipStream.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipStream.write(bytes, 0, length);
}

zipStream.closeEntry();
} catch (IOException e) {
logger.error("IO Exception occurred: " + e.getMessage());
} finally {
if (fis != null) {
fis.close();
}
}
}

}
Loading