Pdf file renaming and deleting not working in Android 10 using MediaStore - pdf

I create an app that fetch all pdf documents from Phone storage... But in Android 10 devices , all pdfs not retrieved ... and even when I shall be tried to rename the pdf file , the pdf file is gone...
this is my code :
#NonNull
public ArrayList getAllPdfs(#NonNull Context context1) {
String str = null;
Uri collection;
ArrayList<PdfModel> arrayList = new ArrayList<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
collection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
} else {
collection = MediaStore.Files.getContentUri("external");
}
// collection = MediaStore.Files.getContentUri("external");
try {
final String[] projection = new String[]{
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.DISPLAY_NAME,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.MIME_TYPE,
};
Context context = getActivity();
SharedPreferences save_preferences = homeContext.getSharedPreferences(MY_SORT_PREF,
MODE_PRIVATE);
SharedPreferences preferencesOrder = homeContext.getSharedPreferences("Order", MODE_PRIVATE);
String order_by_descending = preferencesOrder.getString("order", "descending");
String order = null;
switch (order_by_descending) {
case "descending":
String sort = save_preferences.getString("sorting", "SortByDate");
switch (sort) {
case "SortByName":
order = MediaStore.Files.FileColumns.DISPLAY_NAME + " DESC";
break;
case "SortByDate":
order = MediaStore.Files.FileColumns.DATE_ADDED + " DESC";
break;
case "SortBySize":
order = MediaStore.Files.FileColumns.SIZE + " DESC";
break;
}
break;
case "ascending":
String sort_date = save_preferences.getString("sorting", "SortByDate");
switch (sort_date) {
case "SortByName":
order = MediaStore.Files.FileColumns.DISPLAY_NAME + " ASC";
break;
case "SortByDate":
order = MediaStore.Files.FileColumns.DATE_ADDED + " ASC";
break;
case "SortBySize":
order = MediaStore.Files.FileColumns.SIZE + " ASC";
break;
}
break;
}
final String selection = MediaStore.Files.FileColumns.MIME_TYPE + " = ?";
final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
final String[] selectionArgs = new String[]{mimeType};
CursorLoader cursorLoader = new CursorLoader(context1, collection, projection, selection,
selectionArgs, order);
Cursor cursor = cursorLoader.loadInBackground();
if (cursor != null && cursor.moveToFirst()) {
do {
int columnName = cursor.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME);
int columnData = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
String path = cursor.getString(columnData);
if (new File(path).exists()) {
#SuppressLint("Range")
File file = new
File(cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA)));
if (file.exists()) {
Log.d(TAG, "getAllPdfs: a " + file.length());
PdfModel pdfModel = new PdfModel();
//------------------------------Remove (.pdf) extension------------------------
String fileName = file.getName();
if (fileName.indexOf(".") > 0)
fileName = fileName.substring(0, fileName.lastIndexOf("."));
Uri imageUri = Uri.fromFile(file.getAbsoluteFile());
Log.d(TAG, "getAllPdfs: bb " + file.getName());
pdfModel.setId(file.getName());
pdfModel.setName(removeExtension(file.getName()));
pdfModel.setAbsolutePath(file.getAbsolutePath());
pdfModel.setParentFilePath(Objects.requireNonNull(file.getParentFile()).getName());
pdfModel.setPdfUri(file.toString());
pdfModel.setLength(file.length());
pdfModel.setLastModified(file.lastModified());
//pdfModel.setThumbNailUri(file.);
arrayList.add(pdfModel);
} else {
Log.d(TAG, "getAllPdfs: ");
}
}
} while (cursor.moveToNext());
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return arrayList;
}
Please solve this problem ....

Related

Android MPAndroidChart xAxis.setValueFormatter throws ArrayIndexOutOfBoundsException

