XFA form loses interactivity when filling XML data with IText - itext

I have an Adobe LiveCycle form which is dynamically composed. We need to load XML data into this form. I tried that with IText and it worked. But after filling the form it has lost its interactivity. How do I fill the form so that it still generates the fields when opened and executes the JavaScript behind it?
For the filling I used the following code snippet (template Itext):
public class FillXFA
{
public static readonly String DEST = "dest/path";
public static readonly String SRC = "src/path";
public static readonly String XML = "xml/path";
public static void Main(String[] args)
{
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new FillXFA().ManipulatePdf(DEST);
}
protected void ManipulatePdf(string dest)
{
PdfDocument pdfdoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfdoc, true);
XfaForm xfa = form.GetXfaForm();
// Method fills this object with XFA data under datasets/data.
xfa.FillXfaForm(new FileStream(XML, FileMode.Open, FileAccess.Read));
xfa.Write(pdfdoc);
pdfdoc.Close();
}
}

Related

Access to stepExecution inside FlatFileFooterCallback

I am creating a fixed length file I have to attached the number of files that are read in to the footer. I need to access the the stepExecution to get the write count, I followed this FlatFileFooterCallback - how to get access to StepExecution For Count. StepExecution is null??
FlatFileFooterCallback
public class LexisNexisRequestFileFooter implements FlatFileFooterCallback {
#Value("#{StepExecution}")
private StepExecution stepExecution;
int totalItemsWritten = 0;
#Override
public void writeFooter(Writer writer) throws IOException {
System.out.println(stepExecution.getWriteCount());
String julianDate = createJulianDate();
String SAT = "##!!SAT#"+julianDate+totalItemsWritten+" \r\n";
String SIT = "##!!SIT#"+julianDate+totalItemsWritten+" \r\n";
String footer = SAT+SIT;
writer.write(footer);
}
}
Configuration file
#Bean
#StepScope
public FlatFileFooterCallback customFooterCallback() {
return new LexisNexisRequestFileFooter();
}
Writer file
// Create writer instance
FlatFileItemWriter<LexisNexisRequestRecord> writer = new FlatFileItemWriter<>();
LexisNexisRequestFileFooter lexisNexisRequestFileFooter = new LexisNexisRequestFileFooter();
writer.setFooterCallback(lexisNexisRequestFileFooter);
// Set output file location
writer.setResource(new FileSystemResource("homeData.txt"));
// All job reptitions should append to same output file
writer.setAppendAllowed(true);
writer.setEncoding("ascii");
In your writer configuration, you are creating the footer callback manually here:
LexisNexisRequestFileFooter lexisNexisRequestFileFooter = new LexisNexisRequestFileFooter();
writer.setFooterCallback(lexisNexisRequestFileFooter);
and not injecting the step scoped bean. Your item writer bean definition method should be something like:
#Bean
public FlatFileItemWriter writer() {
// Create writer instance
FlatFileItemWriter<LexisNexisRequestRecord> writer = new FlatFileItemWriter<>();
writer.setFooterCallback(customFooterCallback());
// Set output file location
writer.setResource(new FileSystemResource("homeData.txt"));
// All job reptitions should append to same output file
writer.setAppendAllowed(true);
writer.setEncoding("ascii");
}

Excel File Upload using GWT

