How do I get the RFT version number? - java

How can a Rational Functional Tester script figure out under which version of RFT it executes/was built with?
I digged through the documentation, and the closest I found was
com.rational.test.ft.script.ScriptUtilities.getOperatingSystemVersion()
which returns OS version info, which might be close, but still not what Daddy is looking for ;O

I didn't find anything in the APIs or in the Windows registry.
The only way I can think of is to create a custom method and include it in you helper class.
You can find the versione in the file C:\IBM\SDP\FunctionalTester\properties\version\IBM_Rational_Functional_Tester.*.*.swtag, change the path to match your installation.
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
private final static String RFTVersionFolder = "C:\\IBM\\SDP\\FunctionalTester\\properties\\version";
public static String getRFTVersionWithXML() {
File versionFolder = new File(RFTVersionFolder);
File[] versionFile = versionFolder.listFiles( new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.endsWith(".swtag"));
} } );
Document versionDocument = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
versionDocument = builder.parse(new FileInputStream(versionFile[0]));
} catch (SAXParseException spe) {
spe.printStackTrace();
} catch (SAXException sxe) {
sxe.printStackTrace();
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
Node versionNode = versionDocument.getElementsByTagName("ProductVersion").item(0);
return versionNode.getTextContent();
}
This is a quite expensive method, because it istantiates a DocumentBuilder for XML parsing.
As an alternative, load the file content as a String and parse it with a RegExp,
use this matching pattern: [0-9]\.[0-9]\.[0-9]
public static String getRFTVersionWithRegexp() {
File versionFolder = new File(RFTVersionFolder);
File[] versionFile = versionFolder.listFiles( new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.endsWith(".swtag"));
} } );
byte[] buffer = null;
FileInputStream fin;
try {
fin = new FileInputStream(versionFile[0]);
buffer = new byte[(int) versionFile[0].length()];
new DataInputStream(fin).readFully(buffer);
fin.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
String versionFileContent = new String(buffer);
String version = null;
Regex r = new Regex("[0-9]\\.[0-9]\\.[0-9]", Regex.MATCH_NORMAL);
if (r.matches(versionFileContent))
version = r.getMatch();
return version;
}

1) Go to Help> About RFT, it shows the version.

Related

org.xml.sax.SAXParseException error while integrating XML for generating PDF

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

How can I efficiently write the (700,000 lines) content from a For-loop into a file efficiently from Java?