Good morning,
I'm struggling with ArrayIndexOutOfBoundsException thrown when i'm inserting the row
xAxis.setValueFormatter(formatter) (commented in code).
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bc = findViewById(R.id.chart);
CaricaStorico cs = new CaricaStorico();
try {
cs.execute().get();
} catch (ExecutionException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
List<BarEntry> turno1 = new ArrayList<>();
List<BarEntry> turno2 = new ArrayList<>();
List<BarEntry> turno3 = new ArrayList<>();
String[] date = new String[100];
boolean datiturno1 = false;
boolean datiturno2 = false;
boolean datiturno3 = false;
for (int i = 0; i < storicoMacchina.size(); i++) {
Storico st = storicoMacchina.get(i);
System.out.println(st.getData() + " - " + st.getProduzione1() + " - " + st.getProduzione2() + " - " + st.getProduzione3());
turno1.add(new BarEntry(i, st.getProduzione1()));
turno2.add(new BarEntry(i, st.getProduzione2()));
turno3.add(new BarEntry(i, st.getProduzione3()));
if (st.getProduzione1() != 0) {
datiturno1 = true;
}
if (st.getProduzione2() != 0) {
datiturno2 = true;
}
if (st.getProduzione3() != 0) {
datiturno3 = true;
}
Calendar c = Calendar.getInstance();
c.setTime(st.getData());
String dataMese = c.get(Calendar.DAY_OF_MONTH) + "/" + (c.get(Calendar.MONTH) + 1);
xLabels.add(dataMese);
}
ValueFormatter formatter = new ValueFormatter() {
#Override
public String getAxisLabel(float value, AxisBase axis) {
return xLabels.get((int) value);
}
};
BarDataSet set1 = null;
BarDataSet set2 = null;
BarDataSet set3 = null;
set1 = new BarDataSet(turno1, "Turno 1");
set2 = new BarDataSet(turno2, "Turno 2");
set3 = new BarDataSet(turno3, "Turno 3");
System.out.println(datiturno1 + "," + datiturno2 + "," + datiturno3);
float groupSpace = 0.04f;
float barSpace = 0.02f;
float barWidth = 0.3f;
// set1.setColors(new int[] { R.color.red, R.color.red1, R.color.red2, R.color.red3 },MainActivity.this);
set1.setColor(getResources().getColor(R.color.turno1));
set2.setColor(getResources().getColor(R.color.turno2));
set3.setColor(getResources().getColor(R.color.turno3));
BarData barData;
if (datiturno3 == false) {
barData = new BarData(set1, set2);
groupSpace = 0.06f;
barSpace = 0.02f;
barWidth = 0.45f;
} else {
barData = new BarData(set1, set2, set3);
}
barData.setBarWidth(barWidth);
bc.setData(barData);
Description desc = new Description();
desc.setText("Produzione ultima settimana");
bc.setDescription(desc);
bc.groupBars(0, groupSpace, barSpace);
XAxis xAxis = bc.getXAxis();
xAxis.setCenterAxisLabels(true);
xAxis.setPosition(XAxis.XAxisPosition.BOTH_SIDED);
xAxis.setAxisMinimum(0f);
xAxis.setGranularity(1);
xAxis.setAxisMaximum(storicoMacchina.size());
// xAxis.setValueFormatter(formatter);
bc.invalidate();
}
without this line code is working fine except for the labels in xAxis that i'm trying to set with this line.
Anyone can help me to find what i'm doing wrong?
Thank you for your help
your text
I'have found workaround to solve my problem changing the code above with this
If anyone can explain me the reason value index differs from my xlabel, dataset size will be appreciated.
Thanks again
public String getAxisLabel(float value, AxisBase axis) {
String label = "";
if ((value >= 0) && (value <= xLabels.size() -1)) {
label = xLabels.get((int) value);
}
return label;
}

SQL injection error in Dynamic SQL with prepared statement