I am not able to upload excel file and parse using GWT 2.7.0. Referred many links Link1 Link2
using above technique and RequestBuilder I couldn't send parsed excel data back to client. Finally implemented GWT RPC technique but having problem load Excel file as GWT cannot implement File.io api on client(Javascript or browser cannot read)
Code:
Client side FileUploading
public class MyFileUpload extends Composite implements Constants{
private ExcelClientServiceImpl excelServiceClient;
private VerticalPanel vPanel;
public MyFileUpload(ExcelClientServiceImpl excelServiceClient){
this.excelServiceClient = excelServiceClient;
this.vPanel = new VerticalPanel();
initWidget(this.vPanel);
}
public void initiateUpload() {
// Create a FormPanel and point it at a service.
final FormPanel form = new FormPanel();
form.setAction("/excelParser");
// Because we're going to add a FileUpload widget, we'll need to set the
// form to use the POST method, and multipart MIME encoding.
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
// Create a panel to hold all of the form widgets.
vPanel = new VerticalPanel();
form.setWidget(vPanel);
// Create a FileUpload widget.
final FileUpload upload = new FileUpload();
//upload.setName("uploadFormElement");
vPanel.add(upload);
System.out.println("File name is : "+upload.getFilename());
// Add a 'submit' button.
vPanel.add(new Button("Submit", new ClickHandler() {
public void onClick(ClickEvent event) {
Window.alert("In Button >>>>>> "+event);
form.submit();
}
}));
// Add an event handler to the form.
form.addSubmitHandler(new FormPanel.SubmitHandler() {
public void onSubmit(SubmitEvent event) {
Window.alert("In Handler >>>>>> "+event);
}
});
form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
public void onSubmitComplete(SubmitCompleteEvent event) {
// When the form submission is successfully completed, this event is
// fired. Assuming the service returned a response of type text/html,
// we can get the result text here (see the FormPanel documentation for
// further explanation).
Window.alert("In complete >>>>>> "+event.getResults());
}
});
RootPanel.get().add(form);
}
}
Client Interface
public interface ExcelClientServiceInt {
void parse(String fileName, String[] lines, StringBuilder integerNumber, StringBuilder floatNumber,
String separator);
void readingExcel();
}
Client Implementation
public class ExcelClientServiceImpl implements ExcelClientServiceInt{
private ExcelServiceIntAsync service;
private MyFileUpload excelUpload;
public ExcelClientServiceImpl(String url){
this.service = GWT.create(ExcelParserService.class);
ServiceDefTarget endpoint = (ServiceDefTarget) this.service;
endpoint.setServiceEntryPoint(url);
this.excelUpload = new MyFileUpload(this);
}
#Override
public void parse(String fileName, String[] lines, StringBuilder integerNumber, StringBuilder floatNumber,
String separator) {
this.service.parse(fileName, lines, integerNumber, floatNumber, separator, new DefaultCallback());
}
#Override
public void readingExcel() {
this.service.readingExcel(null, new DefaultCallback());
}
private class DefaultCallback implements AsyncCallback{
#Override
public void onFailure(Throwable caught) {
System.out.println("Output failed");
}
#Override
public void onSuccess(Object result) {
System.out.println("Output reieved successfully "+result);
}
}
}
Service Interface
#RemoteServiceRelativePath("excelParser")
public interface ExcelServiceInt extends RemoteService{
void parse(String fileName, String[] lines, StringBuilder integerNumber, StringBuilder floatNumber, String separator);
public List readingExcel(String fileName);
}
Async Call Back
public interface ExcelServiceIntAsync{
void parse(String fileName, String[] lines, StringBuilder integerNumber, StringBuilder floatNumber,
String separator, AsyncCallback<Void> callBack);
void readingExcel(String fileName, AsyncCallback<List<String>> callBack);
}
Server side Service
public class ExcelParserService extends RemoteServiceServlet implements ExcelServiceInt{
public void parse(String fileName, String[] lines, StringBuilder integerNumber, StringBuilder floatNumber,
String separator) {
ExcelParser.parse(fileName, lines, integerNumber, floatNumber, separator);
}
public List<String> readingExcel(String fileName) {
return ExcelParser.readingExcel(fileName);
}
}

How can I read using FlatFileReader but write only to ExecutionContext

