Running OpenOffice Macro from Java API - java

I'm trying to write a Java program that will run an OpenOffice Macro. I'm getting this error:
java.lang.RuntimeException:
com.sun.star.script.provider.ScriptFrameworkErrorException: Incorrect
format for Script URI: vnd.sun.star.script:Name of macro
I believe it has something to do with the way that I'm calling the macro (String cmd)
I've searched high and low but can't seem to find any information on this. There are a few posts on the OO forums but none of them seemed to help. Here is some of the code:
public static void main(String[] args) throws BootstrapException {
if(args.length == 0)
{
System.out.println("Must enter a filename");
System.exit(1);
}
try
{
String param = args[0];
//String cmd = "Standard.Conversion.ConvertHTMLToWord?langauge=Basic&location=application";
String cmd = "Name.Of.Macro?langauge=Basic&location=Document";
System.out.println("Running macro on " + param);
Macro macObj = new Macro();
macObj.executeMacro(cmd, new Object[]{param}]);
System.out.println("Completed");
}
catch(Exception e)
{
System.out.println(e.toString());
//e.printStackTrace();
}
Macro Class:
class Macro {
private static final String ooExecPath = "C:/Program Files/OpenOffice.org 3/program";
public Object executeMacro(String strMacroName, Object[] aParams) throws BootstrapException
{
try
{
com.sun.star.uno.XComponentContext xContext;
System.out.println("Connecting to OpenOffice");
xContext = BootstrapSocketConnector.bootstrap(ooExecPath);
System.out.println("Connected to a running instance of OpenOffice");
System.out.println("Trying to execute macro...");
com.sun.star.text.XTextDocument mxDoc = openWriter(xContext);
XScriptProviderSupplier xScriptPS = (XScriptProviderSupplier) UnoRuntime.queryInterface(XScriptProviderSupplier.class, mxDoc);
XScriptProvider xScriptProvider = xScriptPS.getScriptProvider();
XScript xScript = xScriptProvider.getScript("vnd.sun.star.script:"+strMacroName);
short[][] aOutParamIndex = new short[1][1];
Object[][] aOutParam = new Object[1][1];
return xScript.invoke(aParams, aOutParamIndex, aOutParam);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static com.sun.star.text.XTextDocument openWriter(com.sun.star.uno.XComponentContext xContext)
{
com.sun.star.frame.XComponentLoader xCLoader;
com.sun.star.text.XTextDocument xDoc = null;
com.sun.star.lang.XComponent xComp = null;
try {
// get the remote office service manager
com.sun.star.lang.XMultiComponentFactory xMCF =
xContext.getServiceManager();
Object oDesktop = xMCF.createInstanceWithContext(
"com.sun.star.frame.Desktop", xContext);
xCLoader = (com.sun.star.frame.XComponentLoader)
UnoRuntime.queryInterface(com.sun.star.frame.XComponentLoader.class,
oDesktop);
com.sun.star.beans.PropertyValue [] szEmptyArgs =
new com.sun.star.beans.PropertyValue [0];
/*
ArrayList<PropertyValue> props = new ArrayList<PropertyValue>();
PropertyValue p = new PropertyValue();
p.Name = "Hidden";
p.Value = new Boolean(true);
props.add(p);
PropertyValue[] properties = new PropertyValue[props.size()];
props.toArray(properties);
String strDoc = "private:factory/swriter";
xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0, properties);
*/
String strDoc = "private:factory/swriter";
xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0, szEmptyArgs);
xDoc = (com.sun.star.text.XTextDocument)
UnoRuntime.queryInterface(com.sun.star.text.XTextDocument.class,
xComp);
} catch(Exception e){
System.err.println(" Exception " + e);
e.printStackTrace(System.err);
}
return xDoc;
}
}

I suppose your problem is in the "Name.Of.Macro": it must be: Library.Module.NameOfMacro.
"langauge=Basic" of course sets the language name, and "location=application" means the macro library should be searched in the opened document, and not in global OO libraries.
As far as parameters are involved, I use:
XScriptProviderSupplier xScriptPS = (XScriptProviderSupplier) UnoRuntime.queryInterface(XScriptProviderSupplier.class, xComponent);
XScriptProvider xScriptProvider = xScriptPS.getScriptProvider();
XScript xScript = xScriptProvider.getScript("vnd.sun.star.script:"+macroName);
short[][] aOutParamIndex = new short[1][1];
Object[][] aOutParam = new Object[1][1];
Object[] aParams = new String[2];
aParams[0] = myFirstParameterName;
aParams[1] = mySecondParameterName;
#SuppressWarnings("unused")
Object result = xScript.invoke(aParams, aOutParamIndex, aOutParam);
System.out.println("xScript invoke macro " + macroName);
Hope it can be useful, after such long time... :-(

XScriptProviderSupplier xScriptPS = (XScriptProviderSupplier) UnoRuntime.queryInterface(XScriptProviderSupplier.class, xComponent);
What is xComponent in the above code?

Compare: ?langauge=Basic&location=Document"
to: ?language=Basic&location=Document"
wring is: "langauge" :D, swap "au" to "ua". :)

Related

Snmp code gives me this error Caused by: java.lang.NoClassDefFoundError: org/snmp4j/TransportMapping

i have been trying to apply commands of snmp at java on Ubuntu, i find an example code at stackoverflow and code's github link: https://github.com/jineshmathewt/snmpbulkwalk/blob/master/snmpbulkwalk/src/TestSNMP.java
But when i try to execute i m getting an error .
i would like to ask what am i doing wrong ? , to mention i can use get command on terminal and it works .
public class TestSNMP {
private static final String SNMPPORT = "161";
private static final int snmpVersion = SnmpConstants.version2c;
private int snmpTimeout = 500;
private int numRetries = 2;
public void doSNMPBulkWalk(String ipAddr, String commStr, String bulkOID, String operation) throws IOException {
Snmp snmp = new Snmp(new DefaultUdpTransportMapping());
UserTarget targetV3 = null;
CommunityTarget targetV2 = null;
UsmUser user = null;
PDU request = null;
snmp.listen();
Address add = new UdpAddress(ipAddr + "/" + SNMPPORT);
if (snmpVersion == SnmpConstants.version2c || snmpVersion == SnmpConstants.version1) {
targetV2 = new CommunityTarget();
targetV2.setCommunity(new OctetString(commStr));
targetV2.setAddress(add);
targetV2.setTimeout(snmpTimeout);
targetV2.setRetries(numRetries);
targetV2.setVersion(snmpVersion);
targetV2.setMaxSizeRequestPDU(65535);
}
if (snmpVersion == SnmpConstants.version2c) {
request = new PDU();
//request.setMaxRepetitions(100);
//request.setNonRepeaters(0);
}
request.setType(PDU.GETBULK);
OID oID = new OID(bulkOID);
request.add(new VariableBinding(oID));
OID rootOID = request.get(0).getOid();
VariableBinding vb, ar[];
List<TreeEvent> l = null;
TreeUtils treeUtils = new TreeUtils(snmp, new DefaultPDUFactory());
if (snmpVersion == SnmpConstants.version2c) {
targetV2.setCommunity(new OctetString(commStr));
if (operation.equalsIgnoreCase("bulkwalk")) {
OID[] rootOIDs = new OID[1];
rootOIDs[0] = rootOID;
l = treeUtils.walk(targetV2, rootOIDs);
} else {
l = treeUtils.getSubtree(targetV2, rootOID);
}
}
//System.out.println(l);
System.out.println("size="+l.size());
for(TreeEvent t : l){
VariableBinding[] vbs= t.getVariableBindings();
for (int i = 0; (vbs != null) && i < vbs.length; i++) {
vb = vbs[i];
String s = vb.toString();
System.out.println(s);
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Date d1 = new Date();
TestSNMP snmpTest = new TestSNMP();
try {
snmpTest.doSNMPBulkWalk(args[0], args[1], args[2], args[3]);
} catch (IOException e) {
e.printStackTrace();
}
Date d2 = new Date();
System.out.println("Time Elapsed=" + (d2.getTime() - d1.getTime()));
}
}
I think the snmp library jar is not included in the eclipse project. You have to download the snmp library jar from maven repository. Right click on the project and go to Properties -> Java Build Path -> Libraries and add those library jar there using Add External Jars.

How to persist changes with docx4j Java library to word document

I am using the docx4j Java library for the first time and have some difficulties finding a good reference. What i need to start is a simple Java class to enforce the protection on a Word document in read-only mode. I have com that far that i can read the protection mode and set it. But when saving the Word document the changes are not written to the Word document.
public class Doc4JPOC {
public static void main(String[] args) {
String docName = "/Users/petervannes/Desktop/Unprotected document.docx";
// String docName = "/Users/petervannes/Desktop/Protected document.docx" ;
Doc4JPOC d4j = new Doc4JPOC();
d4j.isProtected(docName);
d4j.protect(docName);
d4j.isProtected(docName);
}
private void protect(String filename) {
try {
WordprocessingMLPackage wordMLPackage = Docx4J.load(new java.io.File(filename));
MainDocumentPart mdp = wordMLPackage.getMainDocumentPart();
Relationship rs = mdp.getRelationshipsPart().getRelationshipByType(Namespaces.SETTINGS);
DocumentSettingsPart dsp = (DocumentSettingsPart) mdp.getRelationshipsPart().getPart(rs);
// Update settings.xml
List<Object> nodes = dsp.getJAXBNodesViaXPath("//w:documentProtection", true);
for (Object obj : nodes) {
CTDocProtect cdtP = ((CTDocProtect) obj);
cdtP.setEnforcement(Boolean.TRUE);
cdtP.setEdit(STDocProtect.READ_ONLY);
}
// Write updated settings.xml to document
wordMLPackage.addTargetPart(dsp);
// wordMLPackage.save(new java.io.File(filename));
Docx4J.save(wordMLPackage, new java.io.File(filename), 0);
System.out.println("Protected document " + filename) ;
} catch (Docx4JException ex) {
Logger.getLogger(Doc4JPOC.class.getName()).log(Level.SEVERE, null, ex);
} catch (JAXBException jex) {
Logger.getLogger(Doc4JPOC.class.getName()).log(Level.SEVERE, null, jex);
}
}
private void isProtected(String filename) {
Boolean isProtectionEnforced = false;
STDocProtect editMode = STDocProtect.NONE;
try {
WordprocessingMLPackage wordMLPackage = Docx4J.load(new java.io.File(filename));
MainDocumentPart mdp = wordMLPackage.getMainDocumentPart();
Relationship rs = mdp.getRelationshipsPart().getRelationshipByType(Namespaces.SETTINGS);
DocumentSettingsPart dsp = (DocumentSettingsPart) mdp.getRelationshipsPart().getPart(rs);
System.out.println("Partname : " + dsp.getPartName());
List<Object> nodes = dsp.getJAXBNodesViaXPath("//w:documentProtection", true);
for (Object obj : nodes) {
CTDocProtect cdtP = ((CTDocProtect) obj);
isProtectionEnforced = cdtP.isEnforcement();
editMode = cdtP.getEdit();
System.out.println("Enforced: " + cdtP.isEnforcement());
System.out.println("Edit: " + cdtP.getEdit());
}
if (isProtectionEnforced) {
System.out.println("Protection is enabled , protection mode is " + editMode.toString());
} else {
System.out.println("Protection is disabled");
}
} catch (Docx4JException ex) {
Logger.getLogger(Doc4JPOC.class.getName()).log(Level.SEVERE, null, ex);
} catch (JAXBException jex) {
Logger.getLogger(Doc4JPOC.class.getName()).log(Level.SEVERE, null, jex);
}
}
}
When executing this class i do get the following output;
Partname : /word/settings.xml
Protection is disabled
Protected document /Users/petervannes/Desktop/Unprotected document.docx
Partname : /word/settings.xml
Protection is disabled
So i suspect that i am not updating the WordprocessingMLPackage or DocumentSettingsPart correctly in the protect method, but have currently no clue where it goes wrong.
Resolved it. Instead of adding the DocumentSettingsPart to the loaded WordprocessingMLPackage. The CTDocProtect instance needs to be used to set the document protection on the content.
CTDocProtect cdtP = new CTDocProtect();
cdtP.setEnforcement(Boolean.TRUE);
cdtP.setEdit(STDocProtect.READ_ONLY);
dsp.getContents().setDocumentProtection(cdtP);
Docx4J.save(wordMLPackage, new java.io.File(filename), 0);
For docx4j v3.3.0, please see http://www.docx4java.org/forums/docx-java-f6/password-set-for-documentprotection-not-accepted-in-msword-t2427.html#p8290

JACOB:Presentation.Export : PowerPoint can't save ^0 to ^1

public boolean PptExport2Png(String filePath,String exportPath){
Boolean flag = false;
ActiveXComponent component = new ActiveXComponent("PowerPoint.Application");
try{
Dispatch presentations = component.getProperty("Presentations").toDispatch();
Dispatch presentation = Dispatch.call(presentations, "Open", new Variant(filePath),
new Variant(-1), new Variant(-1), new Variant(0))
.toDispatch();
Dispatch.call(presentation,"Export",new Variant(exportPath),new Variant(720),new Variant(540));
}catch (Exception e){
System.out.println("|||" + e.toString());
}finally {
}
return false;
}
public static void main(String[] strs)throws Exception{
String filePath="D://ppttest.ppt";
String pngPath="D://folder22";
JacobPptUtils jac = new JacobPptUtils(filePath,true);
jac.PptExport2Png(filePath,pngPath);
}
I found that when i was using JACOB to export the ppt ,now,i have no any idea.please,give me some advice to deal it.
Here are the way where i has try:
1. to modify the file path expression
public static void main(String args[]) throws Exception{
source = "D:/test.ppt" ;
dest = "D:/xxx.pdf" ;
File file = new File(source);
if(!file.exists()){
throw new Exception("error");
}
ppt2Pdf(source,dest);
}
}

How to train Name model in OpenNLP?

Iam trying to train the name finder model to detect the Names but it is not giving proper result.
Here is the Code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InputStream is=null;
Resources resources=this.getResources();
assetManager=resources.getAssets();
String trainingDataFile = "en-ner-person.train";
String outputModelFile = "en-ner-person.bin";
String sentence[] = {"Sunil", "61 years old , will join the board as a nonexecutive director Nov. 29" };
train(trainingDataFile, outputModelFile, "person");
try {
predict(sentence, outputModelFile);
}
catch(Exception e)
{
System.out.println("Errror Preditct" + e.getMessage());
}
}
private static void train(String trainingDataFile, String outputModelFile, String tagToFind) {
NameSampleDataStream nss = null;
try {
nss = new NameSampleDataStream(new PlainTextByLineStream(new java.io.FileReader(trainingDataFile)));
} catch (Exception e) {}
TokenNameFinderModel model = null;
try {
model = NameFinderME.train("en", tagToFind, nss, Collections.<String, Object>emptyMap());
} catch(Exception e) {}
try {
File outFile = new File(outputModelFile);
FileOutputStream outFileStream = new FileOutputStream(outFile);
model.serialize(outFileStream);
}
catch (Exception ex) {}
}
private void predict(String sentence[], String modelFile) throws Exception {
InputStream is1 ;
is1 = assetManager.open("en-ner-person.bin",MODE_PRIVATE);
TokenNameFinderModel model1 = new TokenNameFinderModel(is1);
String sd;
NameFinderME nameFinder = new NameFinderME(model1);
Span sp[] = nameFinder.find(sentence);
String a[] = Span.spansToStrings(sp, sentence);
StringBuilder fd = new StringBuilder();
int l = a.length;
for (int j = 0; j < l; j++) {
fd = fd.append(a[j] + "\n");
}
sd = fd.toString();
Log.d("Name Detected:", sd);
}
}
Here is Output iam getting:
D:\Name Detected: [ 07-20 19:35:47.516 8799: 8799 I/Adreno-EGL ]
Content Of en-ner-person.train is:
<START:person> Sunil <END> , 61 years old , will join the board as a nonexecutive director Nov. 29 .
Kindly help.
Try this:
Span[] sp = nameFinder.find(search);
nameFinder.clearAdaptiveData();
for (Span span : sp) {
for (int i=span.getStart(); i<span.getEnd(); i++) {
fd.append(sentence[i] + "\n");
}
}
Also this line seems to be wrong, you don't need to assign the content of append to fd again.
fd = fd.append(a[j] + "\n");
Hope that helps.

