When I run a work item on the DA, I get the following reporting:
[07/24/2019 17:50:39] InventorCoreConsole.exe Information: 0 : Loading plug-in: iLogic Plugin
[07/24/2019 17:50:39] InventorCoreConsole.exe Information: 0 : Activating plug-in: iLogic Plugin
[07/24/2019 17:50:41] iLogic Plugin: initializing...
[07/24/2019 17:50:43] Unspecified error (Exception from HRESULT: 0x80004005 (E_FAIL))
[07/24/2019 17:50:43] InventorCoreConsole.exe Information: 0 : Opening document: T:\Aces\Jobs\66472a1ecb0f4612a610127e9e0ee497\Jet_Engine_Model.zip
[07/24/2019 17:50:43]
[07/24/2019 17:50:43] The process 1788 ended.
[07/24/2019 17:50:43] Process exit code: -1
[07/24/2019 17:50:44]
[07/24/2019 17:50:44] End Inventor Core Engine standard output dump.
[07/24/2019 17:50:44] Error: InventorCoreConsole.exe exits with code -1 which indicates an error.
[07/24/2019 17:50:44] End script phase.
[07/24/2019 17:50:44] Error: An unexpected error happened during phase CoreEngineExecution of job.
Usually, the error occurs after opening the zip file. I'm wondering if I'm specifying inputs incorrectly, or if the server is crashing because it's trying to run the iLogic plugin?
The following are the activity specs. Zip file is specified for input and output.
Activity activitySpec = new Activity()
{
Id = activityName,
Appbundles = new List<string>() { string.Format("{0}.{1}+{2}", NickName, appBundleName, Alias) },
CommandLine = new List<string>() { commandLine },
Engine = engineName,
Parameters = new Dictionary<string, Parameter>()
{
{ "inputFile", new Parameter() { Description = "input file", LocalName = "Jet_Engine_Model.zip", Ondemand = false, Required = true, Verb = Verb.Get, Zip = true } },
{ "inputJson", new Parameter() { Description = "input json", LocalName = "params.json", Ondemand = false, Required = false, Verb = Verb.Get, Zip = false } },
{ "outputFile", new Parameter() { Description = "output file", LocalName = "Jet_Engine_Model.zip", Ondemand = false, Required = true, Verb = Verb.Put, Zip = true } }
},
Settings = new Dictionary<string, ISetting>()
{
{ "script", new StringSetting(){ Value = engineAttributes.script } }
}
};
These are the workitem parameters. Are there any items that should be specified missing?
XrefTreeArgument inputFileArgument = new XrefTreeArgument()
{
Verb = Verb.Get,
Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, "Jet_Engine_Model.zip"),
Headers = new Dictionary<string, string>(){{ "Authorization", "Bearer " + oauth.access_token }}};
// 2. input json
dynamic inputJson = new JObject();
inputJson.length = lengthParam;
inputJson.numberOfFairings = fairingsParam;
XrefTreeArgument inputJsonArgument = new XrefTreeArgument(){
Verb = Verb.Get,
Url = "data:application/json, " + ((JObject)inputJson).ToString(Formatting.None).Replace("\"", "'")};
// 3. output file
//string outputFileNameOSS = string.Format("{0}_output_{1}",
DateTime.Now.ToString("yyyyMMddhhmmss"),
Path.GetFileName(input.inputFile.FileName)); // avoid overriding
XrefTreeArgument outputFileArgument = new XrefTreeArgument(){
Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, "Jet_Engine_Model.zip"),
Verb = Verb.Put,
Headers = new Dictionary<string, string>(){{"Authorization", "Bearer " + oauth.access_token }}};
Thanks for your command line.
If I understand correctly you are trying to send zipped file which you would like to have unzipped before opening one of contained file in Inventor. In that case you have to specify name of contained file (because zip can contains more than one file). You can choose name of the file by adding attribute PathInZip to your inputFile argument in WorkItem definition. Like this:
XrefTreeArgument inputFileArgument = new XrefTreeArgument()
{
Verb = Verb.Get,
Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, "Jet_Engine_Model.zip"),
Headers = new Dictionary<string, string>(){{ "Authorization", "Bearer " + oauth.access_token }},
PathInZip = "FileNameInsideZip.ipt"
};
Related
Please refer to below code
data "amazon-ami" "ubuntu" {
most_recent = true
filters = {
virtualization-type = "hvm"
name = "ubuntu/images/*ubuntu-focal-20.04-amd64-server-*"
root-device-type = "ebs"
}
owners = ["099720109477"]
}
source "null" "one" {
communicator = "none"
}
build {
name = "source-ouput"
sources = ["source.null.one"]
provisioner "shell-local" {
inline = [
"echo ${data.amazon-ami.ubuntu}", ##### <--- problem happens here
]
}
}
As you can see in the code, I want to print out the return value of data "amazon-ami" "ubuntu"
If I run this with packer build .. error occurs like below
Error: Failed preparing provisioner-block "shell-local" ""
on main.pkr.hcl line 20:
(source code not available)
main.pkr.hcl:22,15-37: Invalid template interpolation value; Cannot include the
given value in a string template: string required.
Is there any solution to print the object that returned by data?
How do you capture a JSON object as a prettified string using a Jenkins declarative-syntax pipeline?
pipeline {
agent any
stages {
stage( "Set up" ) {
steps {
script {
hostname = "bld-machine"
reply_email = "jenkins#${hostname}.company.com"
actor_email = "user#company.com"
status_json = initStatusJson()
}
}
}
/** Try figure out the difference between "global" and "env." variables. */
stage( "Capture variables" ) {
steps {
script {
status_json.env["var"] = "${env.var}" as String
status_json.env["var2"] = "${var}" as String
}
}
}
}
post {
always {
script {
def pretty_json = writeJSON( returnText: true, json: status_json )
}
emailext( subject: "CI/CD | ${currentBuild.currentResult}",
from: "${reply_email}",
to: "${actor_email}",
mimeType: "text/plain",
body: "${pretty_json}" )
}
}
}
def initStatusJson() {
def json_obj = readJSON text: '{}'
json_obj.job = readJSON text: '{}'
json_obj.env = [:]
json_obj.job.name = "${JOB_BASE_NAME}" as String
json_obj.job.number = "${BUILD_ID}" as String
json_obj.job.server = "${JENKINS_URL}" as String
json_obj.job.visualization = "${JENKINS_URL}/blue/organizations/jenkins/${JOB_BASE_NAME}/detail/${JOB_BASE_NAME}/${BUILD_ID}/pipeline" as String
return json_obj
}
The def pretty_json =... statement in the above Jenkinsfile triggers the following error:
WARNING: Unknown parameter(s) found for class type WARNING: Unknown parameter(s) found for class type 'org.jenkinsci.plugins.pipeline.utility.steps.json.WriteJSONStep': returnText
[Pipeline] }
[Pipeline] // script
Error when executing always post condition:
java.lang.IllegalArgumentException: You have to provided a file for writeJSON.
at org.jenkinsci.plugins.pipeline.utility.steps.json.WriteJSONStepExecution.run(WriteJSONStepExecution.java:61)
at org.jenkinsci.plugins.pipeline.utility.steps.json.WriteJSONStepExecution.run(WriteJSONStepExecution.java:43)
at org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution.lambda$start$0(SynchronousNonBlockingStepExecution.java:47)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
What I have tried:
The def pretty_json = writeJSON( returnText: true, json: status_json ) statement is inspired by these resources:
Jenkinsfile pipeline construct JSON object and write to file
https://www.jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#writejson-write-json-to-a-file-in-the-workspace
I also tried def pretty_json = writeJSON returnText: true, json: status_json which resulted in an identical error.
status_json.toString() returns a valid, but non-prettified JSON string.
I tried def pretty_json = JsonOutput.toJson(status_json) based on Create JSON strings from Groovy variables in Jenkins Pipeline, and it generates this error:
Error when executing always post condition:
groovy.lang.MissingPropertyException: No such property: JsonOutput for class: groovy.lang.Binding
Tried def pretty_json = groovy.json.JsonOutput.prettyPrint(status_json) based on https://gist.github.com/osima/1161966, and it generated this error:
Error when executing always post condition:
groovy.lang.MissingMethodException: No signature of method: java.lang.Class.prettyPrint() is applicable for argument types: (net.sf.json.JSONObject)
Update: Attempted #daggett's solution as follows:
post {
always {
script {
def pretty_json = status_json.toString(2)
}
emailext( subject: "CI/CD | ${currentBuild.currentResult}",
from: "${reply_email}",
to: "${actor_email}",
mimeType: "text/plain",
body: "${pretty_json}" )
}
}
...and also tried some variations like pretty_json = ... (instead of def pretty_json = ...) and also moving the pretty_json assignment outside the script{...} scope...but none worked.
Inside the script{...} context, the .toString(2) generated this error:
Scripts not permitted to use method net.sf.json.JSON toString int.
Outside the script{...} context, it generated what I interpret to be a "syntax error":
WorkflowScript: 79: Expected a step # line 79, column 7.
pretty_json = status_json.toString(2)
According to last error message
groovy.lang.MissingMethodException:
No signature of method: java.lang.Class.prettyPrint()
is applicable for argument types: (net.sf.json.JSONObject)
You have net.sf.json.JSONObject in status_json variable.
that's really strange - seems you are getting status_json not in a standard way for jenkins
however according to documentation of this class
http://json-lib.sourceforge.net/apidocs/jdk15/net/sf/json/JSONObject.html#toString(int)
just do following to make pretty json:
def pretty_json = status_json.toString(2)
If you have Scripts not permitted to use method XYZ exception:
for security reasons a lot of non-standard methods are disabled in jenkins.
refer this answer to resolve this kind of issue: https://stackoverflow.com/a/39412951/1276664
and finally - almost every case from your question should work:
writeJSON( returnText: true, json: status_json ) :
update pipeline-utility-steps jenkins plugin to the latest version to support returnText parameter
the same as above
...
JsonOutput.toJson(status_json) : JsonOutput class located in groovy.json package. you could import this package at t
he beginning of the script import groovy.json or call it like this: groovy.json.JsonOutput.toJson(status_json). note that this method returns non-formatted json.
groovy.json.JsonOutput.prettyPrint(status_json) : check the documentation for JsonOutput.prettyPrint - it could be called for string and not for object. so this could work: groovy.json.JsonOutput.prettyPrint(status_json.toString()) but only in case when status_json.toString() returns a valid json and JsonOutput.prettyPrint allowed to be called in jenkins admin.
I just did a test and it gave results :
def pretty_json = writeJSON( returnText: true, json: status_json , pretty: 4)
Note : Ensure you have the plugin Pipeline Utility Steps installed. Or reinstall it again.
Below is the script example:
#!groovy
import hudson.model.Result
import groovy.json.*
pipeline
{
agent any
stages
{
stage ('Set up')
{
steps
{
script
{
hostname = "bld-machine"
reply_email = "jenkins#${hostname}.company.com"
actor_email = "user#company.com"
status_json = initStatusJson()
println (status_json)
}
}
}
stage ('Capture variables')
{
steps
{
script
{
// Added just for test
status_json.env["var"] = "Alt" as String
status_json.env["var2"] = "su" as String
println (status_json)
}
}
}
}
post {
always {
script {
def pretty_json = writeJSON( returnText: true, json: status_json , pretty: 4)
println (pretty_json)
emailext( subject: "CI/CD | ${currentBuild.currentResult}",
from: "${reply_email}",
to: "${actor_email}",
mimeType: "text/plain",
body: "${pretty_json}" )
}
}
}
}
def initStatusJson() {
def json_obj = readJSON text: '{}'
json_obj.job = readJSON text: '{}'
json_obj.env = [:]
json_obj.job.name = "${JOB_BASE_NAME}" as String
json_obj.job.number = "${BUILD_ID}" as String
json_obj.job.server = "${JENKINS_URL}" as String
json_obj.job.visualization = "${JENKINS_URL}/blue/organizations/jenkins/${JOB_BASE_NAME}/detail/${JOB_BASE_NAME}/${BUILD_ID}/pipeline" as String
return json_obj
}
Output log :
Using Adams example from https://forge.autodesk.com/blog/store-template-documents-appbundle, i am trying to open an idw document and save as a pdf. I am getting the following error from forge
InventorCoreConsole.exe Information: 0 : Processing failed: System.Runtime.InteropServices.COMException (0x80004005): Unspecified error (Exception from HRESULT: 0x80004005 (E_FAIL))
at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
at Inventor.TranslatorAddIn.SaveCopyAs(Object SourceObject, TranslationContext Context, NameValueMap Options, DataMedium TargetData)
at UpdateIPTParam.SampleAutomation.Run(Document doc) InventorCoreConsole.exe Error: 0 : Inventor message: Failed to publish DWF file. InventorCoreConsole.exe Error: 0 : Inventor inner xml:
code to open plugin
string idwDocPath = System.IO.Path.Combine(assemblyPath, parameters["generator"], "test.idw");
Document idwDoc = m_server.Documents.Open(idwDocPath, false);
pdf output code
TranslatorAddIn PDFAddIn;
TranslationContext context;
NameValueMap options;
DataMedium dataMedium;
GetPDFAddIn(m_server, out PDFAddIn, out context, out options, out dataMedium);
dataMedium.FileName = System.IO.Path.Combine(assemblyPath, parameters["generator"], "sampleOutput.pdf");
PDFAddIn.SaveCopyAs(idwDoc, context, options, dataMedium);
// Close the idw
idwDoc.Close(true);
void GetPDFAddIn(InventorServer ThisApplication, out TranslatorAddIn PDFAddIn, out TranslationContext context, out NameValueMap options, out DataMedium dataMedium)
{
PDFAddIn = (TranslatorAddIn)ThisApplication.ApplicationAddIns.ItemById["{0AC6FD96-2F4D-42CE-8BE0-8AEA580399E4}"];
context = ThisApplication.TransientObjects.CreateTranslationContext();
context.Type = IOMechanismEnum.kFileBrowseIOMechanism;
options = ThisApplication.TransientObjects.CreateNameValueMap();
options.Value["All_Color_AS_Black"] = 1;
options.Value["Remove_Line_Weights"] = 1;
options.Value["Vector_Resolution"] = 400;
options.Value["Sheet_Range"] = Inventor.PrintRangeEnum.kPrintAllSheets;
options.Value["Custom_Begin_Sheet"] = 1;
options.Value["Custom_End_Sheet"] = 1;
dataMedium = ThisApplication.TransientObjects.CreateDataMedium();
}
Any thoughts on why i would be getting this error?
Usually option settings is wrapped in if block.
// Check whether the translator has 'SaveCopyAs' options
if(PDFAddIn.HasSaveCopyAsOptions(oDocument, oContext, oOptions)){
// Options for drawings...
oOptions.Value["Sheet_Range"] = Inventor.PrintRangeEnum.kPrintCurrentSheet;
oOptions.Value["All_Color_AS_Black"] = 0;
// oOptions.Value["Remove_Line_Weights"] = 0;
// oOptions.Value["Vector_Resolution"] = 400;
// oOptions.Value["Custom_Begin_Sheet"] = 2;
// oOptions.Value["Custom_End_Sheet"] = 4;
}
I've spent a better part of a day trying to figure out the correct JSON body and arguments to update an OU; I'm actually trying to rename an OU. I'm close but in any case, the solution has so far escaped me.
I've referenced these docs so far:
https://developers.google.com/admin-sdk/directory/v1/reference/orgunits/update#http-request
https://developers.google.com/resources/api-libraries/documentation/admin/directory_v1/python/latest/admin_directory_v1.orgunits.html#update
I have tried a few variations on arguments in the object with parameters passed to AdminDirectory.Orgunits.update. Ultimately, there are no examples so I'm not 100% sure what the correct parameters are.
Here's my test function thus far as well:
function test_renameOU(){
/* Args:
customerId: string, Immutable ID of the G Suite account (required)
orgUnitPath: string, Full path of the organizational unit or its ID (required) (repeated)
body: object, The request body. (required)
The object takes the form of:
{ # JSON template for Org Unit resource in Directory API.
"kind": "admin#directory#orgUnit", # Kind of resource this is.
"parentOrgUnitPath": "A String", # Path of parent OrgUnit
"name": "A String", # Name of OrgUnit
"etag": "A String", # ETag of the resource.
"orgUnitPath": "A String", # Path of OrgUnit
"parentOrgUnitId": "A String", # Id of parent OrgUnit
"blockInheritance": True or False, # Should block inheritance
"orgUnitId": "A String", # Id of OrgUnit
"description": "A String", # Description of OrgUnit
}
*/
/* Function to perform rename */
function renameOU(customerId, orgUnitPath, body){
Logger.log(customerId + ", " + orgUnitPath + ", " + JSON.stringify(body))
try{
var org = AdminDirectory.Orgunits.update(customerId, orgUnitPath, body)
}catch(e){
Logger.log(JSON.stringify(e));
}
}
/* Arguments */
var customerId = 'my_customer';
var oldOUname = "Education";
var parentOrgUnitPath = "/Users/200 COGS";
var orgUnitId = "id:03ph8a2z39wdr3v";
var orgUnitPath = parentOrgUnitPath + "/" + oldOUname;
var parentOrgUnitId = "id:03ph8a2z1lakohp";
var newOUname = "255 Education";
Logger.log(orgUnitPath);
var body = { //# JSON template for Org Unit resource in Directory API.
"kind": "admin#directory#orgUnit", //# Kind of resource this is.
"parentOrgUnitPath": parentOrgUnitPath, //# Path of parent OrgUnit
"name": newOUname, //# Name of OrgUnit
"orgUnitPath": parentOrgUnitPath + "/" + newOUname, //# Path of OrgUnit
"parentOrgUnitId": parentOrgUnitId, //# Id of parent OrgUnit
"blockInheritance": false, //# Should block inheritance
"orgUnitId": orgUnitId, //# Id of OrgUnit
}
/* Call Rename Function */
Logger.log(customerId + ", " + orgUnitId + ", " + JSON.stringify(body))
renameOU(customerId, orgUnitId, body)
}
I expect the result of the OU to change from "/Users/200 COGS/Education" to "/Users/200 COGS/255 Education".
The output is a parse error though:
[19-06-17 17:39:39:165 PDT] /Users/200 COGS/Education
[19-06-17 17:39:39:166 PDT] my_customer, id:03ph8a2z39wdr3v, {"kind":"admin#directory#orgUnit","parentOrgUnitPath":"/Users/200 COGS","name":"255 Education","orgUnitPath":"/Users/200 COGS/255 Education","parentOrgUnitId":"id:03ph8a2z1lakohp","blockInheritance":false,"orgUnitId":"id:03ph8a2z39wdr3v"}
[19-06-17 17:39:39:166 PDT] my_customer, id:03ph8a2z39wdr3v, {"kind":"admin#directory#orgUnit","parentOrgUnitPath":"/Users/200 COGS","name":"255 Education","orgUnitPath":"/Users/200 COGS/255 Education","parentOrgUnitId":"id:03ph8a2z1lakohp","blockInheritance":false,"orgUnitId":"id:03ph8a2z39wdr3v"}
[19-06-17 17:39:39:198 PDT] {"message":"API call to directory.orgunits.update failed with error: Parse Error","name":"GoogleJsonResponseException","fileName":"GSuiteOrgUnits","lineNumber":573,"stack":"\tat GSuiteOrgUnits:573 (renameOU)\n\tat GSuiteOrgUnits:600 (test_renameOU)\n","details":{"message":"Parse Error","code":400,"errors":[{"domain":"global","reason":"parseError","message":"Parse Error"}]}}
If you use the patch endpoint you only need to pass in the fields you want to change:
AdminDirectory.Orgunits.patch({
name: 'New Name'
}, customerId, ouIdOrPath);
It worked for me. Do not pass the Unit Path org as it is automatically adjusted by the api based on the "name" field
var orgUnit = new OrgUnit()
{
Name = "new name",
Description = "new description"
};
var request = service.Orgunits.Patch(orgUnit, customerId, orgUnitPath);
request.Execute();
What is the simplest way to export data to CSV from Meteor?
How to generate CSV?
What I've tried
Add Npm package:
$ meteor add meteorhacks:npm
Add Node.js CSV suite:
// packages.json
{
"csv": "0.4.0",
}
Add Iron Router package:
$ meteor add iron:router
Configure router on server:
// server/router.coffee
Router.map ->
#route 'exportCSV',
where: 'server'
path: '/export-csv/:id'
onAfterAction: ->
data = ... // Generated CSV
filename = 'filename.csv'
headers =
'Content-type': 'text/csv'
'Content-Disposition': 'attachment; filename=' + filename
#response.writeHead 200, headers
#response.end file
For my use-case, all of the data was already published to the client. So I decided to generate the file there, using FileSaver.
Here's a basic class to build a csv by calling addRow(), then call download('xxx.csv') to have the user download the file.
class CsvBuilder
constructor: ->
#content = []
line: ->
row = [].slice.call(arguments)
if row.length == 0
#addBlankRow()
else
#addRow(row)
return
addRow: (row)->
#content.push(#row2Csv(row), "\n")
return
addBlankRow: ->
#content.push("", "\n")
return
row2Csv: (row)->
d = ''
for cell in row
d += '"' + (cell + "").replace(/"/g, '""') + '",'
return d
download: (filename)->
try
isFileSaverSupported = !!new FileSaver.Blob()
unless isFileSaverSupported
window.alert("Save as CSV not supported");
return
contentBlob = new FileSaver.Blob(#content, {type: "text/csv;charset=utf-8"})
FileSaver.saveAs(contentBlob, filename)
return
destroy: ->
#content = []
Using the FileSave.js from eligrey/Filesaver and save in lib folder in you client
'click .btnRawCSV' : function() {
var rawData = Gifts.find({
receiptdate:{
$gte: Session.get("giftsStartDate"),
$lte: Session.get("giftsEndDate")
}
}).fetch();
csv = json2csv( rawData, true, true );
var blob = new Blob([csv], {type: "text/plain;charset=utf-8;",});
saveAs(blob, "rawgifts.csv");
},