Problem with chilkat ActiveX HTTP component with Redirect - chilkat

I used this script to check the last redirect url:
set http = CreateObject("Chilkat_9_5_0.Http")
http.FollowRedirects = 0
' resp is a Chilkat_9_5_0.HttpResponse
Set resp = http.QuickGetObj(link)
If (http.LastMethodSuccess = 0) Then
wscript.echo http.LastErrorText
WScript.Quit
End If
status = resp.StatusCode
wscript.echo "HTTP Response Status: " & status
wscript.echo "Redirect URL >>>: " & http.FinalRedirectUrl
nextUrl = http.WasRedirected
loopCount = 0
Do While (status = 302 OR status = 301)
wscript.echo "HTTP Response Status: " & status
wscript.echo "Redirect URL >>>: " & http.FinalRedirectUrl
nextUrl = http.FinalRedirectUrl
' resp is a Chilkat_9_5_0.HttpResponse
Set resp = http.QuickGetObj(nextUrl)
If (http.LastMethodSuccess = 0) Then
wscript.echo http.LastErrorText
WScript.Quit
End If
status = resp.StatusCode
wscript.echo "HTTP Response Status: " & status
' For safety, prevent infinite loops by
' keeping a loopCount and only allows following a max
' of 10 redirects:
loopCount = loopCount + 1
If (loopCount > 10) Then
wscript.echo "Too many redirects."
WScript.Quit
End If
Loop
This code prints the 301 status code correctly, but it doesn't print the http.FinalRedirectURL (it's blank).
I also tried with the url https://www.businessonline.it/articoli/guida-al-nuovo-regime-forfettario-2016-e-2017.html
The output is:
Link: https://www.businessonline.it/articoli/guida-al-nuovo-regime-forfettario-2016-e-2017.html
HTTP Response Status: 301
Redirect URL >>>:
HTTP Response Status: 301
Redirect URL >>>:
ChilkatLog:
QuickGetObj:
DllDate: Oct 28 2019
ChilkatVersion: 9.5.0.80
UnlockPrefix: BRKEVN.XXXXXXXXXXX
Architecture: Little Endian; 32-bit
Language: ActiveX
VerboseLogging: 0
Component successfully unlocked using purchased unlock code.
url:
verb: GET
quickRequestDb:
url:
getHttpConnectionByUrl:
urlObject_loadUrl:
No domain in URL
url:
--urlObject_loadUrl
--getHttpConnectionByUrl
--quickRequestDb
Failed.
--QuickGetObj
--ChilkatLog
I used both chilkat 9.5.0.70 and 9.5.0.80.
If I set FollowRedirects to 1, the first StatusCode is "200" and I can't get the url.
Can you help me?
Thank's

Thanks Lorenzo,
The problem had to do with QuickGetObj and QuickGet. The QuickGetStr method worked fine for the WasRedirected and FinalRedirectUrl properties.
Here's a new 32-bit ActiveX build with the fix:
32-bit: https://chilkatdownload.com/prerelease/chilkatax-9.5.0-win32-1630.zip

Related

520 Error everytime I run my code behind Cloudflare

