I wrote a Java program that creates an Excel Workbook with at least 4 sheets & loaded into it some vb modules (by loading a template.xlsm with vb modules) Now I want to transform this Excel workbook into a PDF so I have this code in Excel macro VBA
Dim saveLocation As String
saveLocation = Application.ThisWorkbook.path
Dim ws As Worksheet
For Each ws In Application.ThisWorkbook.Worksheets
With ws.PageSetup
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = False
.Orientation = xlLandscape
.CenterVertically = True
.CenterHorizontally = True
.PaperSize = xlPaperTabloid
End With
Next
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=saveLocation
End Sub
I executed it from Excel VBA and its working fine
However, what I want is to run it from Java directly after it's been created
So what I did after writing the Excel Workbook (in Java) is the following
I wrote from Java into a text file having a VBS extension (module.vbs) the following code
Sub ExcelMacro()
Dim objExcel
Dim objWorkbook
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("PATH\Cost Sheet_233.xlsm")
objExcel.Run "'Cost Sheet_233.xlsm'!Module3.SaveActiveSheetsAsPDF"
objWorkbook.Save
objWorkbook.Close
objExcel.Quit
End Sub
then I executed the following command
try {
Runtime.getRuntime().exec( new String[] { "C:\\Windows\\System32\\wscript.exe", filePath + "\\module.vbs"} );
}
catch (Exception ex)
{
ex.printStackTrace();
}
The output is/should be a PDF file having all Excel sheets
Again, when I run the code from Excel VBA, it works fine. Both the one in the module.vbs and the macro work fine and generate the PDF File, but the Java exec statement isn't
Of course, the paths are right too 100% (wscript.exe exists)
I also tried cscript.exe but didn't work
What could the problem be or did I miss something?
I figured it out yesterday after asking the question.
I tried other ways in writing the .vbs file and the following seemed to work when I call it from Java
Set objShell = CreateObject("WScript.Shell")
Dim cur
cur="Path"
WScript.Echo cur
ExcelMacroExample
Sub ExcelMacroExample()
Dim xlApp
Dim xlBook
Dim xlsFile
xlsFile=cur & "\Cost Sheet_274.xlsm"
Set xlApp=CreateObject("Excel.Application")
Set xlBook =xlApp.Workbooks.Open(xlsFile)
xlApp.Run "SaveActiveSheetsAsPDF"
xlBook.Save
xlApp.Quit
End Sub
and this the Java code that runs the .vbs file
try {
Runtime.getRuntime().exec(new String[] { "C:\\Windows\\System32\\wscript.exe", filePath + "\\module.vbs" });
} catch (Exception ex) {
ex.printStackTrace();
}
Related
After running my load test Jmeter generate result onto "summary.csv".
Some urls in this file looks like:
1482255989405,3359,POST ...users/G0356GM7QOITIMGA/...
1482255989479,3310,POST ...users/HRC50JG3T524N9RN/...
1482255989488,3354,POST ...users/54QEGZB54BEWOCJJ/...
Where "...users/G0356GM7QOITIMGA/..." - its URL column.
After that I try to generate jmeter-report using this command:
jmeter -g summary.csv -o report
Howewer this action throw Out of memory exception (because of many different URLs).
So I decide to edit summary.csv in tearDown Thread Group and replace all ID to "someID" string, using BeanShell Sampler:
import java.io.*;
import org.apache.jmeter.services.FileServer;
try {
String sep = System.getProperty("line.separator");
String summaryFileDirPath = FileServer.getFileServer().getBaseDir() + File.separator;
String summaryFilePath = summaryFileDirPath + "summary.csv";
log.info("read " + summaryFilePath);
File file = new File(summaryFilePath);
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
String text = "";
while ((line = reader.readLine()) != null) {
text += line + sep;
}
reader.close();
log.info(summaryFilePath);
file.delete();
FileWriter writer = new FileWriter(summaryFileDirPath + "summary.csv", false);
writer.write(text.replaceAll("users/[A-Z0-9]*/", "users/EUCI/"));
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
Result:summary.csv screen
Seems like Jmeter append some rows after tearDown Thread Group ends his work.
How can I edit summary.csv file after test run using only jmeter script?
PS: I need collect result only in summary.csv
There is a JMeter Property - jmeter.save.saveservice.autoflush, most probably you are suffering from its default value of false
# AutoFlush on each line written in XML or CSV output
# Setting this to true will result in less test results data loss in case of Crash
# but with impact on performances, particularly for intensive tests (low or no pauses)
# Since JMeter 2.10, this is false by default
#jmeter.save.saveservice.autoflush=false
You can override the value in at least 2 ways:
Add the next line to user.properties file:
jmeter.save.saveservice.autoflush=true
Pass it to JMeter via -J command-line argument like:
jmeter -Jjmeter.save.saveservice.autoflush=true -n -t ....
See Apache JMeter Properties Customization Guide article for comprehensive information on JMeter Properties and ways of working with them
I am trying to copy a file 'project.jpg' from my /sdcard to /sdcard/temp/ folder, but for some reason , the file isn't getting copied. I am testing using a virtual device and have transferred the file 'project.jpg' via the adb shell. The function used to copy the file is,
public void $copyFile()
{
try
{
cpSrc = escapePath(this.cpSrc);
cpDest = escapePath(this.cpDest);
Log.d("$copyFile()","cpSrc = "+cpSrc);
Log.d("$copyFile()","cpDest = "+cpDest);
String destination = getFilename(cpDest,extractFilename(cpSrc));
Runtime.getRuntime().exec("dd in="+cpSrc+" of="+destination);
Log.d("$copyFile()","executed command : 'dd in="+cpSrc+" of="+destination+"'");
displayToast("File Copied Sucessfully.");
clearAllModes();
return;
}
catch(Exception e)
{
displayToast("$copyFile Error : "+e);
this.clearCopyBuffer();
clearAllModes();
}
}
where escapePath() is used to escape space characters(if any) in the given paths. I got the debug Logs as follows,
cpSrc = /sdcard/project.jpg
cpDest = /sdcard/temp
executed command : 'dd in=/sdcard/project.jpg of=/sdcard/temp/project.jpg
Could anyone point the error in the code,
BTW suggestions for other ways of coping files/folders ? it would be helpful as i am trying my hand at a file manager.
I am new to using Mockito test framework. I need to unit test one method which return the the string content. Also the same contents will be stored in one .js file (i.e. "8.js").
How do I verify the the string contents returned from the method is as expected as i want.
Please find the below code for generating the .js file:
public String generateJavaScriptContents(Project project)
{
try
{
// Creating projectId.js file
FileUtils.mkdir(outputDir);
fileOutputStream = new FileOutputStream(outputDir + project.getId() + ".js");
streamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
StringTemplateGroup templateGroup =
new StringTemplateGroup("viTemplates", "/var/vi-xml/template/", DefaultTemplateLexer.class);
stringTemplate = templateGroup.getInstanceOf("StandardJSTemplate");
stringTemplate.setAttribute("projectIdVal", project.getId());
stringTemplate.setAttribute("widthVal", project.getDimension().getWidth());
stringTemplate.setAttribute("heightVal", project.getDimension().getHeight());
stringTemplate.setAttribute("playerVersionVal", project.getPlayerType().getId());
stringTemplate.setAttribute("finalTagPath", finalPathBuilder.toString());
streamWriter.append(stringTemplate.toString());
return stringTemplate.toString();
}
catch (Exception e)
{
logger.error("Exception occurred while generating Standard Tag Type Content", e);
return "";
}
}
The output of above method writes the .js file and the contents of that file are looks something below:
var projectid = 8; var playerwidth = 300; var playerheight =
250; var player_version = 1; .....
I have written the testMethod() using mockito to test this, however i am able to write the .js file successfully using the test method, but how do I verify its contents?
Can anyone help me to sort out this problem?
As #ŁukaszBachman mentions, you can read the contents from the js file. There are a couple of things to consider when using this approach:
The test will be slow, as you will have to wait for the js content to be written to the disk, read the content back from the disk and assert the content.
The test could theoretically be flaky because the entire js content may not be written to the disk by the time the code reads from the file. (On that note, you should probably consider calling flush() and close() on your OutputStreamWriter, if you aren't already.)
Another approach is to mock your OutputStreamWriter and inject it into the method. This would allow you to write test code similar to the following:
OutputStreamWriter mockStreamWriter = mock(OutputStreamWriter.class);
generateJavaScriptContents(mockStreamWriter, project);
verify(mockStreamWriter).append("var projectid = 8;\nvar playerwidth = 300;...");
http://mockito.googlecode.com/svn/branches/1.5/javadoc/org/mockito/Mockito.html#verify%28T%29
If you persist this *.js file on file system then simply create util method which will read it's contents and then use some sort of assertEquals to compare it with your fixed data.
Here is code for reading file contents into String.
I m passing multiple tab delim files into R via Java.The R programm merges those tab delim files as single file and sends back to java and it is captured in the variable "name".Now I want to rename and save that file stored in "name" as tab delim using save dialog box in windows.Any help highly appreciated.Here is the java code:
import org.rosuda.REngine.*;
public class rjava {
// Before this run Rserve() command in R
public String ana(String filenames)
{
String name = "";
try{
System.out.println("INFO: Trying to connect to R ");
RConnection c = new RConnection();
System.out.println("INFO: Connected to R");
System.out.println("INFO: The Server version is "+ c.getServerVersion());
// c.voidEval("source('D:/combine/combining_files.r')");
c.voidEval("source('D:/combine/merge.r')");
c.assign("file",filenames);
// name = (c.eval("fn(file)").asString());
name = (c.eval("combine (file)").asString());
c.close();
}
catch(Exception e)
{
System.out.println("ERROR: In Connection to R");
System.out.println("The Exception is "+ e.getMessage());
e.printStackTrace();
}
return name;
}
}
I find passing complex objects between R and Java to be a pain the ass. I would not pass the full data, but rather would pass only file names as a string. Either have Java tell R to write out the new file (my pref) or have Java read in the file and then write out with a new name.
Can you modify the R program, so that it outputs files in the same path with a given file name, such as [path]/filename.out?
Otherwise, you can modify the execte string so that the R program outputs in a given location.
See http://cran.r-project.org/doc/manuals/R-intro.html#Invoking-R-from-the-command-line
When working at a command line on UNIX or Windows, the command ‘R’ can be used both for starting the main R program in the form R [options] [<infile] [>outfile]
-- EDIT
I just saw that you are using an RConnection. According to the R docs, you can define where to pipe stdout
The function sink, sink("record.lis") will divert all subsequent output from the console to an external file, record.lis.
I'm making a falling sand game in Java. I want users to be able to write their own engine for it using a simpler language. Falling sand games can be very CPU intensive so I want to have the engine running as fast as possible while not having to manually compile.
I need to know how to compile rhino javascript files to .class files by at runtime to be used.
I've looked for a way but couldn't find any other than manually compiling it by using the command line which I don't want users to have to do.
There's a short tutorial here:
Scripting: Compiling Scripts in Java
My solution here:
Has anyone used or written an Ant task to compile (Rhino) JavaScript to Java bytecode?
You can compile your scripts at runtime using Context.compileString(). This produces a Script object which you can reuse.
Script s = someContext.compileString(myScript, "<cmd>", 1, null);
// Store s, cache it in a map or something, maybe even serialize and persist it.
// Later...
Object result = s.exec(anotherContext, someScope);
The performance difference between something like this and using Context.evaluateString() could easily be multiple orders of magnitude faster.
You can try the follow sample:
void toClassFile( String script ) throws IOException {
CompilerEnvirons compilerEnv = new CompilerEnvirons();
ClassCompiler compiler = new ClassCompiler( compilerEnv );
Object[] compiled = compiler.compileToClassFiles( script, null, 1, "javascript.Test" );
for( int j = 0; j != compiled.length; j += 2 ) {
String className = (String)compiled[j];
byte[] bytes = (byte[])compiled[(j + 1)];
File file = new File( className.replace( '.', '/' ) + ".class" );
file.getParentFile().mkdirs();
try (FileOutputStream fos = new FileOutputStream( file )) {
fos.write( bytes );
}
}
}