I wrote following code to fetch the results in form of XML responses and write some of its content to the a file from Java. This is done by receiving an XML-response for about 700,000 queries to a public database.
However, before the code can write to the file, it is either stopped by some random exception (from the server) at a random position in code. I tried writing to the file from the For-loop itself, but was not able to. So I tried to store the chunks from received responses into Java HashMap and write the HashMap to the file in a single call. But before the code receives all the responses in the for-loop and stores them into a HashMap, it stops with some exception (maybe at the 15000th iteration!!). Is there any other efficient way to write to the file in Java when one requires such iterations to fetch the data?
The local file that I use for this code is here.
My code is,
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class random {
static FileWriter fileWriter;
static PrintWriter writer;
public static void main(String[] args) {
// Hashmap to store the MeSH values for each PMID
Map<String, String> universalMeSHMap = new HashMap<String, String>();
try {
// FileWriter for MeSH terms
fileWriter = new FileWriter("/home/user/eclipse-workspace/pmidtomeshConverter/src/main/resources/outputFiles/pmidMESH.txt", true);
writer = new PrintWriter(fileWriter);
// Read the PMIDS from this file
String filePath = "file_attached_to_Post.txt";
String line = null;
BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
String[] pmidsAll = null;
int x = 0;
try {
//print first 2 lines or all if file has less than 2 lines
while(((line = bufferedReader.readLine()) != null) && x < 1) {
pmidsAll = line.split(",");
x++;
}
}
finally {
bufferedReader.close();
}
// List of strings containing the PMIDs
List<String> pmidList = Arrays.asList(pmidsAll);
// Iterate through the list of PMIDs to fetch the XML files from PubMed using eUtilities API service from PubMed
for (int i = 0; i < pmidList.size(); i++) {
String baseURL = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&retmode=xml&rettype=abstract&id=";
// Process to get the PMIDs
String indPMID_p0 = pmidList.get(i).toString().replace("[", "");
String indPMID_p1 = indPMID_p0.replace("]", "");
String indPMID_p2 = indPMID_p1.replace("\\", "");
String indPMID_p3 = indPMID_p2.replace("\"", "");
// Fetch XML response from the eUtilities into a document object
Document doc = parseXML(new URL(baseURL + indPMID_p3));
// Convert the retrieved XMl into a Java String
String xmlString = xml2String(doc); // Converts xml from doc into a string
// Convert the Java String into a JSON Object
JSONObject jsonWithMeSH = XML.toJSONObject(xmlString); // Converts the xml-string into JSON
// -------------------------------------------------------------------
// Getting the MeSH terms from a JSON Object
// -------------------------------------------------------------------
JSONObject ind_MeSH = jsonWithMeSH.getJSONObject("PubmedArticleSet").getJSONObject("PubmedArticle").getJSONObject("MedlineCitation");
// List to store multiple MeSH types
List<String> list_MeSH = new ArrayList<String>();
if (ind_MeSH.has("MeshHeadingList")) {
for (int j = 0; j < ind_MeSH.getJSONObject("MeshHeadingList").getJSONArray("MeshHeading").length(); j++) {
list_MeSH.add(ind_MeSH.getJSONObject("MeshHeadingList").getJSONArray("MeshHeading").getJSONObject(j).getJSONObject("DescriptorName").get("content").toString());
}
} else {
list_MeSH.add("null");
}
universalMeSHMap.put(indPMID_p3, String.join("\t", list_MeSH));
writer.write(indPMID_p3 + ":" + String.join("\t", list_MeSH) + "\n");
System.out.println("Completed iteration for " + i + " PMID");
}
// Write to the file here
for (Map.Entry<String,String> entry : universalMeSHMap.entrySet()) {
writer.append(entry.getKey() + ":" + entry.getValue() + "\n");
}
System.out.print("Completed writing the file");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
writer.flush();
writer_pubtype.flush();
writer.close();
writer_pubtype.close();
}
}
private static String xml2String(Document doc) throws TransformerException {
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.METHOD, "xml");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(2));
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc.getDocumentElement());
trans.transform(source, result);
String xmlString = sw.toString();
return xmlString;
}
private static Document parseXML(URL url) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse((url).openStream());
doc.getDocumentElement().normalize();
return doc;
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
}
This is what it prints on the Console before the exception.
Completed iteration for 0 PMID
Completed iteration for 1 PMID
Completed iteration for 2 PMID
Completed iteration for 3 PMID
Completed iteration for 4 PMID
Completed iteration for 5 PMID
And it writes until the below given exception appears...
So at any random point in the loop, I get the exception below.
java.io.FileNotFoundException: https://dtd.nlm.nih.gov/ncbi/pubmed/out/pubmed_190101.dtd
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1890)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:647)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startEntity(XMLEntityManager.java:1304)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startDTDEntity(XMLEntityManager.java:1270)
at com.sun.org.apache.xerces.internal.impl.XMLDTDScannerImpl.setInputSource(XMLDTDScannerImpl.java:264)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.dispatch(XMLDocumentScannerImpl.java:1161)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.next(XMLDocumentScannerImpl.java:1045)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:959)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:602)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:505)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:842)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:771)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:243)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:339)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:121)
at pmidtomeshConverter.Convert2MeSH.parseXML(Convert2MeSH.java:240)
at pmidtomeshConverter.Convert2MeSH.main(Convert2MeSH.java:121)
You want your parser to ignore DTD when parsing them.
Use this feature :
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
See Xerces documentation for other features.
There is no need to use a Map; just write directly to the file. For better performance use a BufferedWriter.
I would also check that there is no rate limit or anything of that nature on the server side (you can guess that from the error you're getting). Save the response in a separate file when parsing or downloading fails, that way you will be able to diagnose the issue better.
I would also invest some time into implementing a restart mechanism, such that you can restart the process from the last failed location instead of starting from the beginning every time. It can be as simple as providing a skip counter as input to skip the first N requests.
You should re-use the DocumentBuilderFactory so that it doesn't load the same DTD every time. Additionally you may want to disable DTD validation altogether (unless you want only valid documents, in which case it's good to catch that exception and dump the bad XML to a separate file for review).
private static DocumentBuilderFactory dbf;
public static void main(String[] args) {
dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
dbf.setFeature("http://xml.org/sax/features/validation", false);
...
}
private static Document parseXML(URL url) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse((url).openStream());
doc.getDocumentElement().normalize();
return doc;
}