I want to read read a text file to build a map and place it into the ExecutionContext for later reference.
I thought to start out using chunk-processng to read the file, the process it, but I don't need the FlatFileItemWriter to write to a file. However, bean initializing requires I set a resource on the writer.
Am I going about this wrong? Is chunk=process the wrong approach. Creating a tasklet my be wiser, but I liked that SpringBatch would read my file for me. With a tasklet, I'd have to write the code to open and process the text file. Right?
Advice on how to proceed would be greatly appreciated.
What I wound up doing (I'm new) was create a Tasklet, and have it also implement the StepExecutionListener interface. Worked like a charm. It's reading a comma-delimited file by lines, plucking out the second column. I created an 'enum' for my ExecutionContext map keys. Basically, this below:
public class ProcessTabcPermitsTasklet implements Tasklet, StepExecutionListener {
private Resource resource;
private int linesToSkip;
private Set<String> permits = new TreeSet<String>();
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
BufferedReader reader = new BufferedReader((new FileReader(resource.getFile())));
String line = null;
int lines = 0;
while ((line = reader.readLine()) != null) {
if (++lines <= linesToSkip)
continue;
String[] s = StringUtils.commaDelimitedListToStringArray(line);
permits.add(s[TABC_COLUMNS.PERMIT.ordinal()]);
}
return RepeatStatus.FINISHED;
}
/**
* #param file
* the file to set
*/
public void setResource(Resource resource) {
this.resource = resource;
}
/**
* #param linesToSkip
* the linesToSkip to set
*/
public void setLinesToSkip(int linesToSkip) {
this.linesToSkip = linesToSkip;
}
public ExitStatus afterStep(StepExecution stepExecution) {
stepExecution.getExecutionContext().put(EXECUTION_CONTEXT.TABC_PERMITS.toString(), permits);
return ExitStatus.COMPLETED;
}
}

Accessing related entity of an entity stored in HttpSession

