Problematic
I want to update html files before packagind in war to set an HASH variable corresponding to a JS bundle compilation.
Here is what I have
<script th:src="#{/static/js/assistance/manifest.js}" charset="UTF-8"></script>
Here is what I want at the end of the process
<script th:src="#{/static/js/assistance/manifest.hereIsTheHash.js}" charset="UTF-8"></script>
The hash is generated after the JS compilation which is a gradle task (see below) and is stored in a json file created after the compilation.
What I've tried (after a thousand of another try)
In order to update all my HTML files with a reference to my JS with HASH, I've tried this :
war{
dependsOn 'createStatsJson'
filesMatching('WEB-INF/views/**.html'){
filter { String line ->
line = line.replaceAll('assistance.js', ext.assistanceJs)
line = line.replaceAll('manifest.js', ext.manifestJs)
line = line.replaceAll('vendor.js', ext.vendorJs)
}
}
}
If I replace ext.assistanceJs, ext.manifestJs or ext.vendorJs by a string, it works perfectly.
These variables are defined in another task which read a json file :
task createStatsJson(dependsOn: 'buildAssistanceJS') {
def jsonFile = file('build/webpack/assistance/stats.json')
def parsedJson = new groovy.json.JsonSlurper().parseText(jsonFile.text)
ext.assistanceJs = parsedJson.assetsByChunkName.assistance[0]
ext.manifestJs = parsedJson.assetsByChunkName.manifest
ext.vendorJs = parsedJson.assetsByChunkName.vendor
}
This json file is created by another task :
task buildAssistanceJS(dependsOn: 'gulp_less', type: NpmTask) {
args = ['--prefix', 'src/main/javascript/assistance', 'run', 'build']
}
Problem
Unfortunately, it don't works as gradle tels me that the json file does not exists. I supposed it's an build lifecycle related problem but I don't know how to achive this.
Any help is greatly appreciated.
task createStatsJson(dependsOn: 'buildAssistanceJS') {
def jsonFile = file('build/webpack/assistance/stats.json')
def parsedJson = new groovy.json.JsonSlurper().parseText(jsonFile.text)
ext.assistanceJs = parsedJson.assetsByChunkName.assistance[0]
ext.manifestJs = parsedJson.assetsByChunkName.manifest
ext.vendorJs = parsedJson.assetsByChunkName.vendor
}
This is a configuration closure of the createStatsJson task, not the execution phase.
See Gradle build lifecycle for more information.
Essentially, when that piece of code executes - there is still no build/.../stats.json (unless it's there from a previous build and you're not using the clean task).
You need to change this task to
task createStatsJson(dependsOn: 'buildAssistanceJS') {
doLast {
def jsonFile = file('build/webpack/assistance/stats.json')
def parsedJson = new groovy.json.JsonSlurper().parseText(jsonFile.text)
ext.assistanceJs = parsedJson.assetsByChunkName.assistance[0]
ext.manifestJs = parsedJson.assetsByChunkName.manifest
ext.vendorJs = parsedJson.assetsByChunkName.vendor
}
}
This will provide values in the ex.* variables in the execution phase.
I assume that createStatsJson has an explicit dependency on the relevant build tasks so that the stats.json (buildAssistanceJS I guess) file will be present when executed.
Your war task code suffers from the same problem. the code runs in the configuration phase, not the execution phase.
war{
dependsOn 'createStatsJson'
doLast {
filesMatching('WEB-INF/views/**.html'){
filter { String line ->
line = line.replaceAll('assistance.js', ext.assistanceJs)
line = line.replaceAll('manifest.js', ext.manifestJs)
line = line.replaceAll('vendor.js', ext.vendorJs)
}
}
}
}
Finally found a working solution. Hope it will help.
task buildAssistanceJS(dependsOn: 'gulp_less', type: NpmTask) {
args = ['--prefix', 'src/main/javascript/assistance', 'run', 'build']
}
def assistanceJs = ""
def manifestJs = ""
def vendorJs = ""
task createStatsJson(dependsOn: 'buildAssistanceJS') {
doLast {
def jsonFile = file('build/webpack/assistance/stats.json')
def parsedJson = new groovy.json.JsonSlurper().parseText(jsonFile.text)
assistanceJs = parsedJson.assetsByChunkName.assistance[0]
manifestJs = parsedJson.assetsByChunkName.manifest
vendorJs = parsedJson.assetsByChunkName.vendor
}
}
war {
dependsOn 'createStatsJson'
filesMatching('WEB-INF/views/**.html'){ fichier ->
fichier.filter { String line ->
line = line.replaceAll('assistance.js', assistanceJs)
line = line.replaceAll('manifest.js', manifestJs)
line = line.replaceAll('vendor.js', vendorJs)
}
}
}
Related
I am trying to create a function in Groovy that inputs a string and returns a modified string. The problem I believe is within an addon, which is a specific software environment I am working with i.e. logic.script.Microblock. The error message I am receiving is:
No signature of method: com.controlj.addonsupport.logic.script.Microblock.capAbbreviate() is applicable for argument types: (java.lang.String) values: [OAT Dewpoint bavo].
I have tried dispName = capAbbreviate(dispName.toString()), dispName = capAbbreviate(dispName), and capAbbreviate(dispName).
The software environment is using some sort of addon. I am still fairly new to Groovy/Java so this seems like it could be something simple but it's not clicking in my head just yet.
The code simplified below is:
def exceptions = ['Ac':'AC','Oat':'OAT','Vav':'VAV']
def exceptionNonAlpha = '(?=[^a-zA-Z])'
def dispName
def capAbbreviate(String mbText)
{
// Iterates through 'exceptions' map and finds abbreviations and recapitalizes them
for (hvacName in exceptions.keySet()) {
mbText = mbText.replaceAll(hvacName + exceptionNonAlpha, exceptions[hvacName])
}
return mbText
}
logic.microblocks
{
dispName = prop.'display name'
dispName = capAbbreviate(dispName.toString()) // also tried capAbbreviate(dispName)
println dispName
}
The solution has two parts:
Similar to what #AndrejIstomin mentioned, removing the def to make a list or variable global resolved one part of the issue
The second part to the solution is that this. needed to be used to call the method. i.e. this.capAbbreviate(dispName)
If my scenarios got failed the JSON report not generating. But for passes scenarios I can able to see the JSON report.
Please find my config file as below.
In comment prompt console I can able to see the failure message:
W/launcher - Ignoring uncaught error AssertionError: expected false to equal true
E/launcher - BUG: launcher exited with 1 tasks remaining
You can save the report by using a hook, so don't generate the file form the protractor.conf.js file, but use a cucumber-hook for it.
The hook can look like this
reportHook.js:
const cucumber = require('cucumber');
const jsonFormatter = cucumber.Listener.JsonFormatter();
const fs = require('fs-extra');
const jsonFile = require('jsonfile');
const path = require('path');
const projectRoot = process.cwd();
module.exports = function reportHook() {
this.registerListener(jsonFormatter);
/**
* Generate and save the report json files
*/
jsonFormatter.log = function(report) {
const jsonReport = JSON.parse(report);
// Generate a featurename without spaces, we're gonna use it later
const featureName = jsonReport[0].name.replace(/\s+/g, '_').replace(/\W/g, '').toLowerCase();
// Here I defined a base path to which the jsons are written to
const snapshotPath = path.join(projectRoot, '.tmp/json-output');
// Think about a name for the json file. I now added a featurename (each feature
// will output a file) and a timestamp (if you use multiple browsers each browser
// execute each feature file and generate a report)
const filePath = path.join(snapshotPath, `report.${featureName}.${new Date}.json`);
// Create the path if it doesn't exists
fs.ensureDirSync(snapshotPath);
// Save the json file
jsonFile.writeFileSync(filePath, jsonReport, {
spaces: 2
});
};
}
You can save this code to the file reportHook.js and then add it to the cucumberOpts:.require so it will look like this in your code
cucumberOpts: {
require: [
'../step_definitions/*.json',
'../setup/hooks.js',
'../setup/reportHook.js'
],
....
}
Even with failed steps / scenario's it should generate the report file.
Hope it helps
I want to define a different logger from the default to log things in a different file. I've try to define a custom logger. The file is created but grails never logs anything.
appender("APPENDER", FileAppender) {
file = "logs/info.log"
append = true
encoder(PatternLayoutEncoder) {
pattern = "%level - %msg%n"
}
}
logger("logger", INFO, ['APPENDER'], false)
Then in a controller I want to call it using: log.info "something" but nothing is written.
This contains daily rolling policy and max size of the log file. The catch is /var/logs should have a write access.
def currentDay = timestamp("yyyyMMdd")
appender(FILE, RollingFileAppender) {
file = "/var/logs/info_${currentDay}.log"
rollingPolicy(FixedWindowRollingPolicy) {
fileNamePattern = "/var/logs/info_${currentDay}.%i.log"
minIndex = 1
maxIndex = 9
}
triggeringPolicy(SizeBasedTriggeringPolicy) {
maxFileSize = "50MB"
}
encoder(PatternLayoutEncoder) {
pattern = "%level %date %logger - %msg%n"
}
append = true
}
Note: your user should have a write access to /var/logs/
Add: import static ch.qos.logback.classic.Level.INFO
Where: conf/logback.groovy file
Thanks "nayan kakati" I've figured out earlier!
According to boto3 documentation here: https://boto3.readthedocs.org/en/latest/reference/services/iot-data.html#client the update_thing_shadow method takes the thingName & JSON payload as parameters. Currently it reads:
client = boto3.client('iot-data', region_name='us-east-1')
data = {"state" : { "desired" : { "switch" : "on" }}}
mypayload = json.dumps(data)
response = client.update_thing_shadow(
thingName = 'MyDevice',
payload = b'mypayload'
)
When I use the command line there's no problem but can't seem to get it right from within the lamba function. I've called it with numerous versions of code (json.JSONEncoder, bytearray(), etc..) without any luck. The errors range from syntax to (ForbiddenException) when calling the UpdateThingShadow operation: Bad Request: ClientError. Has anyone had success calling this or a similar method from within a AWS lambda function? Thanks.
This code is working fine for me:
def set_thing_state(thingName, state):
# Change topic, qos and payload
payload = json.dumps({'state': { 'desired': { 'property': state } }})
logger.info("IOT update, thingName:"+thingName+", payload:"+payload)
#payload = {'state': { 'desired': { 'property': state } }}
response = client.update_thing_shadow(
thingName = thingName,
payload = payload
)
logger.info("IOT response: " + str(response))
logger.info("Body:"+response['payload'].read())
def get_thing_state(thingName):
response = client.get_thing_shadow(thingName=thingName)
streamingBody = response["payload"]
jsonState = json.loads(streamingBody.read())
print jsonState
#print jsonState["state"]["reported"]
Good luck
garnaat is right.
Just replace payload = b'mypayload' with payload = mypayload and it should work.
I have got a file downloaded from AWS S3 to my NSTemporaryDirectory using this code:
let downloadFilePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent("FILENAME")
let downloadingFileURL = NSURL(fileURLWithPath:downloadFilePath)
let downloadRequest: AWSS3TransferManagerDownloadRequest = AWSS3TransferManagerDownloadRequest();
downloadRequest.bucket = "Bucketname";
downloadRequest.key = "FileName";
downloadRequest.downloadingFileURL = downloadingFileURL;
The file = .json file
the apps content is all saved on the JSON file, therefore i need to redirect the file from the NSTemporaryDirectory in order for the content to appear on the application.
Does anyone know the parse function in order to load the data from my JSON file into the application?
Thank you
You cannot modify the main bundle, so this isn't going to work.
There are a few directories under your control, for example the home directory, the application support directory, cache directories, or possibly the document directory.
As gnasher729 notes, you can't modify the main bundle itself, but there's no reason to here. You don't need to move the file in order to display it. You can read from your temporary directory. It's inside your application sandbox, and there's nothing special about it (it doesn't even get cleaned up for you either, so that's your responsibility if you need that).
The temp directory isn't backed up, so if you want that, you should move this to your documents directory. See NSFileManager moveItemAtPath:toPath:error: if you want to do that (or just download to your documents directory in the first place).
I figured it out.
So after downloading the File:
let downloadFilePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent("FILENAME")
let downloadingFileURL = NSURL(fileURLWithPath:downloadFilePath)
let downloadRequest: AWSS3TransferManagerDownloadRequest = AWSS3TransferManagerDownloadRequest();
downloadRequest.bucket = "Bucketname";
downloadRequest.key = "FileName";
downloadRequest.downloadingFileURL = downloadingFileURL;
i have to submit the download request - as seen below:
// submit download request
let transferManager: AWSS3TransferManager = AWSS3TransferManager.defaultS3TransferManager();
print("Downloading started, please wait...");
transferManager.download(downloadRequest).continueWithExecutor(AWSExecutor.defaultExecutor(), block: { (task) -> AnyObject? in
print("TASK:::::: \(task)");
if (task.error != nil){
print("Error Downloading");
}else{
self.readFile()
print("Download complete");
}
return nil;
}, cancellationToken: nil)
}
create a function that will parse your JSON file through the temp directory, using AlamoFire and SwiftyJSON:
func readFile() {
// JSON parsing step (from temporary directory)
let path = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent("FILENAME")
do {
let readFile:NSString? = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
let json = JSON.parse(readFile as String!)
for (_, subJson) in json["FILECONTENT"] {
let version = subJson["FILECONTENT"].string
let newsletter = Edition(Version: version!)
self.editions.append(ARRAYNAME!)
}
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
//print(readFile)
} catch {
}
}
this will showcase the text on your application when ran.
I am trying to get the images to do the something now.