I keep getting a 520 error when trying to load s3 files via my code. It all works fine locally but when I upload the changes to my production server which is behind cloudflare I get a 520 error. Im using IIS 7.5 with asp classic code, here is my test page which is call everytime I want to download a file from s3.
https://www.gbca.org.au/aws_test.asp?fileID=9450&hash=688254C6503507FDDF8CF5D5CD113212&type=pam
It doesnt make sense and cloudflare doesnt provide any error messages.
' #########################################
function downloadFile()
Server.ScriptTimeout = 30000
set http = Server.CreateObject("Chilkat_9_5_0.Http")
http.UnlockComponent("BLUESIHttp_MHoP0vyTTL3e")
http.AwsAccessKey = AWS_ACCESS_KEY
http.AwsSecretKey = AWS_SECRET
if bucketType = "not-secure" then
http.AwsEndpoint = "s3.ap-southeast-1.amazonaws.com"
http.AwsRegion = "ap-southeast-1"
bucketLocale = AWS_BUCKET_ASIA
else
http.AwsEndpoint = "s3.ap-southeast-2.amazonaws.com"
http.AwsRegion = "ap-southeast-2"
bucketLocale = AWS_BUCKET_SECURE
end if
s3FileBytes = http.S3_DownloadBytes(bucketLocale, objectName)
If (http.LastMethodSuccess <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode(http.LastErrorText) & "</pre>"
Response.End
End If
'response.write("AWS_BUCKET_ASIA: " & AWS_BUCKET_ASIA & "<br />")
'response.write("objectName: " & objectName& "<br />")
'response.write("s3FileBytes: " & ubound(s3FileBytes) & "<br />")
''response.write("s3FileBytes: " & filetype & "<br />")
''response.end()
Response.Clear
Response.AddHeader "Pragma", "no-cache"
Response.AddHeader "Content-Disposition", "attachment; filename=""" & filename & """"
Response.AddHeader "Content-Length", ubound(s3FileBytes)
Response.AddHeader "Connect", "close"
Response.ContentType = filetype
Response.BinaryWrite s3FileBytes
set AWS = nothing
'-- log the file access
'SQLLine = "INSERT INTO download_history (fileID, who, etc) VALUES (" & fileID & ")"
'DBCC.execute(SQLLine)
end function
https://www.gbca.org.au/aws_test.asp?fileID=9450&hash=688254C6503507FDDF8CF5D5CD113212&type=pam
Error 520 is essentially a catch-all response when something unexpected happens or when the origin server incorrectly interprets or does not tolerate a request due to a protocol violation or an empty response.
Besides reviewing your server logs, I recommend contacting Cloudflare support to review logs on their end as well. Unless you're on Enterprise Plan and explicitly requested to enable 100% logs, keep in mind they only keep 1% anonymized sampled logs for a limited time, so the logs might not be available if you contact them too late.
I've seen cases where nginx error upstream prematurely closed connection while reading response header from upstream was observed, upstream in this case means the origin server. This indicates that the origin server or the path along which it travelled was having issues during this period which caused Cloudflare to generate those 520 errors. Correlating the timestamp with your server's logs will give you better picture as to what the root cause could possibly be.

Consume secured Web service in Classic ASP

I am new to ASP classic and IIS. I have been given task to call a Web Service from Classic ASP. I have achieved that. The code I have written is as follows :
<%
On Error Resume Next
Dim oRequest
Set oRequest = Server.CreateObject("Microsoft.XMLHTTP")
' HTTP URL
msURL = "http://10.6.10.65:8080/myweb/hello"
'HTTPS URL
'msURL = "https://10.6.10.65:8443/myweb/hello"
msSOAP = "<?xml version=""1.0"" ?>"
msSOAP = msSOAP & "<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:ws=""http://ws.mkyong.com/"">"
msSOAP = msSOAP & " <soapenv:Header/>"
msSOAP = msSOAP & " <soapenv:Body>"
msSOAP = msSOAP & " <ws:getHelloWorldAsString/>"
msSOAP = msSOAP & " </soapenv:Body>"
msSOAP = msSOAP & "</soapenv:Envelope>"
oRequest.Open "POST", msURL, False
oRequest.setRequestHeader "Content-Type", "text/xml"
oRequest.send msSOAP
Response.Clear
Response.BinaryWrite oRequest.responseBody
if err.number <> 0 then
response.write "Error detected: " & err.number & ": " & err.Description & ""
Response.end
end if
on error goto 0
%>
This is a simple Hello World web service.
The code works fine with http protocol to web service ("http://10.6.10.65:8080/myweb/hello") but When I change url of my web service to https ("https://10.6.10.65:8443/myweb/hello") I get follwing:
Error detected: -2147352571: 007~ASP 0106~Type Mismatch~An unhandled data type was encountered.
This is very vague error.. but I sense that I need to do something to get this work.
The web service is on tomcat on different pc in network. I am having IIS 7.5 on windows server 2008.
Please assist to get this work... I am in little mess
Thank you
Try
oRequest.setOption 2, 13056
after creating the object

groovyx.net.http.ResponseParseException while invoking web service from Spock groovy. Works fine from Postman or other clients

I want to consume a webservice and add assertions to its response. I get the following exception:
groovyx.net.http.ResponseParseException:
at groovyx.net.http.HTTPBuilder$1.handleResponse(HTTPBuilder.java:495)
......
at Subscription.Order Products(Subscription.groovy:14)
Caused by: groovy.json.JsonException: Unable to determine the current character, it is not a string, number, array, or object
The current character read is 'I' with an int value of 73
Unable to determine the current character, it is not a string, number, array, or object
line number 1
index number 0
Invalid UTF-8 middle byte 0x52
My operation is as follows:
def setupSpec() {
client = new RESTClient("http://tsi-services-dev2.canaldigital.com:9080/test/webgw-dealer/v1/");
client.handler.failure = { resp, data -> return resp }
}
///// orderProductPayload is a variable which has an input
def "Order Products"() {
when:
def resp = client.post(path: "order/orderProduct", requestContentType: JSON, contentType: JSON, body: orderProductPayload) as HttpResponseDecorator
then:
println("response: " + resp.data)
resp.status == successResponseStatus
}
I have other such tests too which work fine and this particular test with the input payload entered works fine from Postman
Here is my response headers for this operation which fails in spock/groovy:
Content-Length →159
Content-Type →application/json
Date →Wed, 05 Apr 2017 06:19:16 GMT
X-Correlation-ID → xxxxx
Response header for another opertion which is working:
Connection →close
Content-Length →273
Content-Type →application/json
Date →Wed, 05 Apr 2017 06:16:41 GMT
X-Correlation-ID → xxxxx
Thanks alot for the help turns out there was a special character such as Ø in my request which the service didnt like and hence was responding in such an absurd way. Works fine now

rails 4 flash not persisting across redirect "ActionDispatch::Request::Session -- not yet loaded"

I am having a weird issue where a flash message is not persisting across redirects in a Rails 4.0.2 application. I suspect that the problem has something to do with the session not yet being loaded when I try to access the flash hash as I am logging the session and getting the following output:
#<ActionDispatch::Request::Session:0x7ffda10835a8 not yet loaded>
I am trying to update an asset in the 'assets_controller' and then redirect to the 'home' action of the 'dashboard_controller' if the asset was successfully updated. My code is as follows:
AssetsController:
def update
#asset = Asset.update_asset(asset_parameters, params[:id])
if #asset.errors.any?
flash.now[:error] = "There were some errors"
render 'edit'
else
flash[:success] = "Asset updated!"
logger.debug("flash in assets: #{flash.inspect}")
redirect_to root_path()
end
end
DashboardController:
def home
logger.debug("session #{session.inspect}")
logger.debug("flash in home #{flash.inspect}")
res = Bid.bids_query({:generation => 'current'})
#bids = []
#staging_jobs = []
res.each do |bid|
bid.staging_job_id ? #staging_jobs << bid : #bids << bid
end
end
Log Output:
Started PATCH "/assets/19" for 127.0.0.1 at 2014-03-16 21:45:53 -0700
Processing by AssetsController#update as HTML
flash in assets: #<ActionDispatch::Flash::FlashHash:0x007ff7abdcfc30 #discard=#<Set:
{}>, #flashes={:success=>"Asset updated!"}, #now=nil>
Redirected by /Users/louism2/rails_projects/rosebank-
b/app/controllers/assets_controller.rb:31:in `update'
Redirected to http://localhost:3000/
Completed 302 Found in 14ms (ActiveRecord: 2.4ms)
Started GET "/" for 127.0.0.1 at 2014-03-16 21:45:53 -0700
Processing by DashboardController#home as HTML
session #<ActionDispatch::Request::Session:0x7ffda10835a8 not yet loaded>
flash in home #<ActionDispatch::Flash::FlashHash:0x007ff7abe743e8 #discard=#<Set: {}>,
#flashes={}, #now=nil>
Completed 200 OK in 81ms (Views: 53.7ms | ActiveRecord: 2.6ms)
The issue had to do with the fact that my model was named "assets" and that was somehow conflicting with the asset pipeline. The trick was to prefix the asset pipeline with an identifier other than assets which you can specify in your application.rb file with the following line:
config.assets.prefix = '/new_name_for_asset_pipeline'

Windows Script to Parse names of WebSphere JVMs from a command output

I am writing a (batch file or VBScript) to nicely shutdown all the running WebSphere JVMs on a Windows server, but need help with some text handling. I want the script to run and parse the output of the "serverstatus" command to get the names of Application Servers on the box and store the matches (with carriage returns) in a variable for use in the rest of the script.
Sample command output:
C:\WebSphere\AppServer\bin>serverstatus -all
ADMU0116I: Tool information is being logged in file
C:\WebSphere\AppServer\profiles\MySrv01\logs\serverStatus.log
ADMU0128I: Starting tool with the MySrv01 profile
ADMU0503I: Retrieving server status for all servers
ADMU0505I: Servers found in configuration:
ADMU0506I: Server name: MyCluster_MySrv01
ADMU0506I: Server name: MyCluster_MySrv01_1
ADMU0506I: Server name: MyNextCluster_MySrv04
ADMU0506I: Server name: MyNextCluster_MySrv04_1
ADMU0506I: Server name: nodeagent
ADMU0508I: The Application Server "MyCluster_MySrv01" is STARTED
ADMU0508I: The Application Server "MyCluster_MySrv01_1" is STARTED
ADMU0508I: The Application Server "MyNextCluster_MySrv04" is STARTED
ADMU0509I: The Application Server "MyNextCluster_MySrv04_1" cannot be
reached. It appears to be stopped.
ADMU0508I: The Node Agent "nodeagent" is STARTED
*nodeagent should NOT match. The jury is still out on whether I want to target all app servers or just those with a status of "STARTED".
Here's an alternative to using Regex. It simply reads stdout and processes all started app servers - the app servers are stored in an array called AppServers. Tested on W2K3.
Edit: We have added a way to log output to a file by adding a log write function (don't forget to add the const ForAppending at the start of the script that we have just added to this answer). The log write function takes the format of:
Logwrite "some text to write - delete file if exists", "c:\Path\filename.txt", 1
Logwrite "some text to write - append to file, don't delete", "c:\path\filename.txt", 0
It is a crude function, but does what you ask. I hope that helps. :)
option explicit
Const ForAppending = 8
Dim objShell, objWshScriptExec, objStdOut
Dim objCmdString, strLine, appServers(), maxAppServers
Dim x
' File Path / Location to serverstatus.bat ----
objCmdString = "C:\WebSphere\AppServer\bin\serverstatus.bat -all"
Set objShell = CreateObject("WScript.Shell")
Set objWshScriptExec = objShell.Exec(objCmdString)
Set objStdOut = objWshScriptExec.StdOut
MaxAppServers = -1
' While we're looping through the response from the serverstatus command, look for started application servers
' and store them in an ever expanding array AppServers.
' The Variable MaxAppServers should always contain the highest number of AppServers (ie: ubound(AppServers))
While Not objStdOut.AtEndOfStream
strLine = objStdOut.ReadLine
If InStr(LCase(strLine), "admu0508i: the application server """) Then
MaxAppServers = MaxAppServers + 1
ReDim Preserve AppServers(MaxAppServers)
AppServers(MaxAppServers) = wedge(strLine, Chr(34))
End If
Wend
If MaxAppServers => 0 then
For x = 0 To ubound(AppServers) ' You could just use For x = 1 to MaxAppServers in this case.
' Add your instructions here.........
' ... We are simply echoing out the AppServer name below as an example to a log file as requested below.
Logwrite AppServers(x), "c:\Output.log", 0
Next
End If
Function Wedge(wStr, wOpr)
' This clunky function simply grabs a section of a string the is encapsulated by wOpr.
' NOTE: This function expects wOpr to be a single character (eg; for our purpose, it is pulling data between double quotes).
Dim wFlag, wCount, wFinish
wflag = False
wFinish = False
wCount = 1
Wedge = ""
Do Until wCount > Len(wStr) Or wFinish
If Mid(wStr, wCount, 1) = wOpr Then
If wFlag Then
wFinish = True
Else
wFlag = True
End If
Else
If wFlag Then Wedge = Wedge & Mid(wStr, wCount, 1)
End If
wCount = wCount + 1
Loop
End Function
Function logwrite (lstrtxt, lwLogfile, lwflag)
Dim lwObjFSO, lwObjFile, fstr, lwcounter, lwc
fstr = lstrtxt
Set lwObjFSO = CreateObject("Scripting.FileSystemObject")
If lwflag=1 And lwObjFSO.FileExists(lwLogFile) Then lwObjfso.deletefile(lwLogFile)
If lwObjFSO.FileExists(lwLogFile) then
On Error Resume next
Set lwObjFile = lwObjFSO.OpenTextFile(lwLOgFile, ForAppending)
lwCounter = 20000
Do While Err.number = 70 And lwCounter > 0
wscript.echo "ERROR: Retrying output - Permission denied; File may be in use!"
For lwc = 1 To 1000000
Next
Err.clear
Set lwObjFile = lwObjFSO.OpenTextFile(lwLogFile, ForAppending)
lwCounter = lwCounter-1
Loop
If Err.number <> 0 Then
wscript.echo "Error Number: "&Err.number
wscript.quit
End If
On Error goto 0
Else
Set lwObjFile = lwObjFSO.CreateTextFile(lwLogFile)
End If
wscript.echo (fstr)
lwObjFile.Write (fstr) & vbcrlf
lwObjFile.Close
Set lwObjFSO=Nothing
Set lwObjfile=Nothing
End Function
Use a RegExp that cuts quoted names from your input; add context - Server, Started - to fine tune the result set. In code:
Option Explicit
Function q(s) : q = "'" & s & "'" : End Function
Dim sInp : sInp = Join(Array( _
"ADMU0116I: Tool information is being logged in file C:\WebSphere\AppServer\profiles\MySrv01\logs\serverStatus.log" _
, "ADMU0128I: Starting tool with the MySrv01 profile" _
, "ADMU0503I: Retrieving server status for all servers" _
, "ADMU0505I: Servers found in configuration:" _
, "ADMU0506I: Server name: MyCluster_MySrv01" _
, "ADMU0506I: Server name: MyCluster_MySrv01_1" _
, "ADMU0506I: Server name: MyNextCluster_MySrv04" _
, "ADMU0506I: Server name: MyNextCluster_MySrv04_1" _
, "ADMU0506I: Server name: nodeagent" _
, "ADMU0508I: The Application Server ""MyCluster_MySrv01"" is STARTED" _
, "ADMU0508I: The Application Server ""MyCluster_MySrv01_1"" is STARTED" _
, "ADMU0508I: The Application Server ""MyNextCluster_MySrv04"" is STARTED" _
, "ADMU0509I: The Application Server ""MyNextCluster_MySrv04_1"" cannot be reached. It appears to be stopped." _
, "ADMU0508I: The Node Agent ""nodeagent"" is STARTED" _
), vbCrLf)
Dim aRes : aRes = Array( _
Array("all quoted names", """([^""]+)""") _
, Array("all quoted started servers", "Server ""([^""]+)"" is STARTED") _
)
Dim aRE
For Each aRe In aRes
WScript.Echo "----------------", q(aRe(0)), q(aRe(1))
Dim re : Set re = New RegExp
re.Global = True
re.Pattern = aRe(1)
Dim oMTS : Set oMTS = re.Execute(sInp)
ReDim a(oMTS.Count - 1)
Dim i
For i = 0 To UBound(a)
a(i) = q(oMTS(i).SubMatches(0))
Next
WScript.Echo " =>", Join(a)
Next
output:
cscript 20984738.vbs
---------------- 'all quoted names' '"([^"]+)"'
=> 'MyCluster_MySrv01' 'MyCluster_MySrv01_1' 'MyNextCluster_MySrv04' 'MyNextCluster_MySrv04_1' 'nodeagent'
---------------- 'all quoted started servers' 'Server "([^"]+)" is STARTED'
=> 'MyCluster_MySrv01' 'MyCluster_MySrv01_1' 'MyNextCluster_MySrv04'