(Location of error unknown)com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: Invalid byte 2 of 3-byte UTF-8 sequence

I know the question is asked several times before, but none of the selutions seems to work for me.
I'm trying to create a newsfeed from rss and write it to a pdf.
The pdf is created, but empty and I get a
(Location of error unknown)com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: Invalid byte 2 of 3-byte UTF-8 sequence.
error.
These are my classes:
Get feed:
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
public class GetFeed {
private String adress;
private URL url;
public GetFeed(String adress) {
super();
this.adress = adress;
try {
setUrl();
} catch (MalformedURLException e) {
System.out.println("This isn't a correct url");
e.printStackTrace();
}
}
public void setUrl() throws MalformedURLException {
url = new URL(adress);
}
public SyndFeed getFeed() throws IOException, IllegalArgumentException,
FeedException {
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build(new XmlReader(httpcon));
return feed;
}
Example of feedcreation:
public void homeland() {
GetFeed homeland = new GetFeed("http://www.standaard.be/rss/section/1f2838d4-99ea-49f0-9102-138784c7ea7c");
try {
feed = homeland.getFeed();
WriteToXml xml = new WriteToXml(feed);
} catch (IllegalArgumentException | IOException |FeedException e) {
e.printStackTrace();
}
}
Write the xmlfile:
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedOutput;
public class WriteToXml {
public WriteToXml(SyndFeed feed) throws IOException, FeedException {
Writer writer = new FileWriter("newsfeed.xml", true);
SyndFeedOutput output = new SyndFeedOutput();
output.output(feed, writer);
writer.close();
}
}
Create pdf
public class CreatePdf {
public void convertToPDF() throws IOException, FOPException, TransformerException {
File xsltFile = new File("template.xsl");
StreamSource xmlSource = new StreamSource(new File("newsfeed.xml"));
FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());
FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
OutputStream out;
out = new java.io.FileOutputStream("newsfeed.pdf");
try {
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(new StreamSource(xsltFile));
Result res = new SAXResult(fop.getDefaultHandler());
transformer.transform(xmlSource, res);
} finally {
out.close();
}
}
}
The mainapp:
import java.io.IOException;
import javax.xml.transform.TransformerException;
import org.apache.fop.apps.FOPException;
public class NewsfeedApp {
public static void main(String[] args) {
CreateFeeds feeds = new CreateFeeds();
CreatePdf pdf = new CreatePdf();
try {
pdf.convertToPDF();
} catch (FOPException | IOException | TransformerException e) {
e.printStackTrace();
}
}
}
Anny help would be greatly appreciated
Sorry for crappy eEnglish, I'm not native.

Couldn't append the text onto a Google Drive File