BeanSerializer/BeanDeserializer Axis Generated Object

I have a large number of axis generated objects from several WSDLs, I need a generic solution to store the objects in xml format in the database, but also load them back in java when needed.
This is what I've made so far:
private String serializeAxisObject(Object obj) throws Exception {
if (obj == null) {
return null;
}
StringWriter outStr = new StringWriter();
TypeDesc typeDesc = getAxisTypeDesc(obj);
QName qname = typeDesc.getXmlType();
String lname = qname.getLocalPart();
if (lname.startsWith(">") && lname.length() > 1)
lname = lname.substring(1);
qname = new QName(qname.getNamespaceURI(), lname);
AxisServer server = new AxisServer();
BeanSerializer ser = new BeanSerializer(obj.getClass(), qname, typeDesc);
SerializationContext ctx = new SerializationContext(outStr,
new MessageContext(server));
ctx.setSendDecl(false);
ctx.setDoMultiRefs(false);
ctx.setPretty(true);
try {
ser.serialize(qname, new AttributesImpl(), obj, ctx);
} catch (final Exception e) {
throw new Exception("Unable to serialize object "
+ obj.getClass().getName(), e);
}
String xml = outStr.toString();
return xml;
}
private Object deserializeAxisObject(Class<?> cls, String xml)
throws Exception {
final String SOAP_START = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"><soapenv:Header /><soapenv:Body>";
final String SOAP_START_XSI = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><soapenv:Header /><soapenv:Body>";
final String SOAP_END = "</soapenv:Body></soapenv:Envelope>";
Object result = null;
try {
Message message = new Message(SOAP_START + xml + SOAP_END);
result = message.getSOAPEnvelope().getFirstBody()
.getObjectValue(cls);
} catch (Exception e) {
try {
Message message = new Message(SOAP_START_XSI + xml + SOAP_END);
result = message.getSOAPEnvelope().getFirstBody()
.getObjectValue(cls);
} catch (Exception e1) {
throw new Exception(e1);
}
}
return result;
}
private TypeDesc getAxisTypeDesc(Object obj) throws Exception {
final Class<? extends Object> objClass = obj.getClass();
try {
final Method methodGetTypeDesc = objClass.getMethod("getTypeDesc",
new Class[] {});
final TypeDesc typeDesc = (TypeDesc) methodGetTypeDesc.invoke(obj,
new Object[] {});
return (typeDesc);
} catch (final Exception e) {
throw new Exception("Unable to get Axis TypeDesc for "
+ objClass.getName(), e);
}
}
I have fixed it, I will leave this here if anyone else needs to use it
Have fun.
I have fixed it, I will leave this here if anyone else needs to use it. See the updated version.
Thank you

Categories