How to fix '0 level missing for abstractListDefinition 0' error when using Emulator.getNumber() - docx4j

I used docx4j to read the docx file. And I need to read the paragraph number format characters. I use Emulator.getNumber() to process, but I got this error. How should I deal with it?
try {
PPr pPr = ((P) p).getPPr();
if (pPr != null && pPr.getNumPr() != null) {
Emulator.ResultTriple triple = Emulator.getNumber(wordprocessingMLPackage, pPr);
if (triple != null) {
order = triple.getNumString();
}
}
} catch (Exception e) {
// throw error '0 level missing for abstractListDefinition 0'
e.printStackTrace();
}
Any help would be appreciated.Thanks.
docx4j version: 6.1.2

docx4j's html output uses it like so:
// Numbering
String numberText=null;
String numId=null;
String levelId=null;
if (pPrDirect.getNumPr()!=null) {
numId = pPrDirect.getNumPr().getNumId()==null ? null : pPrDirect.getNumPr().getNumId().getVal().toString();
levelId = pPrDirect.getNumPr().getIlvl()==null ? null : pPrDirect.getNumPr().getIlvl().getVal().toString();
}
ResultTriple triple = org.docx4j.model.listnumbering.Emulator.getNumber(
conversionContext.getWmlPackage(), pStyleVal, numId, levelId);
if (triple==null) {
getLog().debug("computed number ResultTriple was null");
} else {
if (triple.getBullet() != null) {
//numberText = (triple.getBullet() + " ");
numberText = "\u2022 ";
} else if (triple.getNumString() == null) {
getLog().error("computed NumString was null!");
numberText = ("?");
} else {
numberText = (triple.getNumString() + " ");
}
}
if (numberText!=null) {
currentParent.appendChild(document.createTextNode(
numberText + " "));
}
XSL-FO output:
if (pPrDirect!=null && pPrDirect.getNumPr()!=null) {
triple = org.docx4j.model.listnumbering.Emulator.getNumber(
conversionContext.getWmlPackage(), pStyleVal,
pPrDirect.getNumPr().getNumId().getVal().toString(),
pPrDirect.getNumPr().getIlvl().getVal().toString() );
} else {
// Get the effective values; since we already know this,
// save the effort of doing this again in Emulator
Ilvl ilvl = pPr.getNumPr().getIlvl();
String ilvlString = ilvl == null ? "0" : ilvl.getVal().toString();
triple = null;
if (pPr.getNumPr().getNumId()!=null) {
triple = org.docx4j.model.listnumbering.Emulator.getNumber(
conversionContext.getWmlPackage(), pStyleVal,
pPr.getNumPr().getNumId().getVal().toString(),
ilvlString );
}
}

Related

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

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 ....

getExternalStoragePublicDirectory is deprecated and getExternalFilesDir is not working

i'm trying to take a photo and upload it. weird thing is, it's working on my android 9 device, but not working on the android 11 device... input field remains as "no file chosen" even after taking the photo.
here are the codes related to photo upload system
private String mCM;
private ValueCallback<Uri[]> mUMA;
private final static int FCR=1;
ActivityResultLauncher<Intent> startActivityIntent = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
Uri[] results = null;
if (result.getResultCode() == Activity.RESULT_OK) {
if(null == mUMA){
return;
}
if(result.getData() == null || result.getData().getData() == null){
if(mCM != null){
results = new Uri[]{Uri.parse(mCM)};
}
}else{
String dataString = result.getData().getDataString();
if(dataString != null){
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mUMA.onReceiveValue(results);
mUMA = null;
});
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, perms, FCR);
} else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, FCR);
} else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, FCR);
}
if (mUMA != null) {
mUMA.onReceiveValue(null);
}
mUMA = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (MainActivity.this.getPackageManager().resolveActivity(takePictureIntent, 0) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
} catch (IOException ex) {
Log.e("TAG", "ioexception log", ex);
}
if (photoFile != null) {
mCM = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityIntent.launch(chooserIntent);
return true;
}
private File createImageFile() throws IOException{
String imageFileName = java.util.UUID.randomUUID().toString();
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
// File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
return File.createTempFile(imageFileName,".jpg",storageDir);
}
this is the last deprecation warning i have left in my app. it's working fine on all 3 of my test devices(android 7-9-11) with "getExternalStoragePublicDirectory"
I tried again with "getExternalFilesDir" and checked "Internal shared storage\Android\data-myapp-\files\Pictures"
there are files but 0bytes...
i can hardcode like this and it works on all 3 devices without any deprecation warnings...
File storageDir = new File("/storage/emulated/0/Pictures/");
but its probably even worse than using deprecated api?