I my application we are collection some user inputs from UI and based on those values we are generating dynamic SQLs with different 'Where' conditions to query data.
It is found that that piece of code has some SQL injection flaw.
public void filter(String strSerialNumberLogic, String strSerialNumber1,
String strSerialNumber2, String strCreationDateLogic,
long lngCreationDate1, long lngCreationDate2,
String strTypeNumbers, String strTitles, long lngLoc)
throws SQLException, ClassNotFoundException {
StringBuffer strWhere = new StringBuffer();
List paramList = new ArrayList();
String arrTypeNumbers[];
String arrTitles[];
int i;
boolean bolHit;
if (!strTypeNumbers.equals("") || !strTitles.equals("")) {
arrTypeNumbers = strTypeNumbers.split(",");
arrTitles = strTitles.split(",");
bolHit = false;
strWhere.append("(");
for (i = 0; i < arrTypeNumbers.length; i++) {
if (arrTypeNumbers[i].length() > 0) {
if (bolHit) {
strWhere.append(" OR ");
} else {
bolHit = true;
}
strWhere.append(" REPORT_NUMBER = ?");
paramList.add(arrTypeNumbers[i]);
}
}
for (i = 0; i < arrTitles.length; i++) {
if (arrTitles[i].length() > 0) {
if (bolHit) {
strWhere.append(" OR ");
} else {
bolHit = true;
}
strWhere.append(" REPORT_NAME = ?");
paramList.add(arrTitles[i]);
}
}
strWhere.append(") ");
}
if (!strSerialNumber1.equals("")) {
if (!strWhere.equals("")) {
strWhere.append(" AND ");
}
strWhere.append(" REPORT_FILE_NO " + strSerialNumberLogic + " ? ");
paramList.add(strSerialNumber1);
if (strSerialNumberLogic.equals("between")) {
strWhere.append(" AND ? ");
paramList.add(strSerialNumber2);
}
}
if (lngCreationDate1 != 0) {
if (!strWhere.equals("")) {
strWhere.append(" AND ");
}
strWhere.append(" REPORT_CREATION_DATE " + strCreationDateLogic + " ? ");
paramList.add(Long.toString(lngCreationDate1));
if (strCreationDateLogic.equals("between")) {
strWhere.append(" AND ? ");
paramList.add(Long.toString(lngCreationDate2));
}
}
if (lngLoc != 0) {
if (!strWhere.equals("")) {
strWhere.append(" AND ");
}
strWhere.append(" REPORT_FILE_LOCATION = ? ");
paramList.add(Long.toString(lngLoc));
}
String finalQuery = "";
if (!strWhere.equals("")) {
finalQuery = "WHERE " + strWhere.toString();
}
String strSQL = "SELECT * " + "FROM D990800 "
+ "LEFT JOIN D990400 ON REPORT_SYSTEM_ID ||" + " REPORT_NO = REPORT_NUMBER " + finalQuery
+ "ORDER BY REPORT_FILE_NO ASC";
System.out.println("strSQL:" + strSQL );
System.out.println("paramList:" + paramList );
Connection conn = ConnectionFactory.instance().getConnection();
PreparedStatement preparedStatement = null;
preparedStatement = conn.prepareStatement(strSQL);
for (int index = 0; index < paramList.size(); index++) {
String param = (String) paramList.get(index);
if (isParsableInt(param)) {
preparedStatement.setInt(index+1, Integer.parseInt(param));
} else {
preparedStatement.setString(index+1, param);
}
}
ResultSet rsReports = preparedStatement.executeQuery();
buildCollection(rsReports);
rsReports.close();
preparedStatement.close();
conn.close();
}
How did you come to the conclusion that you have SQL injection in this code? That would help clearing that up.
Anyway, looking at your code it seems that both strSerialNumberLogic and strCreationDateLogic are variables that comes from an external source, and are concatinated in a way that allows SQL to be injected. If this external source is the user, SQL injection can be executed. If not, than this is probably a false positive. I would improve the code anyway by chaning the logic variables turning them into Enums.

How to get list of email address based on a specified group (CN) from memberOf Attribute in Active Directory in java