I have an image upload/store application in which I have a User entity having multiple related images(List<Image> images using OneToMany relationship). I am iterating images of the user in session using struts iterator tag in Home.jsp
<s:iterator value="#session['user'].images" status="itStatus">
<s:property value="imageid"/>
<s:property value="name"/>
<s:url action="GetImageAction" var="imgUrl">
<s:param name="imageId" value="imageid"></s:param>
</s:url>
<li>
<img src="<s:property value="#imgUrl"/>"/>
</li>
</s:iterator>
The upload form is on the same page so when the user logs in, he can see the images he has already uploaded & can also upload new images.
Here is my problem. When a new image is uploaded, the same page refreshes to show his images but the recently uploaded image does not get displayed(appears as broken) but I am able to see all previously uploaded images. This is because the imageId field of Image is having the value 0 in this case instead of the correct id. GetImageAction action sets the inputstream from the image using the param imageId
Here is the Image class:
#Entity(name="Images")
public class Image implements Serializable {
private long imageid;
private String name;
private byte[] image;
private static final long serialVersionUID = 1L;
public Image() {
super();
}
public Image(String name, byte[] image) {
super();
this.name = name;
this.image = image;
}
#Id
#GeneratedValue
#Column(name="Id")
public long getImageid() {
return this.imageid;
}
public void setImageid(long id) {
this.imageid = id;
}
...
}
Now I am guessing this is because the new Image object iterated is having the default long value 0 instead of the generated Id (I am able to access other fields' values like name). Why is this? Since the image is already persisted by the time the result is displayed, shouldn't the Id value be retrieved correctly? What am I doing wrong here?
Please help. I feel I may be missing something simple here but it just wouldn't get solved.
Edit:
UserAddImageAction
public class UserAddImageAction implements SessionAware {
private User user;
private Map session;
private File photo;
private String photoContentType;
private String photoFileName;
public String execute() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("StrTest1");
EntityManager em = emf.createEntityManager();
EntityTransaction etx = em.getTransaction();
try {
BufferedInputStream i = new BufferedInputStream(new FileInputStream(photo));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c;
while((c=i.read()) != -1) {
baos.write(c);
}
user = (User) session.get("user");
user.getImages().add(new Image(photoFileName, baos.toByteArray()));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
etx.begin();
em.merge(user);
etx.commit();
em.close();
emf.close();
session.put("user", user);
return "SUCCESS";
}
...

Trying to create simple GEF

i am trying to create simple automation tool for testing.I have followed a simple tutorials
on net and created a RCP with view on eclipse. now i have tried to include simple GEF
component on the view it throws me error saying " Could not create the view: Plug-in "GEFTutorial" was unable to instantiate class "geftutorial.View"."
here is my source code
particularly when i uncomment creation of
private ScrollingGraphicalViewer viewer = new ScrollingGraphicalViewer();
private RootEditPart rootEditPart = new ScalableFreeformRootEditPart();
private EditPartFactory editPartFactory = new SimpleGEFEditPartFactory();
all the above statements on the view.my view appears back
here is my source code for view.java
package geftutorial;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.gef.*;
import org.eclipse.gef.editparts.ScalableFreeformRootEditPart;
import org.eclipse.gef.ui.parts.ScrollingGraphicalViewer;
public class View extends ViewPart {
public static final String ID = "GEFTutorial.view";
//Use a standard Viewer for the Draw2d canvas
private ScrollingGraphicalViewer viewer = new ScrollingGraphicalViewer();
//Use standard RootEditPart as holder for all other edit parts
private RootEditPart rootEditPart = new ScalableFreeformRootEditPart();
//Custom made EditPartFactory, will automatically be called to create
//edit
// parts for model elements
private EditPartFactory editPartFactory = new SimpleGEFEditPartFactory();
//The model
private SuperWidget model;
//private TableViewer viewer;
/**
* The content provider class is responsible for providing objects to the
* view. It can wrap existing objects in adapters or simply return objects
* as-is. These objects may be sensitive to the current input of the view,
* or ignore it and always show the same content (like Task List, for
* example).
*/
class ViewContentProvider implements IStructuredContentProvider {
public void inputChanged(Viewer v, Object oldInput, Object newInput) {
}
public void dispose() {
}
public Object[] getElements(Object parent) {
if (parent instanceof Object[]) {
return (Object[]) parent;
}
return new Object[0];
}
}
class ViewLabelProvider extends LabelProvider implements
ITableLabelProvider {
public String getColumnText(Object obj, int index) {
return getText(obj);
}
public Image getColumnImage(Object obj, int index) {
return getImage(obj);
}
public Image getImage(Object obj) {
return PlatformUI.getWorkbench().getSharedImages().getImage(
ISharedImages.IMG_OBJ_ELEMENT);
}
}
/**
* This is a callback that will allow us to create the viewer and initialize
* it.
*/
public void createPartControl(Composite parent) {
/*viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL
| SWT.V_SCROLL);
viewer.setContentProvider(new ViewContentProvider());
viewer.setLabelProvider(new ViewLabelProvider());
// Provide the input to the ContentProvider
viewer.setInput(new String[] {"One", "Two", "Three"});
*/
//Create a dummy model
model = new SuperWidget("Model");
model.createDummyModel();
//Initialize the viewer, 'parent' is the
// enclosing RCP windowframe
viewer.createControl(parent);
viewer.setRootEditPart(rootEditPart);
viewer.setEditPartFactory(editPartFactory);
//Inject the model into the viewer, the viewer will
// traverse the model automatically
viewer.setContents(model);
//Set the view's background to white
viewer.getControl().setBackground(new Color(null, 255,255,255));
}
/**
* Passing the focus request to the viewer's control.
*/
public void setFocus() {
viewer.getControl().setFocus();
}
}
Can someone give me a clue about this? i am new to RCP and GEF :(
I'm also just learning GEF, but from what I have seen gef editors are not ViewPart (views) but editors, extending EditPart.
Check my ongoing GEF tutorial here. Hope it helps.
You can also access other GEF tutorial from the eclipse website.