import template style with listing : getNumberingDefinitionsPart() return null for WordprocessingMLPackage.createPackage() - docx4j

i have some problems importing styles from a docx template.
I want to extract these styles to apply it to my new document.
Most of them have a numbering.
I can extract the style and numbering correctly from template.
I can apply styles but can t apply numbering as my wordMLPackage.getMainDocumentPart().getNumberingDefinitionsPart() return null
If I try to not import NumberingDefinitionPart, all my styles implying listing with number turn to be considered as list without number (and that s not what I want).
I can t find a way to instanciate it and there is not method to set a new one.
Here is my code.
public class ModuleToDocxGenerator {
private WordprocessingMLPackage wordMLPackage = null;
private XHTMLImporter xHTMLImporter = null;
private List<String> listStyle;
private ProjectType project;
private File file;
private Map<String, Object> mapElement = new HashMap<>();
private int taillePolice = 12;
private final String police = "Arial";
private Map<String, String> mapBookmark = new HashMap<>();
private int compteurIDBookMark = 1;
public void docxParser() {
// Récupération des styles du template
WordprocessingMLPackage wordMLPackage2 = null;
try {
wordMLPackage2 = WordprocessingMLPackage.load(new File("template.docx"));
} catch (Docx4JException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
wordMLPackage = WordprocessingMLPackage.createPackage();
} catch (InvalidFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
MainDocumentPart tempDocPart = wordMLPackage2.getMainDocumentPart();
//add Style part
StyleDefinitionsPart sdp = tempDocPart.getStyleDefinitionsPart();
Styles tempStyle = null;
// Add numbering part
NumberingDefinitionsPart ndp = tempDocPart.getNumberingDefinitionsPart();
Numbering numbStyle = null;
try {
tempStyle = sdp.getContents();
numbStyle=ndp.getContents();
} catch (Docx4JException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
wordMLPackage.getMainDocumentPart().getNumberingDefinitionsPart().setJaxbElement(numbStyle);
wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().setJaxbElement(tempStyle);
Could someone help me please?

Have a look at https://github.com/plutext/docx4j/blob/master/src/samples/docx4j/org/docx4j/samples/NumberingRestart.java#L54
You need something like:
// Add numbering part
NumberingDefinitionsPart ndp = new NumberingDefinitionsPart();
wordMLPackage.getMainDocumentPart().addTargetPart(ndp);
ndp.setJaxbElement( (Numbering) XmlUtils.unmarshalString(initialNumbering) );

Related

Trouble in testing with invalid field

public with sharing class SobjectByParams {
public SObject createSObject(String sObjectName, Map<String, String> fields) {
String invalidSObjectError = System.Label.invalid_Sobject_Name;
String invalidFieldError = System.Label.Invalid_Sobject_Field;
SObject newObject;
try {
newObject = (SObject) Type.forName(sObjectName).newInstance();
} catch (NullPointerException ex) {
throw new InvalidTypeNameException(invalidSObjectError);
}
for (String field : fields.keySet()) {
try {
newObject.put(field, fields.get(field));
} catch (SObjectException ex) {
throw new InvalidTypeNameException(invalidFieldError);
}
}
insert newObject;
return newObject;
}
public class InvalidTypeNameException extends Exception {
}
}
#IsTest
public with sharing class SobjectByParamsTest {
SobjectByParams sobjectByParams;
private static final String TestName = 'TestName';
private static final String BCity = 'Lviv';
private static final String LastName = 'Kapo';
private static final String Email = 'email';
#IsTest
static void createSObject() {
SobjectByParams sobjectByParams = new SobjectByParams();
Map<String, String> fields = new Map<String, String>();
fields.put('BillingCity', BCity);
Test.startTest();
SObject result = sobjectByParams.createSObject(TestName, fields);
Test.stopTest();
System.assertEquals(BCity, result.get(BCity));
}
}
SobjectByParams.InvalidTypeNameException: invalidSobjectNameError - PROBLEM
TEST WORKING on 53.33% but I need min 80%
I don`t know how to fix my problem.
Shouldn't TestName be a sObject name like Contact? Does this code work when you run it normally, does it insert anything or throw? Check/fix that and then you probably need a negative test too.
Make second test method
#isTest
static void testPassingBadData() {
SobjectByParams sobjectByParams = new SobjectByParams();
Map<String, String> fields = new Map<String, String>();
fields.put('BillingCity', BCity);
try{
sobjectByParams.createSObject('NoSuchObjectInTheSystem', fields);
System.assert(false, 'This should have failed and thrown exception');
} catch(Exception e){
System.assert(e.getMessage().contains(Label.Invalid_Sobject_Field));
}
}

Write Status of test case with Hash Map and Selenium

I am using Hash Map to read the get excel data and use them in methods to perform If...else validations.
I am using class file for initializing the Hash Map for reading the data. it goes as shown below
public class SampleDataset {
public static HashMap<String, ArrayList<String>> main() throws IOException {
final String DatasetSheet = "src/test/resources/SampleDataSet.xlsx";
final String DatasetTab = "TestCase";
Object[][] ab = DataLoader.ReadMyExcelData(DatasetSheet, DatasetTab);
int rowcount = DataLoader.myrowCount(DatasetSheet, DatasetTab);
int colcount = DataLoader.mycolCount(DatasetSheet, DatasetTab);
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
// i = 2 to avoid column names
for (int i = 2; i < rowcount;) {
ArrayList<String> mycolvalueslist = new ArrayList<String>();
for (int j = 0; j < colcount;) {
mycolvalueslist.add(ab[i][j].toString());
j++;
}
map.put(ab[i][0].toString(), mycolvalueslist);
i++;
}
return map;
}
I am using this map in my testcase file which is as shown below
#Test //Testcase
public void testThis() throws Exception {
try {
launchMainApplication();
TestMain MainPage = new TestMain(tool, test, user, application);
HashMap<String, ArrayList<String>> win = SampleDataset.main();
SortedSet<String> keys = new TreeSet<>(win.keySet());
for (String i : keys) {
System.out.println("########### Test = " + win.get(i).get(0) + " ###########");
MainPage.step01(win.get(i).get(1));
MainPage.step02(win.get(i).get(2));
}
test.setResult("pass");
} catch (AlreadyRunException e) {
} catch (Exception e) {
verificationErrors.append(e.getMessage());
throw e;
}
}
#Override
#After
public void tearDown() throws Exception {
super.tearDown();
}
I want to write the status as PASS or FAIL for all the testcase initiated through above FOR-LOOP on to same excel by creating new column as Status for each row of test case
my excel sheet is as shown below
Cereate global List. After every test case add status result in the list.
After all test cases are finished, iterate trough te list and updete your excell file. In this way.
public static void main(String[] args) throws EncryptedDocumentException, IOException {
// Step 1: load your excel file as a Workbook
String excelFilePath = "D:\\Desktop\\testExcel.xlsx";
Workbook workbook = WorkbookFactory.create(new FileInputStream(excelFilePath));
// Step 2: modify your Workbook as you prefer
Iterator<Sheet> sheetIterator = workbook.sheetIterator(); // Getting an iterator for all the sheets
while (sheetIterator.hasNext()) {
Iterator<Row> rowIterator = sheetIterator.next().rowIterator(); // Getting an iterator for all the rows (of current sheet)
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// Put here your internal logic to understand if the row needs some changes!
int cellsn = row.getLastCellNum();
row.getCell(cellsn).setCellValue("String that you gat from List = list.get(rownumber)")
}
}
You may need Apache POI.
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.00</version>
</dependency>

API request catches exception NULL response

I am using NYT's developers movie reviews API, and i am at the beginning where i just want to see a response. It appears that i get a NULL response which catches the exception that i will pinpoint on the code. " CharSequence text = "There was an error. Please try again";" to help you find it. Could someone please tell me what causes this problem.
NYT Documentation Link http://developer.nytimes.com/movie_reviews_v2.json#/Documentation/GET/critics/%7Bresource-type%7D.json
public class MainActivity extends AppCompatActivity {
private final String site = "https://api.nytimes.com/svc/movies/v2/reviews/search.json?query=";
public int count;
public int i;
public int j;
public int k;
public int n;
public int comas;
public int ingadded;
public String web2 = "";
public String istos;
public ArrayList<String> mylist = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button next = (Button) findViewById(R.id.button);
final EditText edit_text = (EditText) findViewById(R.id.ing);
final TextView show_ing = (TextView) findViewById(R.id.show_ing);
final Button done = (Button) findViewById(R.id.button3);
final Button refresh = (Button) findViewById(R.id.refresh);
final Button delete = (Button) findViewById(R.id.delete);
final ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
//done move to next activity
done.setOnClickListener(new View.OnClickListener() {
#Override
//CHECK IF TEXT BOX IS EMPTY
public void onClick(View view) {
web2 = edit_text.getText().toString();
//check if there are ingredients added
if (web2 == "") {
Context context = getApplicationContext();
CharSequence text = "Search Bar is Empty!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Dialog.dismiss();
}
else {
//IF NOT CREATE THE LINK AND SEND IT TO LongOperation
web2 = edit_text.getText().toString();
//create link - MAYBE THE WAY API KEY MUST BE CALLED?
istos = site + web2 + "?api-key=xxxxxxxxxxxx";
Log.v("Showme=", istos);
web2 = "";
// WebServer Request URL
String serverURL = istos;
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
}
}
});
edit_text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
edit_text.setHint("");
else
edit_text.setHint("Type the title of the movie");
}
});
private class LongOperation extends AsyncTask<String, String, Void> {
// Required initialization
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private Integer count;
private int add = 1;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
String data = "";
TextView jsonParsedname = (TextView) findViewById(R.id.jsonParsedname1);
ArrayList<ArrayList<Integer>> numArray = new ArrayList<ArrayList<Integer>>();
int sizeData = 0;
protected void onPreExecute() {
//Start Progress Dialog (Message)
Dialog.setMessage("Finding Movies..");
Dialog.show();
try {
// Set Request parameter
data = "&" + URLEncoder.encode("data", "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader = null;
// Send data
try {
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "";
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (Exception ex) {
Error = ex.getMessage();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
/*****************************************************/
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
Context context = getApplicationContext();
CharSequence text = "There was an error. Please try again";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Dialog.dismiss();
} else {
JSONObject jsonResponse;
try {
/****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
jsonResponse = new JSONObject(Content);
if (jsonResponse == null) {
jsonParsedname.setText("Wrong Input");
}
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonMainNode = jsonResponse.optJSONArray("results");

saving arraylists to internal storage

I am writing a program which calculates and shows Installed program's data usage.
I want to save My variables and reload them.
I have checked other questions about this but i didn't find my answer.
I have 5 Arraylists in my code to save these items:
"Application Name","Application Icon","Received Data","Sent Data" and "Total Data".
I get these informations and convert Arraylists to String arrays whith "for loop" and show them with my custom Adapter and a listview.
My problem is that my application force stops when i run it on my phone.
I save some variables with SharedPreferences and save Arraylists into internal storage.
I have also tried to save Arraylists with SharedPreferences and i could save them. but when i want to reload and set them to arraylists, i get error.
Here is my "onCreate" method code:
public class MainActivity extends AppCompatActivity {
private static final String MyPREFERENCES="MyPrefs";
private SharedPreferences myPrefs;
int first;
List<String> list=new ArrayList<>();
List<String> s=new ArrayList<>();
List<String> r=new ArrayList<>();
List<String> t=new ArrayList<>();
List<Drawable> ic=new ArrayList<>();
List<Double> StartRx=new ArrayList<>();
List<Double> StartTx=new ArrayList<>();
private long StartTotal;
private long TotalDataUsage;
private long prevData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView1=(ListView)findViewById(R.id.mainListView1);
registerForContextMenu(listView1);
myPrefs=getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
first=myPrefs.getInt("FirstCall",0);
StartTotal=myPrefs.getLong("StartData",0);
TotalDataUsage=myPrefs.getLong("TotalData",0);
prevData=myPrefs.getLong("prevData",0);
try {
list=(ArrayList<String>) InternalStorage.readObject(this,"NamesList");
r=(ArrayList<String>) InternalStorage.readObject(this,"ReceivedData");
s=(ArrayList<String>) InternalStorage.readObject(this,"SentData");
t=(ArrayList<String>) InternalStorage.readObject(this,"TotalData");
ic=(ArrayList<Drawable>) InternalStorage.readObject(this,"IconsList");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();***
}
DataUsage();
int l=list.size();
if (l>0) {
String[] Names = new String[l];
String[] DReceived = new String[l];
String[] DSent = new String[l];
String[] DTotal = new String[l];
Drawable[] icons = new Drawable[l];
for (int i = 0; i < l; i++) {
Names[i] = list.get(i);
DReceived[i] = r.get(i);
DSent[i] = s.get(i);
DTotal[i] = t.get(i);
icons[i] = ic.get(i);
}
assert listView1 != null;
listView1.setAdapter(new CustomAdapter(this, Names, DReceived, DSent, DTotal, icons));
}
}
and "onResume" method code is:
protected void onPause() {
super.onPause();
try {
InternalStorage.writeObject(this,"NamesList",list);
InternalStorage.writeObject(this,"ReceivedData",r);
InternalStorage.writeObject(this,"SentData",s);
InternalStorage.writeObject(this,"TotalData",t);
InternalStorage.writeObject(this,"IconsList",ic);
} catch (IOException e) {
e.printStackTrace();
}
SharedPreferences.Editor edit = myPrefs.edit();
edit.putInt("FirstCall", first);
edit.putLong("TotalData",TotalDataUsage);
edit.putLong("StartData", StartTotal);
edit.putLong("prevData", prevData);
edit.commit();
}
and the "InternalStorage" class is:
public final class InternalStorage {
private InternalStorage() {}
public static void writeObject(Context context,String fileName,Object object) throws IOException {
FileOutputStream fos=context.openFileOutput(fileName,Context.MODE_PRIVATE);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(object);
oos.close();
fos.close();
}
public static Object readObject(Context context,String fileName) throws IOException, ClassNotFoundException {
FileInputStream fis=context.openFileInput(fileName);
ObjectInputStream ois=new ObjectInputStream(fis);
return ois.readObject();
}
}
I didn't get any error from android studio.
I know that the problem is with below codes because when i delete them, it works!
try {
list=(ArrayList<String>) InternalStorage.readObject(this,"NamesList");
r=(ArrayList<String>) InternalStorage.readObject(this,"ReceivedData");
s=(ArrayList<String>) InternalStorage.readObject(this,"SentData");
t=(ArrayList<String>) InternalStorage.readObject(this,"TotalData");
ic=(ArrayList<Drawable>) InternalStorage.readObject(this,"IconsList");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
and this code:
try {
InternalStorage.writeObject(this,"NamesList",list);
InternalStorage.writeObject(this,"ReceivedData",r);
InternalStorage.writeObject(this,"SentData",s);
InternalStorage.writeObject(this,"TotalData",t);
InternalStorage.writeObject(this,"IconsList",ic);
} catch (IOException e) {
e.printStackTrace();
}
CAN ANYONE HELP ME PLEASE?!!

Implementation of simple Java IDE using Runtime Process and JTextArea

I am developing a simple Java IDE like Netbeans/Eclipse. My GUI includes two JTextArea component, one used as a TextEditor where the end user can type in his programs and the other used as an output window.
I am running the users programs by invoking the windows command prompt through Java Runtime and Process classes. I am also catching the IO streams of the process using the methods getInputStream(), getErrorStream(), getOutputStream().
If the program contains only the statements to print something onto the screen, I am able to display the output on the output window(JTextArea). But if it includes statements to read input from the user, then it must be possible for the user to type the expected input value via the output window and it must be sent to the process just as in Netbeans/Eclipse.
I also checked the following link
java: work with stdin/stdout of process in same time
Using this code, I am able to display only the statements waiting for input and not simple output statements. Also, only a single line is displayed on the output window at a time.
It would be great if anybody can help me to resolve this issue.
Thanks
Haleema
I've found the solution with little modification to the earlier post java: work with stdin/stdout of process in same time
class RunFile implements Runnable{
public Thread program = null;
public Process process = null;
private JTextArea console;
private String fn;
public RunFile(JTextArea cons,String filename){
console = cons;
fn=filename;
program = new Thread(this);
program.start();
}
#Override
public void run() {
try {
String commandj[] = new String[4];
commandj[0] = "cmd";
commandj[1]="/C";
commandj[2]="java";
commandj[3] = fn;
String envp[] = new String[1];
envp[0]="path=C:/Program Files (x86)/Java/jdk1.6.0/bin";
File dir = new File("Path to File");
Runtime rt = Runtime.getRuntime();
process = rt.exec(commandj,envp,dir);
ReadStdout read = new ReadStdout(process,console);
WriteStdin write = new WriteStdin(process, console);
int x=process.waitFor();
console.append("\nExit value: " + process.exitValue() + "\n");
}
catch (InterruptedException e) {}
catch (IOException e1) {}
}
}
class WriteStdin implements Runnable{
private Process process = null;
private JTextArea console = null;
public Thread write = null;
private String input = null;
private BufferedWriter writer = null;
public WriteStdin(Process p, JTextArea t){
process = p;
console = t;
writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
write = new Thread(this);
write.start();
console.addKeyListener(new java.awt.event.KeyAdapter() {
#Override
public void keyTyped(java.awt.event.KeyEvent e){
//save the last lines for console to variable input
if(e.getKeyChar() == '\n'){
try {
int line = console.getLineCount() -2;
int start = console.getLineStartOffset(line);
int end = console.getLineEndOffset(line);
input = console.getText(start, end - start);
write.resume();
} catch (BadLocationException e1) {}
}
}
});
console.addCaretListener(new javax.swing.event.CaretListener() {
#Override
public void caretUpdate(CaretEvent e) {
console.setCaretPosition(console.getDocument().getLength());
throw new UnsupportedOperationException("Not supported yet.");
}
});
console.addFocusListener(new java.awt.event.FocusAdapter() {
#Override
public void focusGained(java.awt.event.FocusEvent e)
{
console.setCaretPosition(console.getDocument().getLength());
}
});
}
#Override
public void run(){
write.suspend();
while(true){
try {
//send variable input in stdin of process
writer.write(input);
writer.flush();
} catch (IOException e) {}
write.suspend();
}
}
}
class ReadStdout implements Runnable{
public Thread read = null;
private BufferedReader reader = null;
private Process process = null;
private JTextArea console = null;
public ReadStdout(Process p,JTextArea t){
process = p;
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
console = t;
read = new Thread(this);
read.start();
}
public void run() {
String line;
try {
while((line = reader.readLine())!=null)
console.append(line+"\n");
}catch (IOException e) {}
}
}