I have 5 printers in Windows 8.1 and the PDF file is not in local system its generated in PHP server.
Question. how can i get the PDF file from the server and print to a specific printer?
I am trying with Apache PDFBox 2.0.0
EDIT:
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
public class JPrint {
public static boolean saveFile(URL url, String file) throws IOException {
boolean download_status = false;
System.out.println("[OK] - open");
InputStream in = url.openStream();
FileOutputStream fos = new FileOutputStream(new File(file));
System.out.println("[OK] - reading file...");
int length = -1;
byte[] buffer = new byte[1024];
while ((length = in.read(buffer)) > -1) {
fos.write(buffer, 0, length);
}
fos.close();
in.close();
download_status = true;
System.out.println("[OK] - downloaded");
return download_status;
}
public static void main(String[] args) throws IOException, PrinterException {
String downloaded_filename = "C:/Users/tpt/Downloads/pdf.pdf";
String download_pdf_from = "https://github.com/msysgit/msysgit/releases/download/Git-1.9.2-preview20140411/Git-1.9.2-preview20140411.exe";
String downloaded_filename_open_as_pdf = "C:\\Users\\tpt\\Downloads\\pdf.pdf";
String printerNameDesired = "DYMO LabelWriter 450"; // Brother HL-6180DW series
// Get printers
PrintService[] services = PrinterJob.lookupPrintServices();
DocPrintJob docPrintJob = null;
try{
URL url = new URL(download_pdf_from);
if(saveFile(url, downloaded_filename)) {
try {
PDDocument pdf = PDDocument.load(new File(downloaded_filename_open_as_pdf));
PrinterJob job = PrinterJob.getPrinterJob();
for (int i = 0; i < services.length; i++) {
if (services[i].getName().equalsIgnoreCase(printerNameDesired)) {
docPrintJob = services[i].createPrintJob();
}
}
job.setPrintService(docPrintJob.getPrintService());
job.setPageable(new PDFPageable(pdf));
//docPrintJob = service[i].createPrintJob();
job.print();
} catch (Exception e) {
System.out.println("[FAIL]" + e);
}
} else {
System.out.println("[FAIL] - download fail");
}
} catch (Exception ae) {
System.out.println("[FAIL]" + ae);
}
}
}
This gives you back a list of available printers:
PrintService[] services = PrinterJob.lookupPrintServices();
You can loop through this array and select the printer by name (services[i].getName())
Related
While Running the following code in order to read an XML file and generating a corresponding PDF. I am facing the errors mentioned below the code.
package com.test.pdf;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import com.google.zxing.WriterException;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfDocument;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
import com.itextpdf.xmp.impl.Base64;
//import com.itextpdf.text.pdf.codec.Base64;
import org.apache.log4j.Logger;
public class PDFGenerator {
final static Logger logger = Logger.getLogger(PDFGenerator.class);
private static final String TITLE = "TestReport";
public static final String PDF_EXTENSION = ".pdf";
public static String arg1 = "";
public static String arg2 = "";
public static String arg3 = "";
public static String createPDFBase64(String arg1 , String arg2 , String arg3) throws IOException, URISyntaxException, com.lowagie.text.DocumentException, WriterException {
byte[] encoded = null;
String out= null;
Document document = new Document();
try {
//arg1 = args[0];
//Document is not auto-closable hence need to close it separately
document = new Document(PageSize.LETTER);
System.out.println("Here i amn777");
File temp = File.createTempFile(TITLE ,PDF_EXTENSION);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(
temp)); // new File
HeaderFooter event = new HeaderFooter(arg2);
event.setHeader("Test Report");
writer.setPageEvent(event);
document.open();
PDFCreator pdfCreator = new PDFCreator();
pdfCreator.addMetaData(document, arg1 , arg2 );
pdfCreator.addTitlePage(document, arg2 );
//PDFCreator.addContent(document, dataObjList);
//String base64String = Base64.encodeFromFile("C:\\Users\\2000554\\Downloads\\HTMLToPDF\\TestReport.pdf");
//System.out.println("===============>>>" + base64String);
document.close();
byte[] inFileBytes = Files.readAllBytes(temp.toPath());
//PdfReader pReader = new PdfReader(inFileBytes);
//System.out.println("pReader.getFileLength()===============>>>" + pReader.getFileLength());
//System.out.println("pReader.getFileLength()===============>>>" + PdfTextExtractor.getTextFromPage(pReader, 1));
out = new String(Base64.encode(inFileBytes), "UTF-8");
System.out.println("Clear cache..");
pdfCreator.xmlData.clear();
pdfCreator.dataObjMRCList.clear();
pdfCreator.dataObjNRCList.clear();
pdfCreator.dataObjVASList.clear();
pdfCreator.dataObjDEVList.clear();
pdfCreator.stcPhoneNumDispList.clear();
pdfCreator.stcSvcMap.clear();
pdfCreator.stcSvcBandWthMap.clear();
pdfCreator.invoiceTaxDvcMap.clear();
//byte[] decoded = java.util.Base64.getDecoder().decode(out.getBytes());
/* byte[] decoded = Base64.decode(out.getBytes());
FileOutputStream fos = new FileOutputStream("C:\\Users\\2000554\\Downloads\\HTMLToPDF\\TestBaseReport.pdf");
fos.write(decoded);
fos.flush();
fos.close();*/
}catch ( FileNotFoundException e) {
System.out.println("FileNotFoundException occurs.." + e.getMessage());
e.printStackTrace();
}catch (DocumentException e) {
System.out.println("DocumentException occurs.." + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
System.out.println("Exception occurs.." + e.getMessage());
e.printStackTrace();
return null;
}
finally{
if(null != document){
// document.close();
}
}
return out;
}
public static void main(String args[]) {
try {
if(args != null && args.length>1) {
FileReader fReader = new FileReader(new File("C:\\Users\\2004807\\Downloads\\XML\\Amendment.xml"));
BufferedReader bdr = new BufferedReader(fReader);
String line = null;
String xmlString = "";
while ((line=bdr.readLine())!=null){
xmlString += line;
}
createPDFBase64(xmlString,args[1],args[2]);
}else {
createPDFBase64("","","");
}
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (com.lowagie.text.DocumentException e) {
e.printStackTrace();
} catch (WriterException e) {
e.printStackTrace();
}
}
}
I rechecked the path and the XML format since the error mentioned is due to wrong formatting of XML in some cases. I still am getting the following error.
Here i amn777
1getting resourcesfile:/C:/Users/2004807/Desktop/B2B%20Java/HtmlToPdf/target/classes/new.PNG
Inside getXMLData
XML==>
[Fatal Error] :1:1: Premature end of file.
Error is :org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Premature end of file.
xmlData size is :0
I'm currently using the below method to take screenshots and store them in a folder called 'Screenshots'. But what i want is, to take these screenshots and paste them in a word document according to the test cases to which they belong.
Is it possible? If so could somebody please guide me?
public String FailureScreenshotAndroid(String name) {
try {
Date d = new Date();
String date = d.toString().replace(":", "_").replace(" ", "_");
TakesScreenshot t = (TakesScreenshot)driver;
File f1 = t.getScreenshotAs(OutputType.FILE);//Temporary Location
String permanentLocation =System.getProperty("user.dir")+ "\\Screenshots\\"+name+date+".png";
File f2 = new File(permanentLocation);
FileUtils.copyFile(f1, f2);
return permanentLocation;
}catch (Exception e) {
String msg = e.getMessage();
return msg;
}
}
Try below:
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class TakeScreenshots {
public static void main(String[] args) {
try {
XWPFDocument docx = new XWPFDocument();
XWPFRun run = docx.createParagraph().createRun();
FileOutputStream out = new FileOutputStream("d:/xyz/doc1.docx");
for (int counter = 1; counter <= 5; counter++) {
captureScreenShot(docx, run, out);
TimeUnit.SECONDS.sleep(1);
}
docx.write(out);
out.flush();
out.close();
docx.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void captureScreenShot(XWPFDocument docx, XWPFRun run, FileOutputStream out) throws Exception {
String screenshot_name = System.currentTimeMillis() + ".png";
BufferedImage image = new Robot()
.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
File file = new File("d:/xyz/" + screenshot_name);
ImageIO.write(image, "png", file);
InputStream pic = new FileInputStream("d:/xyz/" + screenshot_name);
run.addBreak();
run.addPicture(pic, XWPFDocument.PICTURE_TYPE_PNG, screenshot_name, Units.toEMU(350), Units.toEMU(350));
pic.close();
file.delete();
}
}
I want to print a PDF file to Zebra printer using a Java application. I have generated a PDF using Jasper reports with 2D bar codes. If I am performing manual print to Zebra printer it's printing that PDF file but once I am trying to print the same pdf file using the Java application, the job is submitting to printer but print is not happening.
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;
public class ZebraPrintUtil {
public static void main(String[] args) throws IOException, InterruptedException {
byte[] content = convertFileToBytes("D://old files/test123.pdf");
print(content, "ZDesigner GX420t");
}
private static byte[] convertFileToBytes(String absoluteFilePath) throws IOException {
File file = new File(absoluteFilePath);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum;
(readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum); // no doubt here is 0
}
} catch (IOException ex) {
} finally {
if (fis != null) {
fis.close();
}
}
byte[] bytes = bos.toByteArray();
return bytes;
}
private static boolean print(byte[] byteArray, String reqPrinterId)
throws IOException, InterruptedException {
boolean isPrintedSuccessfully = false;
DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
PrintService[] services = PrintServiceLookup.lookupPrintServices(
flavor, null);
if (services.length > 0) {
PrintService myService = null;
for (PrintService service: services) {
if (service.getName().contains(reqPrinterId)) {
myService = service;
break;
}
}
DocPrintJob printJob = myService.createPrintJob();
JobCompleteMonitor monitor = new JobCompleteMonitor();
printJob.addPrintJobListener(monitor);
Doc document = new SimpleDoc(byteArray, flavor, null);
try {
printJob.print(document, null);
monitor.waitForJobCompletion();
System.out.println("-------------------- Print Completed " + monitor.completed);
isPrintedSuccessfully = true;
} catch (Exception e) {
e.printStackTrace();
}
}
return isPrintedSuccessfully;
}
private static class JobCompleteMonitor extends PrintJobAdapter {
private boolean completed = false;
#Override
public void printJobCanceled(PrintJobEvent pje) {
signalCompletion();
}
#Override
public void printJobCompleted(PrintJobEvent pje) {
signalCompletion();
}
#Override
public void printJobFailed(PrintJobEvent pje) {
signalCompletion();
}
#Override
public void printJobNoMoreEvents(PrintJobEvent pje) {
signalCompletion();
}
private void signalCompletion() {
synchronized(JobCompleteMonitor.this) {
completed = true;
JobCompleteMonitor.this.notify();
}
}
public synchronized void waitForJobCompletion() {
try {
while (!completed) {
wait();
}
} catch (InterruptedException e) {
}
}
}
}
For Desktop integration:
File file = ...
if (Desktop.isDesktopAvailable()) {
Desktop.getDesktop().print(file);
}
I used Pramod code but before that I have to pass my printer id that is name of printer. I am getting byte array from my db.
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.DocFlavor;
try {
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(new Copies(1));
PrintService pss[] = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.GIF, pras);
if (pss.length == 0)
throw new RuntimeException("No printer services available.");
//You have to check which printer you want to print.
PrintService ps = pss[1];
logger.info("Printing to " + ps);
//Here I am calling Pramod method.
boolean result = PrintPDF.print(byteArray, ps.getName());
logger.info("result " + result);
}
catch (Exception ex){
System.out.println(ex.getMessage());
}
This is not answer, this code will call Pramod method which is precise solution.
Thanks
I am trying to use itext framework to convert a pdf file into a csv for import into excel.
The output is garbled and I pressume I am missing a step in regards to format conversion however I can't seem to find the information in the itext site and am looking for assistance.
Current is as below.
package com.pdf.convert;
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
public class ThirdPDF {
private static String INPUTFILE = "/location/test.pdf";
private static String OUTPUTFILE = "/location/test.csv";
public static void main(String[] args) throws DocumentException,
IOException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(OUTPUTFILE));
document.open();
PdfReader reader = new PdfReader(INPUTFILE);
int n = reader.getNumberOfPages();
PdfImportedPage page;
// Go through all pages
for (int i = 1; i <= n; i++) {
// Only page number 2 will be included
if (i == 2) {
page = writer.getImportedPage(reader, i);
Image instance = Image.getInstance(page);
document.add(instance);
}
}
document.close();
}
}
Converting PDF file to CSV file.
Present Directory and File creation is based on Android Framework.
Change your path and Directory as per your Framework Accordingly.
private void convertPDFToCSV(String pdfFilePath) {
String myfolder = Environment.getExternalStorageDirectory() + "/Mycsv";
if (createFolder(myfolder)) {
try {
Document document = new Document();
document.open();
FileOutputStream fos=new FileOutputStream(myfolder + "/MyCSVFile.csv");
StringBuilder parsedText=new StringBuilder();
PdfReader reader1 = new PdfReader(pdfFilePath);
int n = reader1.getNumberOfPages();
for (int i = 0; i <n ; i++) {
parsedText.append(parsedText+PdfTextExtractor.getTextFromPage(reader1, i+1).trim()+"\n") ;
//Extracting the content fromx the different pages
}
StringReader stReader = new StringReader(parsedText.toString());
int t;
while((t=stReader.read())>0)
fos.write(t);
document.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private boolean createFolder(String myfolder) {
File f = new File(myfolder);
if (!f.exists()) {
if (!f.mkdir()) {
return false;
} else {
return true;
}
}else{
return true;
}
}
I'm writing code to upload a file in FileNet.
A standalone java program to take the some inputs, and upload it in FileNet. I'm new to FileNet. Can you help me out, How to do it?
You can use Document.java provided by IBM for your activities and many other Java classes
package fbis.apitocasemanager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import com.user.DocumentUtil;
public class Addfilescasemanager {
/**
* #param args
*/
public static void addfiles_toicm(String directory, String lFolderPath)
{
try {
DocumentUtil.initialize();
String path = directory;
System.out.println("This is the path:..............................."
+ path);
String file_name;
File folder = new File(directory);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
file_name = listOfFiles[i].getName();
System.out.println(file_name);
String filePaths = directory + file_name;
// File file = new File("C:\\FNB\\att.jpg");
File file = new File(filePaths);
InputStream attStream = null;
attStream = new FileInputStream(file);
DocumentUtil.addDocumentWithStream(lFolderPath, attStream,
"image/jpeg", file_name, "Document");
}
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}//end of method
public static void addfile_toicm(File file_name, String lFolderPath)
{
try {
DocumentUtil.initialize();
InputStream attStream = null;
attStream = new FileInputStream(file_name);
DocumentUtil.addDocumentWithStream(lFolderPath, attStream,
"image/jpeg", file_name.getName(), "Document");
System.out.println("File added successfully");
} catch (Exception e)
{
System.out.println(e.getMessage());
}
}//end of method
public static void main(String nag[])
{
addfiles_toicm("E:\\FSPATH1\\BLR_14122012_001F1A\\","/IBM Case Manager/Solution Deployments/Surakshate Solution for form 2/Case Types/FISB_FactoriesRegistration/Cases/2012/12/06/16/000000100103");
}
}
and my DocumentUtil class is
package com.user;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import javax.security.auth.Subject;
import com.filenet.api.collection.ContentElementList;
import com.filenet.api.constants.AutoClassify;
import com.filenet.api.constants.AutoUniqueName;
import com.filenet.api.constants.CheckinType;
import com.filenet.api.constants.DefineSecurityParentage;
import com.filenet.api.constants.RefreshMode;
import com.filenet.api.core.Connection;
import com.filenet.api.core.ContentTransfer;
import com.filenet.api.core.Document;
import com.filenet.api.core.Domain;
import com.filenet.api.core.Factory;
import com.filenet.api.core.Folder;
import com.filenet.api.core.ObjectStore;
import com.filenet.api.core.ReferentialContainmentRelationship;
import com.filenet.api.util.UserContext;
public class DocumentUtil {
public static ObjectStore objectStore = null;
public static Domain domain = null;
public static Connection connection = null;
public static void main(String[] args)
{
initialize();
/*
addDocumentWithPath("/FNB", "C:\\Users\\Administrator\\Desktop\\Sample.txt.txt",
"text/plain", "NNN", "Document");
*/
File file = new File("E:\\Users\\Administrator\\Desktop\\TT.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
addDocumentWithStream("/FNB", fis, "text/plain", "My New Doc", "Document");
}
public static void initialize()
{
System.setProperty("WASP.LOCATION", "C:\\Progra~1\\IBM\\WebSphere\\AppServer\\profiles\\AppSrv01\\installedApps\\P8Node01Cell\\FileNetEngine.ear \\cews.war\\WEB-INF\\classes\\com\\filenet\\engine\\wsi");
System.setProperty("SECURITY.AUTH.LOGIN.CONFIG",
"C:\\Progra~1\\IBM\\WebSphere\\AppServer\\profiles\\AppSrv01\\installedApps\\P8Node01Cell\\FileNetEngine.ear\\client-download.war\\FileNet\\Download\\dap501.153\\jaas.conf.wsi");
System.setProperty(":SECURITY.AUTH.LOGIN.CONFIG",
"C:\\Progra~1\\IBM\\WebSphere\\AppServer\\profiles\\AppSrv01\\installedApps\\P8Node01Cell\\FileNetEngine.ear\\client-download.war\\FileNet\\Download\\dap501.153\\jaas.conf.wsi");
System.setProperty("java.security.auth.login.config","C:\\Progra~1\\IBM\\WebSphere\\AppServer\\java\\jre");
connection = Factory.Connection.getConnection(CEConnection.uri);
Subject sub = UserContext.createSubject(connection,
com.user.CEConnection.username, CEConnection.password,
CEConnection.stanza);
UserContext.get().pushSubject(sub);
domain = Factory.Domain.getInstance(connection, null);
objectStore = Factory.ObjectStore.fetchInstance(domain, "TARGET", null);
System.out.println("\n\n objectStore--> " + objectStore.get_DisplayName());
}
public static void addDocumentWithPath(String folderPath, String filePath,
String mimeType, String docName, String docClass) {
Folder folder = Factory.Folder.fetchInstance(objectStore,
folderPath, null);
System.out.println("\n\n Folder ID: " + folder.get_Id());
// Document doc = Factory.Document.createInstance(os, classId);
Document doc = CEUtil.createDocWithContent(new File(filePath), mimeType,
objectStore, docName, docClass);
doc.save(RefreshMode.REFRESH);
doc = CEUtil.createDocNoContent(mimeType, objectStore, docName, docClass);
doc.save(RefreshMode.REFRESH);
CEUtil.checkinDoc(doc);
ReferentialContainmentRelationship rcr = CEUtil.fileObject(objectStore, doc, folderPath);
rcr.save(RefreshMode.REFRESH);
}
public static void addDocumentWithStream(String folderPath,
InputStream inputStream, String mimeType,
String docName, String docClass) {
Folder folder = Factory.Folder.fetchInstance(objectStore,
folderPath, null);
System.out.println("\n\n Folder ID: " + folder.get_Id());
// Document doc = Factory.Document.createInstance(os, classId);
Document doc = Factory.Document.createInstance(objectStore, null);
ContentElementList contEleList = Factory.ContentElement.createList();
ContentTransfer ct = Factory.ContentTransfer.createInstance();
ct.setCaptureSource(inputStream);
ct.set_ContentType(mimeType);
ct.set_RetrievalName(docName);
contEleList.add(ct);
doc.set_ContentElements(contEleList);
doc.getProperties().putValue("DocumentTitle", docName);
doc.set_MimeType(mimeType);
doc.checkin(AutoClassify.AUTO_CLASSIFY, CheckinType.MAJOR_VERSION);
doc.save(RefreshMode.REFRESH);
ReferentialContainmentRelationship rcr = folder.file(doc,
AutoUniqueName.AUTO_UNIQUE, docName,
DefineSecurityParentage.DO_NOT_DEFINE_SECURITY_PARENTAGE);
rcr.save(RefreshMode.REFRESH);
/*
doc.save(RefreshMode.REFRESH);
doc = CEUtil.createDocNoContent(mimeType, objectStore, docName, docClass);
CEUtil.checkinDoc(doc);
ReferentialContainmentRelationship rcr = CEUtil.fileObject(objectStore, doc, folderPath);
rcr.save(RefreshMode.REFRESH);
*/
}
public static ObjectStore getObjecctStore()
{
if (objectStore != null) {
return objectStore;
}
// Make connection.
com.filenet.api.core.Connection conn = Factory.Connection
.getConnection(CEConnection.uri);
Subject subject = UserContext.createSubject(conn,
CEConnection.username, CEConnection.password, null);
UserContext.get().pushSubject(subject);
try {
// Get default domain.
Domain domain = Factory.Domain.getInstance(conn, null);
// Get object stores for domain.
objectStore = Factory.ObjectStore.fetchInstance(domain, "TARGET",
null);
System.out.println("\n\n Connection to Content Engine successful !!");
} finally {
UserContext.get().popSubject();
}
return objectStore;
}
}
The above answer is extremely good. Just wanted to save people some time but I don't have the points to comment so am adding this as an answer.
Eclipse wasted a lot of my time getting the above to work because it suggested the wrong classes to import. Here's the list of correct ones:
import com.filenet.api.collection.ContentElementList;
import com.filenet.api.constants.AutoClassify;
import com.filenet.api.constants.AutoUniqueName;
import com.filenet.api.constants.CheckinType;
import com.filenet.api.constants.DefineSecurityParentage;
import com.filenet.api.constants.RefreshMode;
import com.filenet.api.core.Document;
import com.filenet.api.core.ObjectStore;
import com.filenet.api.core.ContentTransfer;
import com.filenet.api.core.Folder;
import com.filenet.api.core.Factory;
import com.filenet.api.core.ReferentialContainmentRelationship;