I am trying to append text to a text file on the Google Drive. But when I write, it whole file is overwritten. Why can't I just add the text in the end of the file?
DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, id);
file.open(mGoogleApiClient, DriveFile.MODE_WRITE_ONLY, null).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult driveContentsResult) {
msg.Log("ContentsOpenedCallBack");
if (!driveContentsResult.getStatus().isSuccess()) {
Log.i("Tag", "On Connected Error");
return;
}
final DriveContents driveContents = driveContentsResult.getDriveContents();
try {
msg.Log("onWrite");
OutputStream outputStream = driveContents.getOutputStream();
Writer writer = new OutputStreamWriter(outputStream);
writer.append(et.getText().toString());
writer.close();
driveContents.commit(mGoogleApiClient, null);
} catch (IOException e) {
e.printStackTrace();
}
}
});
Finally I've found the answer to append the text on the drive document.
DriveContents contents = driveContentsResult.getDriveContents();
try {
String input = et.getText().toString();
ParcelFileDescriptor parcelFileDescriptor = contents.getParcelFileDescriptor();
FileInputStream fileInputStream = new FileInputStream(parcelFileDescriptor
.getFileDescriptor());
// Read to the end of the file.
fileInputStream.read(new byte[fileInputStream.available()]);
// Append to the file.
FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor
.getFileDescriptor());
Writer writer = new OutputStreamWriter(fileOutputStream);
writer.write("\n"+input);
writer.close();
driveContentsResult.getDriveContents().commit(mGoogleApiClient, null);
} catch (IOException e) {
e.printStackTrace();
}
SO
The reason is that commit's default resolution strategy is to overwrite existing files. Check the API docs and see if there is a way to append changes.
For anyone facing this problem in 2017 :
Google has some methods to append data Here's a link!
Though copying the method from google didn't worked entirely for me , so here is the class which would append data : ( Please note this is a modified version of this code link )
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.preference.PreferenceManager;
import android.util.Log;
import com.google.android.gms.common.api.Result;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi.DriveContentsResult;
import com.google.android.gms.drive.DriveApi.DriveIdResult;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveId;
/**
* An activity to illustrate how to edit contents of a Drive file.
*/
public class EditContentsActivity extends BaseDemoActivity {
private static final String TAG = "EditContentsActivity";
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
final ResultCallback<DriveIdResult> idCallback = new ResultCallback<DriveIdResult>() {
#Override
public void onResult(DriveIdResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Cannot find DriveId. Are you authorized to view this file?");
return;
}
DriveId driveId = result.getDriveId();
DriveFile file = driveId.asDriveFile();
new EditContentsAsyncTask(EditContentsActivity.this).execute(file);
}
};
SharedPreferences sp= PreferenceManager.getDefaultSharedPreferences(EditContentsActivity.this);
Drive.DriveApi.fetchDriveId(getGoogleApiClient(), EXISTING_FILE_ID)
.setResultCallback(idCallback);
}
public class EditContentsAsyncTask extends ApiClientAsyncTask<DriveFile, Void, Boolean> {
public EditContentsAsyncTask(Context context) {
super(context);
}
#Override
protected Boolean doInBackgroundConnected(DriveFile... args) {
DriveFile file = args[0];
SharedPreferences sp=PreferenceManager.getDefaultSharedPreferences(EditContentsActivity.this);
System.out.println("0"+sp.getString("drive_id","1"));
DriveContentsResult driveContentsResult=file.open(getGoogleApiClient(), DriveFile.MODE_READ_WRITE, null).await();
System.out.println("1");
if (!driveContentsResult.getStatus().isSuccess()) {
return false;
}
DriveContents driveContents = driveContentsResult.getDriveContents();
try {
System.out.println("2");
ParcelFileDescriptor parcelFileDescriptor = driveContents.getParcelFileDescriptor();
FileInputStream fileInputStream = new FileInputStream(parcelFileDescriptor
.getFileDescriptor());
// Read to the end of the file.
fileInputStream.read(new byte[fileInputStream.available()]);
System.out.println("3");
// Append to the file.
FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor
.getFileDescriptor());
Writer writer = new OutputStreamWriter(fileOutputStream);
writer.write("hello world");
writer.close();
System.out.println("4");
driveContents.commit(getGoogleApiClient(), null).await();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
};
#Override
protected void onPostExecute(Boolean result) {
if (!result) {
showMessage("Error while editing contents");
return;
}
showMessage("Successfully edited contents");
}
}
}
Existing_File_id is the resource id. Here is one link if you need resource id a link

file upload in FileNet?

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;

Categories

Resources