I had written a program to fetch all attributes from active directory based on username. now i want to get list of email address based on the group name CN= App_abc_Admin inside memerOf attribute.
Main .java
public void ldapQueryService()throws Exception{
try {
System.out.println("Querying Active Directory Using Java");
System.out.println("------------------------------------");
String domain = "abc.com";
String url = "ldap.abc.com:389";
String username = "username";
String password = "password";
String choice = "samaccountname";
String searchTerm = "xyz";
//Creating instance of ActiveDirectory
ActiveDirectory activeDirectory = new ActiveDirectory(username, password, domain, url);
//Searching
NamingEnumeration<SearchResult> result = activeDirectory.searchUser(searchTerm, choice, null);
while (result.hasMore()) {
SearchResult rs = (SearchResult) result.next();
Attributes attrs = rs.getAttributes();
String temp = attrs.get("samaccountname").toString();
System.out.println("Username : " + temp.substring(temp.indexOf(":") + 1));
String memberOf = attrs.get("memberOf").toString();
String stringToSearch = "CN=App_abc_Admin";
boolean test = memberOf.toLowerCase().contains(stringToSearch.toLowerCase());
if(test){
String mail = attrs.get("mail").toString();
System.out.println("Email ID : " + mail.substring(mail.indexOf(":") + 1));
}
}
activeDirectory.closeLdapConnection();
}catch(Exception e){
}
}
ActiveDirectory.java
public class ActiveDirectory {
//required private variables
private Properties properties;
private DirContext dirContext;
private SearchControls searchCtls;
private String[] returnAttributes = { "*"};
private String domainBase;
private String baseFilter = "(&((&(objectCategory=Person)(objectClass=User)))";
public ActiveDirectory(String username, String password, String domainController,String url) {
properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
properties.put(Context.PROVIDER_URL, "LDAP://" + url);
properties.put(Context.SECURITY_PRINCIPAL, username + "#" + domainController);
properties.put(Context.SECURITY_CREDENTIALS, password);
//initializing active directory LDAP connection
try {
dirContext = new InitialDirContext(properties);
} catch (NamingException e) {
//LOG.severe(e.getMessage());
//e.printStackTrace();
}
//default domain base for search
domainBase = getDomainBase(domainController);
//initializing search controls
searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchCtls.setReturningAttributes(returnAttributes);
}
public NamingEnumeration<SearchResult> searchUser(String searchValue, String searchBy, String searchBase) throws NamingException {
String filter = getFilter(searchValue, searchBy);
String base = (null == searchBase) ? domainBase : getDomainBase(searchBase);
return this.dirContext.search(base, filter, this.searchCtls);
}
public void closeLdapConnection(){
try {
if(dirContext != null)
dirContext.close();
}
catch (NamingException e) {
//e.printStackTrace();
}
}
private String getFilter(String searchValue, String searchBy) {
String filter = this.baseFilter;
if(searchBy.equals("email")) {
filter += "(mail=" + searchValue + "))";
} else if(searchBy.equals("username")) {
filter += "(samaccountname=" + searchValue + "))";
}else if(searchBy.equals("title")) {
filter += "(title=" + searchValue + "))";
}else if(searchBy.equals("department")) {
filter += "(department=" + searchValue + "))";
}else if(searchBy.equals("givenname")) {
filter += "(givenname=" + searchValue + "))";
}
else if(searchBy.equals("samaccountname")) {
filter += "(samaccountname=" + searchValue + "))";
}
return filter;
}
private static String getDomainBase(String base) {
char[] namePair = base.toUpperCase().toCharArray();
String dn = "DC=";
for (int i = 0; i < namePair.length; i++) {
if (namePair[i] == '.') {
dn += ",DC=" + namePair[++i];
} else {
dn += namePair[i];
}
}
return dn;
}
}
In the above example i'm passing the search by and search term. But how to get list of users based on the CN in the memberOf attribute?
I tried to update the filter as below but no output
private String baseFilter = "(&(objectClass=Person)(memberOf=cn=App_abc_Admin,ou=Application Groups,dc=abc,dc=com))";
updated the filter as below.It works now
private String baseFilter = "(&((&(objectCategory=Person)(objectClass=User)(mail=*abc.com)(memberOf=CN=App_abc_Admin,OU=Application Groups,OU=Security Groups,OU=Users_OU,DC=abc,DC=com))))";

