I'm trying to run phantomjs in my program, below is the command I'm running.
Process exec = Runtime.getRuntime().exec(new String[]{
"C:/Users/buddy/Desktop/phantomjs-1.9.7-windows",
"-c",
"phantomjs "
+ pipedCommand + " "
+ size + " "
+ conversion.getConversionTarget().extension() + " "
+ this.local.getId()});
and I'm getting exception when I run: (But above code runs for Linux)
I have downloaded phantomjs windows version and its in the following path: C:/Users/buddy/Desktop/phantomjs-1.9.7-windows
java.io.IOException: Cannot run program "C:/Users/buddy/Desktop/phantomjs-1.9.7-windows": CreateProcess error=5, Access is denied.
I believe you need to run it from a cmd process... not sure if it helps but how I did it was to create a shellscript file with contents similar to below
echo "- Processing : Creating screenshot image from $1"
'C:\software\phantomjs' 'C:\software\rasterize.js' http://$1 $2
and then within the java code
// Create process command
String command = "cmd /c " + imageScriptLocation + " " + cleanUrl + " " + imgLocation
// Execute the process
Runtime rt = Runtime.getRuntime();
p = rt.exec(command);
// Retrieve any errors from the script
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
logger.debug("Image Script: " + line);
}
// Wait for the process to complete and the images to be generated
p.waitFor();
if you just want to use your approach above though, the below should work...
Process exec = Runtime.getRuntime().exec(new String[]{
"cmd",
"/c",
"phantomjs "
+ pipedCommand + " "
+ size + " "
+ conversion.getConversionTarget().extension() + " "
+ this.local.getId()});
You can run PhantomJS using Selenium.
DesiredCapabilities caps = new DesiredCapabilities();
String path = "Path to PhantomJS Binary";
caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, path);
WebDriver driver = new PhantomJSDriver(caps);
Related
I work on CVRP in combinatorial optimization, where the goal is to compare several models on several instances, using the OPL language. For this to e done, I first wrote and tested the said models; then I wrote an main flow control supposed to run each instance for a 2 hours duration.
My problem is that after 2 hours, and this for each model, the output file appears for some instances, containing the desired information; but for other instances, the output files do not appear, as if these instances do not exist. This problem persists even when you launch one or more of these instances in isolation.
below is the main flow control code, where BPF designates the name of the .mod file, which is simply modified in the code, when one wishes to switch to another model.
{string} datFiles=...;
main {
var source = new IloOplModelSource("BPF.mod");
var cplex = new IloCplex();
var def = new IloOplModelDefinition(source);
cplex.tilim=2*60*60;
cplex.threads=1;
for(var datFile in thisOplModel.datFiles)
{
var opl = new IloOplModel(def,cplex);
var data2= new IloOplDataSource(datFile);
opl.addDataSource(data2);
opl.generate();
var o=new IloOplOutputFile("BPF "+datFile+".txt");
if (cplex.solve()) {
if(cplex.getCplexStatus()==11){
o.writeln("instance : " + datFile
+" / opt = "
+ " / UB = " + cplex.getObjValue()
+ " / LB = " + cplex.getBestObjValue()
+" / time = " + " - "
+" / Gap = "+cplex.getMIPRelativeGap()*100+"%");
}
else {
o.writeln("instance : " + datFile
+ " / opt = " + cplex.getObjValue()
+ " / UB = " + cplex.getBestObjValue()+"*"
+" / time = " + cplex.getSolvedTime()
+ " / Gap : -");
}
o.close();
}
opl.end();
}
}
I got Index was outside the bounds of the array error when use debug mode in asp net core mvc, but its ok when run in non-debug mode (Shift+F5).
Here details of error description :
An unhandled exception occurred while processing the request.
IndexOutOfRangeException: Index was outside the bounds of the array.
AspNetCore.ReportingServices.RdlExpressions.ExpressionHostObjectModel.RemoteArrayWrapper.get_Item(int
index)
ReportProcessingException: An unexpected error occurred in Report
Processing. Index was outside the bounds of the array.
AspNetCore.ReportingServices.ReportProcessing.Execution.RenderReport.Execute(IRenderingExtension
newRenderer)
LocalProcessingException: An error occurred during local report
processing.;An unexpected error occurred in Report Processing. Index
was outside the bounds of the array.
AspNetCore.Reporting.InternalLocalReport.InternalRender(string format,
bool allowInternalRenderers, string deviceInfo, PageCountMode
pageCountMode, CreateAndRegisterStream createStreamCallback, out
Warning[] warnings)
Here my export to pdf code :
int extension = 1;
var path = $"{this._webHostEnvironment.WebRootPath}\\Report\\RptDO2.rdlc";
Dictionary<string, string> parameters = new Dictionary<string, string>();
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Encoding.GetEncoding("windows-1252");
parameters.Add("txtto", inv.Quotation.CustomerContact.Customer.CompanyName);
parameters.Add("txtaddress_detail", inv.Quotation.CustomerContact.Customer.Address1 + "\r\n"
+ inv.Quotation.CustomerContact.Customer.Address2 + "- "
+ inv.Quotation.CustomerContact.Customer.City + "- "
+ inv.Quotation.CustomerContact.Customer.State + " ("
+ inv.Quotation.CustomerContact.Customer.Zip + ")\r\n"
+ "Phone : " + inv.Quotation.CustomerContact.Customer.PhoneNumber
+ ", Email : " + inv.Quotation.CustomerContact.Customer.Email);
parameters.Add("txtdo_no", inv.Id.Replace("INV", "DO"));
parameters.Add("txtdate", inv.Quotation.CreatedAt.ToShortDateString());
parameters.Add("txtrefnum", inv.QuotationId);
parameters.Add("txtfrom", us.FirstName + " " + us.LastName);
parameters.Add("txtUP", TextUp);
parameters.Add("kop_nama", c.CpName);
parameters.Add("kop_alamat", c.CpStreetAddress);
parameters.Add("kop_alamat2", c.CpCity + " " + c.CpState + " (" + c.CpZip + ")");
parameters.Add("kop_contact", c.CpPhone);
parameters.Add("kop_email", c.CpEmail);
parameters.Add("kop_logo", Convert.ToBase64String(c.CpFoto));
parameters.Add("txtjabatan", us.Designation);
parameters.Add("txtPrintedBy", lgnuser.FirstName + " " + lgnuser.LastName);
List<vwQuotationDetail> vwQuotationDetails = new List<vwQuotationDetail>();
foreach (TblquotationDetail quos in inv.Quotation.TblquotationDetail.OrderBy(o => o.Id))
{
vwQuotationDetail quotationDetail = new vwQuotationDetail
{
id = quos.Id,
quotation_id = quos.QuotationId,
order_number = quos.OrderNumber,
product_name = quos.Product.ProductName,
product_id = quos.ProductId,
product_comments = string.IsNullOrEmpty(quos.ProductComments) ? "" : quos.ProductComments,
quantity = quos.Quantity,
unit_price = quos.UnitPrice,
unit_name = quos.Product.Unit.UnitName,
sub_total = quos.SubTotal,
product_desc = quos.Product.ProductDesc,
category_name = quos.Product.Category.CategoryName
};
vwQuotationDetails.Add(quotationDetail);
}
LocalReport localReport = new LocalReport(path);
localReport.AddDataSource("dsDO", vwQuotationDetails.ToArray());
//var result = localReport.Execute(RenderType.Pdf, extension, parameters, mimtype);
var result = localReport.Execute(RenderType.Pdf, extension, parameters);
return File(result.MainStream, "application/pdf");
Any suggestion will appreciated, thanks in advance.
Just Dont Pass extension as 1 in:
var result = localReport.Execute(RenderType.Pdf, extension, parameters);
The Solution is:
int ext = (int)(DateTime.Now.Ticks >> 10);
var result = localReport.Execute(RenderType.Pdf, ext, param);
In other words, Extension should not be same for every report.
I am trying to upload file in a selenium test that is run on chrome browser on an android phone. The usual element.sendkeys(path) is not working.
Are there any known alternatives for android ?
It may help to upload the file:
public CorePage UploadHack(string fileInputId, string contentType, string fileContent, string fileName, string angularScopeVar)
{
UploadFile(_filePath);
var uploadHack =
"(function(){" +
"function convert(base64){" +
"var raw = atob(base64);" +
"var arr = new Uint8Array(new ArrayBuffer(raw.length));" +
"for (var i = 0; i < raw.length; i++){" +
"arr[i] = raw.charCodeAt(i);" +
"}" +
"return arr; " +
"}" +
$"var file = new Blob([convert('{fileContent}')], {{'type':'{contentType}'}}); " +
$"file.name = '{fileName}'; " +
$"angular.element('#{fileInputId}').scope().{angularScopeVar} = file;" +
"})()";
Driver.ExecuteJavaScript(uploadHack);
return this;
}
Katalon is popular in automation testing. I have already used it in our project and it works amazingly.
Now, What I want to achieve is to create a test case where it opens a terminal (using mac) and type in some commands to run it like for example:
cd /documents/pem/key.pem
connect to -my server via SSH#method
sudo su
yum install php7
yum install mysql
You are not alone, and with custom keywords you can achieve what you want. Here is an example showing a test of a command line app. You could do the same thing to call any command line script you wish. Think of a runCmd keyword, or a runCmdWithOutput to grab the output and run various asserts on it.
#Keyword
def pdfMetadata(String input) {
KeywordUtil.logInfo("input: ${input}")
def csaHome = System.getenv("CSA_HOME")
def cmd = "cmd /c ${csaHome}/bin/csa -pdfmetadata -in \"${projectPath}${input}\"";
runCmd(cmd)
}
def runCmd(String cmd) {
KeywordUtil.logInfo("cmd: ${cmd}")
def proc = cmd.execute();
def outputStream = new StringBuffer();
def errStream = new StringBuffer()
proc.waitForProcessOutput(outputStream, errStream);
println(outputStream.toString());
println(errStream.toString())
if(proc.exitValue() != 0){
KeywordUtil.markFailed("Out:" + outputStream.toString() + ", Err: " + errStream.toString())
}
}
You can then use this in a test case:
CustomKeywords.'CSA.pdfMetadata'('/src/pdf/empty.pdf')
Here is another custom keyword! It is takes the file name and path, and if you don't give it a path, it search for the file in the project root directory. It export the batch file's output in a batch_reports folder in your project folder, you need to create that in advance.
#Keyword
def runPostmanBatch(String batchName , String batchPath){
// source: https://www.mkyong.com/java/how-to-execute-shell-command-from-java/
String firstParameter = "cmd /c " + batchName;
String secondParameter = batchPath;
if (batchPath == ""){
secondParameter = RunConfiguration.getProjectDir();
}
try {
KeywordUtil.logInfo("Executing " + firstParameter + " at " + secondParameter)
Process process = Runtime.getRuntime().exec(
firstParameter , null, new File(secondParameter));
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
int exitVal = process.waitFor();
Date atnow = new Date()
String now = atnow.format('yy-MM-dd HH-mm-ss')
String report_path = RunConfiguration.getProjectDir() + "/postman_reports/" + RunConfiguration.getExecutionSourceName() + "_" + now + ".txt"
BufferedWriter writer = new BufferedWriter(new FileWriter(report_path));
writer.write(output.toString());
writer.close();
KeywordUtil.logInfo("postman report at: " + report_path)
if (exitVal == 0) {
println("Success!");
println(output);
KeywordUtil.markPassed("Ran successfully")
} else {
KeywordUtil.markFailed("Something went wrong")
println(exitVal);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
I've done some research. I did not found any resources or any people that is looking for the same thing I am. I think this is officially, No. The answer to this is, it is not possible.
It is possible to run Katalon Studio from the command line.
There's a short tutorial here.
And it will be possible to override Profile Variables via command line execution mode from v5.10 (currently in beta).
An example given on Katalon forum is:
Simply pass the parameters in command line using: -g_XXX = XXX
Below is an example of override an URL variable:
-g_URL=http://demoaut.katalon.com
I want to process and verify that PDFs within a folder are valid PDF/A files. The problem is that I need to process a folder with piles of files including word and excel among others that preflight converts to PDFs, processes, and then hangs for user input to discard the temperary file. There are some hundred files, so waiting for user input isn't doable.
Perhaps I'm not using the correct phrases when I search, but I can't find out how to force Adobe Acrobat DC to only process PDF files. I've found that in Acrobat X you can specify source files https://www.evermap.com/ActionWizardX.asp, but I've not found an equivalent in DC.
Is there a way to force an action to only process PDF files?
Edit:
Following #Joel Geraci's suggestion and finding this post, I've created the following script that runs in an action. At this point, It seems to run the profile, but I don't know if it actually modifies the document, since the call to this.closeDoc() doesn't prompt to save the document, and the resulting document doesn't seem to be saved as a PDF/A file.
/* Convert PDF/A-3a */
try
{
if(this.path.split('.').pop() === 'pdf')
{
var oProfile = Preflight.getProfileByName("Convert to PDF/A-3a");
if( oProfile != undefined )
{
var myPreflightResult = this.preflight( oProfile);
console.println( "Preflight found " + myPreflightResult.numErrors + " Errors.");
console.println( "Preflight found " + myPreflightResult.numWarnings + " Warnings.");
console.println( "Preflight found " + myPreflightResult.numInfos + " Infos.");
console.println( "Preflight fixed " + myPreflightResult.numFixed + " Errors.");
console.println( "Preflight not fixed " + myPreflightResult.numNotFixed + " Errors.");
this.closeDoc();
}
}
}
catch(theError)
{
$error = theError;
this.closeDoc( {bNoSave : true} );
}
Edit 2:
I ended up settling on using the saveAs function. I'm not sure how to export the XML data to a file, but this seems to be sufficient.
/* Convert PDF/A-3a */
try
{
if(this.path.split('.').pop() === 'pdf')
{
var oThermometer = app.thermometer;
var oProfile = Preflight.getProfileByName("Convert to PDF/A-3a");
if( oProfile != undefined )
{
var myPreflightResult = this.preflight( oProfile, false, oThermometer );
console.println( "Preflight found " + myPreflightResult.numErrors + " Errors.");
console.println( "Preflight found " + myPreflightResult.numWarnings + " Warnings.");
console.println( "Preflight found " + myPreflightResult.numInfos + " Infos.");
console.println( "Preflight fixed " + myPreflightResult.numFixed + " Errors.");
console.println( "Preflight not fixed " + myPreflightResult.numNotFixed + " Errors.");
if(myPreflightResult.numErrors > 0) {
var cXMLData = myPreflightResult.report(oThermometer);
console.println(cXMLData);
}
this.saveAs(path,"com.callas.preflight.pdfa");
}
}
}
catch(theError)
{
$error = theError;
this.closeDoc( {bNoSave : true} );
}
Edit 3:
So the problem is that non-PDF files are converted and read before my JavaScript is executed, which means that the this.path.split('.').pop() === 'pdf' doesn't actually filter out anything. I found that the requiresFullSave property of the Doc class specifies whether the document is a temp file or not. I have, however, found that I am still asked if I want to save the temp file, which doesn't help.
Edit 4
Calling Doc.closeDoc(true) on a temporary file causes Acrobat to crash and there doesn't seem to be another way to close a document without saving. I've found there is no clear way (that I've found) to close a temp document without prompting the user to save and have resorted to deleting all non-PDF files.
Final script:
/* Convert PDF/A-3a */
try
{
console.println(path + " is temp: " + requiresFullSave);
if(!requiresFullSave)
{
var oThermometer = app.thermometer;
var oProfile = Preflight.getProfileByName("Convert to PDF/A-3a");
if( oProfile != undefined )
{
var myPreflightResult = this.preflight( oProfile, false, oThermometer );
console.println( "Preflight found " + myPreflightResult.numErrors + " Errors.");
console.println( "Preflight found " + myPreflightResult.numWarnings + " Warnings.");
console.println( "Preflight found " + myPreflightResult.numInfos + " Infos.");
console.println( "Preflight fixed " + myPreflightResult.numFixed + " Errors.");
console.println( "Preflight not fixed " + myPreflightResult.numNotFixed + " Errors.");
if(myPreflightResult.numErrors > 0) {
var cXMLData = myPreflightResult.report(oThermometer);
console.println(cXMLData);
}
this.saveAs(path,"com.callas.preflight.pdfa");
}
}
else{
// As noted in the documentation found [here][2]
// Note:If the document is temporary or newly created, setting dirty to false has no effect. That is, the user is still asked to save changes before closing the document. See requiresFullSave.
// this.dirty = false;
// this.closeDoc(true);
}
}
catch(theError)
{
}
Rather than creating an action that runs preflight, try creating an action that runs some JavaScript. The JavaScript would test for the file extension of the file being processed and then execute preflight via JavaScript if it's a PDF, skipping it if not.