Null pointer exception on Processing (ldrValues)

My code involves both Processing and Arduino. 5 different photocells are triggering 5 different sounds. My sound files play only when the ldrvalue is above the threshold.
The Null Pointer Exception is highlighted on this line
for (int i = 0; i < ldrValues.length; i++) {
I am not sure which part of my code should be changed so that I can run it.
import processing.serial.*;
import processing.sound.*;
SoundFile[] soundFiles = new SoundFile[5];
Serial myPort; // Create object from Serial class
int[] ldrValues;
int[] thresholds = {440, 490, 330, 260, 450};
int i = 0;
boolean[] states = {false, false, false, false, false};
void setup() {
size(200, 200);
println((Object[])Serial.list());
String portName = Serial.list()[3];
myPort = new Serial(this, portName, 9600);
soundFiles[0] = new SoundFile(this, "1.mp3");
soundFiles[1] = new SoundFile(this, "2.mp3");
soundFiles[2] = new SoundFile(this, "3.mp3");
soundFiles[3] = new SoundFile(this, "4.mp3");
soundFiles[4] = new SoundFile(this, "5.mp3");
}
void draw()
{
background(255);
//serial loop
while (myPort.available() > 0) {
String myString = myPort.readStringUntil(10);
if (myString != null) {
//println(myString);
ldrValues = int(split(myString.trim(), ','));
//println(ldrValues);
}
}
for (int i = 0; i < ldrValues.length; i++) {
println(states[i]);
println(ldrValues[i]);
if (ldrValues[i] > thresholds[i] && !states[i]) {
println("sensor " + i + " is activated");
soundFiles[i].play();
states[i] = true;
}
if (ldrValues[i] < thresholds[i]) {
println("sensor " + i + " is NOT activated");
soundFiles[i].stop();
states[i] = false;
}
}
}
You're approach is shall we say optimistic ? :)
It's always assuming there was a message from Serial, always formatted the right way so it could be parsed and there were absolutely 0 issues buffering data (incomplete strings, etc.))
The simplest thing you could do is check if the parsing was successful, otherwise the ldrValues array would still be null:
void draw()
{
background(255);
//serial loop
while (myPort.available() > 0) {
String myString = myPort.readStringUntil(10);
if (myString != null) {
//println(myString);
ldrValues = int(split(myString.trim(), ','));
//println(ldrValues);
}
}
// double check parsing int values from the string was successfully as well, not just buffering the string
if(ldrValues != null){
for (int i = 0; i < ldrValues.length; i++) {
println(states[i]);
println(ldrValues[i]);
if (ldrValues[i] > thresholds[i] && !states[i]) {
println("sensor " + i + " is activated");
soundFiles[i].play();
states[i] = true;
}
if (ldrValues[i] < thresholds[i]) {
println("sensor " + i + " is NOT activated");
soundFiles[i].stop();
states[i] = false;
}
}
}else{
// print a helpful debugging message otherwise
println("error parsing ldrValues from string: " + myString);
}
}
(Didn't know you could parse a int[] with int(): nice!)

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.

IPathVariableManager.validateValue(URI) returns null

in the Eclipse plugin I'm working on I have a piece of code which basically looks like this:
public static void checkProblemV1() {
try {
String path = "C:\\temp";
org.eclipse.core.runtime.IPath value =
new org.eclipse.core.runtime.Path(path);
IPathVariableManager pathManager =
ResourcesPlugin.getWorkspace().getPathVariableManager();
String name = "somename";
IStatus statusName = pathManager.validateName(name);
IStatus statusValue = pathManager.validateValue(value);
if (statusName == null || statusValue == null) {
System.err.println("checkProblemV1(): statusName is " +
(statusName == null ? "null" : ("not null: '" + statusName + "'.")));
System.err.println("checkProblemV1(): statusValue is " +
(statusValue == null ? "null" : ("not null: '" + statusValue + "'.")));
}
else if (statusName.isOK() && statusValue.isOK()) {
pathManager.setValue(name, value); // setValue is deprecated
System.out.println("checkProblemV1(): Everything fine");
}
else {
if (!statusName.isOK()) {
System.err.println("checkProblemV1(): statusName is not OK.");
}
if (!statusValue.isOK()) {
System.err.println("checkProblemV1(): statusValue is not OK.");
}
}
}
catch (CoreException e) {
System.err.println("checkProblemV1(): CoreException: " + e.getMessage());
}
}
When the above method is executed, there are no problems, but I get a deprecation warning for setValue() when compiling. It's when I wanted to fix that deprecation warning by replacing the call to setValue() with a call to setURIValue() that I got into trouble. First I had to tweak how that Windows-style path was written to avoid an URISyntaxException but after doing that, setURIValue() returns null and after having a look in the documentation I can't see that it should do that? I guess the URI is invalid after all but don't know how to fix it. Below is a test method in the same style as the one above demonstrating the problem.
public static void checkProblemV2() {
try {
String path = "C:\\temp";
// Have to replace \ with /, or we get URISyntaxExeption:
// checkProblemV2(): URISyntaxException: Illegal character in opaque part at index 2: C:\temp
path = path.replace('\\', '/');
java.net.URI value = new java.net.URI(path);
IPathVariableManager pathManager =
ResourcesPlugin.getWorkspace().getPathVariableManager();
String name = "somename";
IStatus statusName = pathManager.validateName(name);
IStatus statusValue = pathManager.validateValue(value);
if (statusName == null || statusValue == null) {
System.err.println("checkProblemV2(): statusName is " +
(statusName == null ? "null" : ("not null: '" + statusName + "'.")));
System.err.println("checkProblemV2(): statusValue is " +
(statusValue == null ? "null" : ("not null: '" + statusValue + "'.")));
}
else if (statusName.isOK() && statusValue.isOK()) {
pathManager.setURIValue(name, value);
System.out.println("checkProblemV2(): Everything fine");
}
else {
if (!statusName.isOK()) {
System.err.println("checkProblemV2(): statusName is not OK.");
}
if (!statusValue.isOK()) {
System.err.println("checkProblemV2(): statusValue is not OK.");
}
}
}
catch (URISyntaxException e) {
System.err.println("checkProblemV2(): URISyntaxException: " + e.getMessage());
}
catch (CoreException e) {
System.err.println("checkProblemV2(): CoreException: " + e.getMessage());
}
}
When I run the above two methods, I get the following output.
checkProblemV1(): Everything fine
checkProblemV2(): statusName is not null: 'Status OK: unknown code=0 OK null'.
checkProblemV2(): statusValue is null
Thanks for reading and for any help, it's seriously appreciated!
There's a bug in org.eclipse.core.internal.resources.PathVariableManager.validateValue(URI) where it is using other internal methods but returning null no matter what else is going on. Please open a bug with Eclipse Platform/Resources.
And I agree with your comment, you should use:
URI uri = new File("C:\\temp").toURI();
pathManager.setURIValue(theName, uri);