How to insert current date and time when user insert data in database

I am trying to insert data into database. i am basically trying to get current date , I am also hiding that particular field("Update Date) because I do want the user to see. Now all I am wanting is whenever i insert some data to database created date should automatically inserted.
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(StoreImageCreateVM StoreImageVM)
{
if (ModelState.IsValid)
{
try
{
StoreImageLogic.Insert(StoreImageVM);
}
catch (Exception e)
{
TempData["Failure"] = "Creation Failed. Image too large.";
return View(StoreImageVM);
}
TempData["Success"] = "Creation Successful";
return RedirectToAction("Index", new { id = StoreImageVM.StoreID });
}
return View(StoreImageVM);
}
savechangesmethod
public bool Insert(StoreImageCreateVM imageVM)
{
StoreImage image = new StoreImage();
image.StoreID = imageVM.StoreID;
image.ImageDescription = imageVM.Description;
image.UploadDate = imageVM.uploadDate;
//Upload the file
string path = AppDomain.CurrentDomain.BaseDirectory + #"Content\Uploads";
string filename = imageVM.File.FileName;
string fullPath = Path.Combine(path, filename);
imageVM.File.SaveAs(fullPath);
//Set imageURL
string serverFilePath = #"\Content\Uploads\";
image.FullFilePath = serverFilePath + filename;
image.Active = true;
return base.Insert(image).StoreImageID != 0;
}
}
i just add to change the savechangesmethod by using the DateTime.Now method. see below.
public bool Insert(StoreImageCreateVM imageVM)
{
StoreImage image = new StoreImage();
image.StoreID = imageVM.StoreID;
image.ImageDescription = imageVM.Description;
image.UploadDate = DateTime.Now;
//Upload the file
string path = AppDomain.CurrentDomain.BaseDirectory + #"Content\Uploads";
string filename = imageVM.File.FileName;
string fullPath = Path.Combine(path, filename);
imageVM.File.SaveAs(fullPath);
//Set imageURL
string serverFilePath = #"\Content\Uploads\";
image.FullFilePath = serverFilePath + filename;
image.Active = true;
return base.Insert(image).StoreImageID != 0;
}
}
}

Rewriting search button from web forms application to mvc4

