Needs to redirect the error and exceptions which i found in the catch block to .html page
This is my code now i want if anytime any file not found excpetion will come then it should redirect to .html page or borwser
public class XmlToHtml {
public static void main(String[] args) {
if (args.length == 3 && args.length !=0) {
String dataXML = args[0];
String inputXSL = args[1];
String outputHTML = args[2];
XmlToHtml xmltoHtml = new XmlToHtml();
try {
xmltoHtml.transform(dataXML, inputXSL, outputHTML);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
System.out.println("TransformerConfigurationException" + e);
} catch (TransformerException e) {
e.printStackTrace();
System.out.println("TransformerException" + e);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("FileNotFoundException" + e);
}
} else {
System.err.println("Wrong Input");
System.err
.println("Please Enter in the follwing format : Data.xml Input.xsl Output.html");
}
}
public void transform(String dataXML, String inputXSL, String outputHTML)
throws FileNotFoundException, TransformerException,
TransformerConfigurationException {
TransformerFactory tFactory = TransformerFactory.newInstance();
Source xslDoc = new StreamSource(inputXSL);
Source xmlDoc = new StreamSource(dataXML);
OutputStream htmlDoc = new FileOutputStream(outputHTML);
Transformer transformer = tFactory.newTransformer(xslDoc);
transformer.transform(xmlDoc, new StreamResult(htmlDoc));
Desktop dk = Desktop.getDesktop();
try {
dk.open(new File(outputHTML));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Related
doing the merge of 2 or + pdf I lose some information that imposed in the upload phase of the files (ALT tags on the images). This is the method:
public static void mergeFiles(ArrayList<String> filesToBeMerged, String mergedFileLocation) {
String[] filesTBM = filesToBeMerged.toArray(new String[filesToBeMerged.size()]);
PDFMergerUtility ut = new PDFMergerUtility();
try {
for (int i = 0; i < filesTBM.length; i++) {
ut.addSource(filesTBM[i]);
}
ut.setDestinationFileName(mergedFileLocation);
ut.mergeDocuments();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (COSVisitorException e) {
e.printStackTrace();
}
}
If the PDF with the ALT tags were in the list of files to be merged, the result is correct, otherwise not. So far I've tried max with 3 PDFs including 1 with ALT tags.
The questions:
How can I not lose the alt tag after the merge of the files?
Thanks to those who want to help me
Daniele
N.b. I have also tried iText pdf:
public static void mergeFiles(ArrayList<String> filesToBeMerged, String mergedFileLocation) {
String[] filesTBM = filesToBeMerged.toArray(new String[filesToBeMerged.size()]);
Document document = new Document();
PdfCopy copy = null;
try {
copy = new PdfCopy(document, new FileOutputStream(mergedFileLocation));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
document.open();
PdfReader[] reader = new PdfReader[filesTBM.length];
for (int i = 0; i < filesTBM.length; i++) {
try {
reader[i] = new PdfReader(filesTBM[i]);
} catch (IOException e) {
e.printStackTrace();
}
try {
copy.addDocument(reader[i]);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
copy.freeReader(reader[i]);
} catch (IOException e) {
e.printStackTrace();
}
reader[i].close();
}
document.close();
}
I have created a program to convert text to xml by using ReverseXSL API.
This program is to be executed by an application by calling static method (static int transformXSL).
I am able to execute and produce output with running from Eclipse. However, When I ran program (jar) by using application it stuck somewhere and I couldnt find anything.
Then, I debugged by "Debug as...-> Remote Java Application" in Eclipse from Application and found "InvocationTargetException" at ClassLoaders.callStaticFunction.
Below Static method is called by application.
public class MyTest4 {
public MyTest4()
{
}
public static int transformXSL(String defFile, String inputFile, String XSLFile, String OutputFile) {
System.out.println("Dheeraj's method is called");
// start time
FileWriter fw=null;
try {
fw = new FileWriter("D://Countime.txt");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedWriter output=new BufferedWriter(fw);
DateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date dt= new Date();
System.out.println("Date is calculated");
try {
output.write("Start Time:"+sd.format(dt).toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(sd.format(dt));
FileReader myDEFReader=null, myXSLReader=null;
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t=null;
FileInputStream inStream = null;
ByteArrayOutputStream outStream = null;
// Step 1:
//instantiate a transformer with the specified DEF and XSLT
if (new File(defFile).canRead())
{
try {
myDEFReader = new FileReader(defFile);
System.out.println("Definition file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else myDEFReader = null;
if (new File(XSLFile).canRead())
try {
myXSLReader = new FileReader(XSLFile);
System.out.println("XSL file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
else myXSLReader = null;
try {
t = tf.newTransformer(myDEFReader, myXSLReader);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Step 1: DEF AND XSLT Transformation completed");
// Step 2:
// Read Input data
try {
inStream = new FileInputStream(inputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
outStream = new ByteArrayOutputStream();
System.out.println("Step 2: Reading Input file: completed");
// Step 3:
// Transform Input
try {
try (BufferedReader br = new BufferedReader(new FileReader("D://2.txt"))) {
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("Content: "+line);
}
}
System.out.println("File: "+inputFile.toString());
System.out.println("\n content: \n"+ inStream.toString());
System.out.println("Calling Transform Function");
t.transform(inStream, outStream);
System.out.println("Transformation is called");
outStream.close();
try(OutputStream outputStream = new FileOutputStream(OutputFile)) {
outStream.writeTo(outputStream);
System.out.println("Outstream is generated; Output file is creating");
}
System.out.println(outStream.toString());
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserException 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 (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (javax.xml.transform.TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("output file is created");
// End time
Date dt2= new Date();
System.out.println(sd.format(dt2));
System.out.println("End time:"+dt2.toString());
try {
output.append("End Time:"+sd.format(dt2).toString());
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
}
I am reading in an XML file, and trying to return the values in another class using Java. In the XML Reader I read in the values from the XML file. I'm not quite sure how to do this. Any help would be appreciated.
public class XMLReader {
public static List<String> load()
{
try{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("C:/adapters.xml"));
doc.normalize();
NodeList rootNodes = doc.getElementsByTagName("adapters");
Node rootNode = rootNodes.item(0);
Element rootElement = (Element) rootNode;
NodeList adaptersList = rootElement.getElementsByTagName("class");
for(int i=0; i<adaptersList.getLength(); i++){
Node theAdapter = adaptersList.item(i);
Element adpElement = (Element) theAdapter;
System.out.println("This is: " + adpElement.getTextContent());
}
}catch(ParserConfigurationException e){
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
public class AdapterLoader {
public static List<AbstractAdapter> loadAllAdapters()
{
List<AbstractAdapter> allAdapters = new ArrayList<AbstractAdapter>();
List<String> adapterClasses = XMLReader.load();
for (String className : adapterClasses)
{
try {
Class adapters = Class.forName(className);
AbstractAdapter adp = (AbstractAdapter) adapters.newInstance();
allAdapters.add(adp);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return allAdapters;
}
}
Instead of printing it to console
System.out.println("This is: " + adpElement.getTextContent());
add this to a List and return that instead of
return null;
I am trying to develop a plugin, which from a java file generate test and tables classes... when I select a Java source, I will be able to have an option "generate class test", the problem that I am recupering the Java file as ICompliationUnit, then I have a method that xtract methods of an object, that's why; I want to parse the IComplilationUnit to an instance of the class which represents, I tried to use Class.forName but it doesn't work , that's the code:
private void write(String dir, ICompilationUnit cu) throws JavaModelException
{
try
{
cu.getCorrespondingResource().getName();
System.out.println("0000000000000" + cu.getJavaProject().getProject().toString());
}
catch (JavaModelException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
String test = cu.getCorrespondingResource().getName();
IPackageDeclaration[] test1 = cu.getPackageDeclarations();
// Need
String[] name = test.split("\\.");
String contentFile = dir + "\\" + name[0] + "content.txt";
GenerateFitnessTable inst = new GenerateFitnessTable();
try
{
String pack = test1[0].toString().substring(7, test1[0].toString().indexOf("[") - 1) + "." + name[0];
#SuppressWarnings("rawtypes")
Class classe = Class.forName(cu.getJavaProject().getProject().toString()
.substring(cu.getJavaProject().getProject().toString().indexOf("/"), cu.getJavaProject().getProject().toString().length())
+ pack);
try
{
classe.newInstance();
}
catch (InstantiationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (ClassNotFoundException e1)
{
System.out.print("****************************la classe n'existe pas");
}
try
{
inst.generateContent(cu, contentFile);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this the right way ;)) , i found it :
// nouveau region
region = JavaCore.newRegion();
// ajout de la classe selectionné a cette region
region.add(cu);
if (JavaCore.getGeneratedResources(region, true).length == 0)
{
// bug
}
// recuperer l'url de .class
String url = "file:" + JavaCore.getGeneratedResources(region, true)[0].getLocation().makeAbsolute();
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
InputStream input = connection.getInputStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int data = input.read();
while (data != -1)
{
buffer.write(data);
data = input.read();
}
input.close();
byte[] classData = buffer.toByteArray();
clas = defineClass(pack.substring(1, pack.length()), classData, 0, classData.length);
I want to get data from the clipboard and store it in a .txt file.
How do I create the .txt file? I have read a lot about getting data from a file but not the other way around.
Here is my code:
public void CallClipboard (){
System.out.println("Copying text from system clipboard.");
String grabbed = ReadClipboard();
System.out.println(grabbed);
}
public String ReadClipboard () {
// get the system clipboard
Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
// get the contents on the clipboard in a
// transferable object
Transferable clipboardContents = systemClipboard.getContents(null);
// check if clipboard is empty
if (clipboardContents.equals(null)) {
return ("Clipboard is empty!!!");
}
else
try {
// see if DataFlavor of
// DataFlavor.stringFlavor is supported
if (clipboardContents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
// return text content
String returnText = (String) clipboardContents.getTransferData(DataFlavor.stringFlavor);
return returnText;
}
}
catch (UnsupportedFlavorException ufe) {
ufe.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
}
I have solved it with the current code thanx for the tips
public static void CallClipboard (String file){
System.out.println("Copying text from system clipboard.");
String grabbed = ReadClipboard(file);
System.out.println(grabbed);
}
public static String ReadClipboard (String file) {
File testFile = new File(file);
// get the system clipboard
Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
// get the contents on the clipboard in a
// transferable object
Transferable clipboardContents = systemClipboard.getContents(null);
// check if clipboard is empty
if (clipboardContents.equals(null)) {
return ("Clipboard is empty!!!");
}
else
try {
// see if DataFlavor of
// DataFlavor.stringFlavor is supported
if (clipboardContents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
// return text content
String returnText = (String) clipboardContents.getTransferData(DataFlavor.stringFlavor);
try {
setContents(testFile, returnText);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return returnText;
}
}
catch (UnsupportedFlavorException ufe) {
ufe.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
static public void setContents(File aFile, String aContents) throws FileNotFoundException, IOException {
if (aFile == null) {
throw new IllegalArgumentException("File should not be null.");
}
if (!aFile.exists()) {
throw new FileNotFoundException ("File does not exist: " + aFile);
}
if (!aFile.isFile()) {
throw new IllegalArgumentException("Should not be a directory: " + aFile);
}
if (!aFile.canWrite()) {
throw new IllegalArgumentException("File cannot be written: " + aFile);
}
//use buffering
Writer output = new BufferedWriter(new FileWriter(aFile));
try {
//FileWriter always assumes default encoding is OK!
output.write( aContents );
}
finally {
output.close();
}
}
Take a look at FileWriter and BufferedWriter for writing Strings to files.