I have a web forms application with a service reference
and I need to rewrite only the front-end of it in mvc4
I'm having trouble with search button (still new to programming)
this is the code of it in web forms
private void btnSearch_Click(object sender, EventArgs e)
{
ClearViewers();
btnSearch.Enabled = false;
btnSyncronise.Enabled = false;
PersonalInformation localInfo = null;
PersonInfo[] registryInfo = null;
needsUpdate = false;
Cursor = Cursors.WaitCursor;
try
{
if ((String.IsNullOrEmpty(txtPersonalNumber.Text)) || (txtPersonalNumber.Text.Length != 11) || (Regex.Match(txtPersonalNumber.Text, "^\\d{11}$").Success == false))
{
MessageBox.Show(#"blabla" + Environment.NewLine + #"blablabla" + Environment.NewLine + #"blabla", #"blabla", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
using (PersonalInfoServiceClient proxy = new PersonalInfoServiceClient())
{
try
{
localInfo = proxy.GetLocalInfoForPerson(txtPersonalNumber.Text.Trim());
if (localInfo != null)
{
ssStatusLocal.ForeColor = Color.Green;
ssStatusLocal.Text = #"found personal ID";
lblFirstName.Text = localInfo.FirstName;
lblLastName.Text = localInfo.LastName;
lblMiddleName.Text = localInfo.MiddleName;
lblBirthDate.Text = String.Format("{0:MM/dd/yyyy}", localInfo.BirthDate);
if (localInfo.PersonStatus == PersonStatus.Active)
lblStatus.Text = #"active";
else if (localInfo.PersonStatus == PersonStatus.Rejected)
lblStatus.Text = #"passive";
else if (localInfo.PersonStatus == PersonStatus.Dead)
lblStatus.Text = #"dead";
else
lblStatus.Text = #"unknown";
lblSex.Text = (Convert.ToInt32(localInfo.Sex) == 1) ? #"male" : #"female";
lblAddress.Text = localInfo.Address;
lbBirthPlace.Text = localInfo.BirthPlace;
lbCitizenShip.Text = (string.IsNullOrEmpty(localInfo.CitizenShip) && string.IsNullOrEmpty(localInfo.CitizenShipCode)) ? localInfo.CitizenShip : localInfo.CitizenShip + " / " + localInfo.CitizenShipCode;
lbDoubleCitizenShip.Text = (string.IsNullOrEmpty(localInfo.DoubleCitizenShip) && string.IsNullOrEmpty(localInfo.DoubleCitizenShipCode)) ? localInfo.DoubleCitizenShip : localInfo.DoubleCitizenShip + " / " + localInfo.DoubleCitizenShipCode;
lblRegion.Text = localInfo.RegionName;
if (localInfo.Photo != null)
{
MemoryStream MS = new MemoryStream(localInfo.Photo);
pictureBox2.Image = Image.FromStream(MS);
}
documentInformationBindingSource1.DataSource = localInfo.Documents;
}
else
{
ssStatusLocal.ForeColor = Color.Red;
ssStatusLocal.Text = #"personal ID not found";
}
}
catch
{
ssStatusLocal.ForeColor = Color.Red;
ssStatusLocal.Text = #"error";
throw;
}
try
{
registryInfo = proxy.GetRegistryInfoForPerson(txtPersonalNumber.Text.Trim());
if (registryInfo != null && registryInfo.Length > 0)
{
ssStatusCivil.ForeColor = Color.Green;
ssStatusCivil.Text = #"found personal ID";
btnSyncronise.Enabled = true;
RegistryPersonInfos list = new RegistryPersonInfos();
foreach (PersonInfo personInfo in registryInfo)
{
RegistryPersonInfo registryPersonInfo = new RegistryPersonInfo()
{
BirthDate = personInfo.BirthDate
,
IsDead = (personInfo.IsPersonDead) ? "yes" : "no"
,
FirstName = personInfo.FirstName
,
LastName = personInfo.LastName
,
MiddleName = personInfo.MiddleName
,
DocumentStatusName = personInfo.DocumentStatusStr
,
DocumentStatus = personInfo.DocumentStatusEnum.ToString()
,
PersonalNumber = personInfo.PrivateNumber
,
DocumentRejectDate = personInfo.RejectedDate
,
DocumentType = (personInfo.IsIdCard) ? (string.IsNullOrEmpty(personInfo.IdCardNumber)) ? "one" : "two" : "three"
,
DocumentSerie = (personInfo.IsIdCard) ? personInfo.IdCardSerial : string.Empty
,
DocumentNumber = (personInfo.IsIdCard) ? (string.IsNullOrEmpty(personInfo.IdCardNumber)) ? string.Empty : personInfo.IdCardNumber : personInfo.PaspNumber
};
list.Add(registryPersonInfo);
}
registryPersonInfoBindingSource.DataSource = list;
}
else
{
ssStatusCivil.ForeColor = Color.Red;
ssStatusCivil.Text = #"Personal ID not found";
}
}
catch
{
ssStatusCivil.ForeColor = Color.Red;
ssStatusCivil.Text = #"error";
throw;
}
}
}
catch (Exception x)
{
lblFirstName.Text = String.Empty;
lblLastName.Text = String.Empty;
lblMiddleName.Text = String.Empty;
lblStatus.Text = String.Empty;
needsUpdate = false;
dgwMain.DataSource = null;
MessageBox.Show(
String.Format(
"error during loading. {0} error: {1} {2} info: {3}",
Environment.NewLine, x.Message, Environment.NewLine,
(x.InnerException == null) ? string.Empty : x.InnerException.Message), #"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
Cursor = Cursors.Default;
btnSearch.Enabled = true;
}
}
how do you write this in controller?
the controller can't find labels, there is no picturebox
I have no idea how to get data via service reference
could you help ?