Java net url refused connection - javascript

I'm working with ARIS tool and I want to make calls(GET, POST...) in ARIS to ARIS API repository!
I have authentication that works when I try it directly in the repository, but I got an error when I debug the code I have in ARIS.
The error: Error running script: Connection refused: connect.
I have the following code:
var obj = new java.net.URL(url);
var con = obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", java.net.USER_AGENT);
var tenant = "";
var name = "";
var password = "";
var key = "";
var authString = tenant + ":" + name + ":" + password + ":" + key;
var encoder = new java.lang.String(Base64.encode(authString));
con.setRequestProperty("Authorization", "Basic" + encoder);
var responseCode = con.getResponseCode();
var iN = new java.io.BufferedReader(new java.io.InputStreamReader(con.getInputStream()));
var inputLine = new java.lang.String();
var response = new java.lang.StringBuffer();
while((inputLine = iN.readLine()) != null){
response.append(inputLine);
}
iN.close();
return new java.lang.String(response);
Is the problem that I use Basic authentication, but I have tenant and key also or it's something else?
Also, name, password, key and tenant I'm leaving empty for security purposes, but in the original code the values are inserted. Also the url parameter contains the url link that is called directly in the repository.
Can someone please help me?
Thanks!

Related

Azure IoT Hub device registration via POSTMAN results in Unauthorized

I want to create a sas token for registration of device in Azure IoT hub,using postman.The sas token will be created with pre-requested script.
var resourceUri = "scopeId/registrations/deviceId" // The resource uri
var deviceId = "deviceId";
resourceUri = encodeURIComponent(resourceUri.toLowerCase()); // Encode the url
var expires = Math.ceil((Date.now() / 1000) + 10 * 60); // Expire the token 60 minutes from now
var toSign = resourceUri + "\n" + expires; // this is the string format to gen signature from
var crypted = CryptoJS.HmacSHA256(deviceId, CryptoJS.enc.Base64.parse("symmetrickKeyOfEnrollmentGroup"));
var signature = CryptoJS.HmacSHA256(toSign, crypted); // The signature generated from the decodedKey
var encodedUri = encodeURIComponent(CryptoJS.enc.Base64.stringify(signature)); // The url encoded version of the Base64 signature
// Construct authorization string (shared access signature)
var iotHubSasToken = "SharedAccessSignature sr=" + resourceUri + "&sig=" + encodedUri + "&se=" + expires +"&skn=registration";
console.log(iotHubSasToken);
postman.setGlobalVariable("token", iotHubSasToken);
This is what i created, but i receive Unauthorized.Some ideas where i am wrong, i think i somewhere in the signature, because the "sr" and "se" are okay
Output of the code above which throws Unauthorized:
SharedAccessSignature sr=0ne002ee24e%2Fregistrations%2Fcxdlx3f3zv9xx3f3zq&sig=Ukz%2FPyyLaweLYmFq4gHUP%2BhiO7X%2FyQAE9noAaw4nuLU%3D&se=1659940252&skn=registration
References:
About SAS: https://learn.microsoft.com/en-us/azure/iot-dps/how-to-control-access
About the REST API: https://learn.microsoft.com/en-us/rest/api/iot-dps/device/runtime-registration/register-device#provisioningserviceerrordetails
About DPS sas token: https://learn.microsoft.com/en-us/azure/iot-dps/how-to-control-access
Error:
The issue was in the signature.
var crypted = CryptoJS.HmacSHA256(deviceId, CryptoJS.enc.Base64.parse("symmetrickKeyOfEnrollmentGroup"));
var signature = CryptoJS.HmacSHA256(toSign, crypted); // The signature generated from the decodedKey
var encodedUri = encodeURIComponent(CryptoJS.enc.Base64.stringify(signature)); // The url encoded version of the Base64 signature
This is the right way of creating it.

Cannot extract and import CSV from ZIP in website to Google Sheets (App Scripts) with Basic Auth

I'm trying to get a CSV that is zipped in a URL, which needs basic auth. I can't get to do it. I get a syntax error on 'files' argument. This is what I tried:
function importdatastreamcsv() {
var user = 'user';
var pw = 'pass';
var csvUrl = 'https://example.com/api/datastream/download/58350?tableIds=67595&usePreferences=false';
var csvContent = UrlFetchApp.fetch(csvUrl,{headers: {'Authorization': 'Basic ' + Utilities.base64Encode(user + ':' + pw, Utilities.Charset.UTF_8)}});
var files = Utilities.unzip(csvContent)[0]; //syntax error on the argument! :(
var csvData = Utilities.parseCsv(files.getDataAsString());
var sheet = SpreadsheetApp.getActiveSheet().getActiveCell();
sheet.setValues(csvData);
}
Looking for other alternatives, I noticed that is possible to pull the data in html table (not zip-csv format), so I wrote another script. It kind of worked, but all the information is in plain html and stored in only one cell, so it's almost impossible to read... here is the code:
function importdatastreamhtml() {
var user = 'user';
var pw = 'pass';
var csvUrl = 'https://example.com/api/datastream/download/58350?tableIds=67595&usePreferences=false&format=web';
var csvContent = UrlFetchApp.fetch(csvUrl,{headers: {'Authorization': 'Basic ' + Utilities.base64Encode(user + ':' + pw, Utilities.Charset.UTF_8)}});
var html = csvContent.getContentText();
var sheet = SpreadsheetApp.getActiveSheet().getRange(1, 1);
sheet.setValue(html);
}
I need to have at least one of these two running correctly. What can I be missing here?
The output should be a simple table.
Many thanks,
César

API call with Javascript

im currently trying to call on a API using "GET" method in javascipt, but i don't seem to get any access. This is the code.
loadLibrary("cus:json3.js");
try {
var buffer = new MemoryBuffer();
buffer.fromString("username" + ':' + "password", "utf-8");
var http = new HttpClientRequest();
http.header["Authorization"] = "Basic " + buffer.toBase64();
this.baseURL = "https://url...";
http.url = this.baseURL;
http.method = "GET";
http.execute();
logInfo();
var response = http.response;
}
} catch(e) {
logInfo(e);
}
But all i get is -55 error. Not sure why I can't access the API like this. Does anybody have an idea that would be awsome. The firewall has allowed the IP that my program is using.

Google script xls attachment not displaying

any thoughts as to why this script emails an attachment but the attachment is not the correct spreadsheet, and looks like some sort of google error page.
function getGoogleSpreadsheetAsExcel(){
try {
var ss = SpreadsheetApp.getActive();
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + ss.getId() + "&exportFormat=xlsx";
Logger.log(url);
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blob = UrlFetchApp.fetch(url, params).getBlob();
blob.setName(ss.getName() + ".xlsx");
MailApp.sendEmail("youremail#email.com", "Google Sheet to Excel", "The XLSX file is attached", {attachments: [blob]});
} catch (f) {
Logger.log(f.toString());
}
}
I guess API has changed. You can try Drive REST API(v3) instead. Replace
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + ss.getId() + "&exportFormat=xlsx";
var params = { ... };
var blob = UrlFetchApp.fetch(url, params).getBlob();
to
var url = "https://www.googleapis.com/drive/v3/files/" + ss.getId() +
"/export?mimeType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&key=" +
"{your API key}";
var blob = UrlFetchApp.fetch(url).getBlob();
I tested and it worked. Of course you first should get your own API key, etc, at API Manager. Then you can try some APIs like simple GET requests at APIs Explorer. Or you can try some APIs, in this case Files: export, also at the documentation page itself, but notice that you cannot try your own API key here.
This is the updated code that #sangbok helped with:
function getGoogleSpreadsheetAsExcel(){
try {
var ss = SpreadsheetApp.getActive();
var sheet = DriveApp.getFileById(ss.getId());
// sets sharing to public - to send out email.
sheet.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.EDIT);
var url = "https://www.googleapis.com/drive/v3/files/" + ss.getId() + "/export?mimeType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&key=" + "YOURAPIKEYGOESHERE4";
var blob = UrlFetchApp.fetch(url).getBlob();
Logger.log(url);
blob.setName(ss.getName() + ".xlsx");
var now = new Date();
MailApp.sendEmail("YOUREMAILADDRESSGOESHERE", "EMAIL SUBJECT " + now , "EMAIL BODY " + now , {attachments: [blob]});
} catch (f) {
Logger.log(f.toString());
}
// returns the file back to Private access
sheet.setSharing(DriveApp.Access.PRIVATE, DriveApp.Permission.EDIT);
}

Not able to load the response

var soapre1 = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:glob=\"http://sap.com/xi/SAPGlobal20/Global\">";
var soapre2 = "<soapenv:Header/><soapenv:Body><glob:EmployeeLeaveRequestByParticipantQuery><EmployeeLeaveRequestSelectionByParticipant><EmployeeLeaveRequestParticipantRoleCode listVersionID=\"?\">2</EmployeeLeaveRequestParticipantRoleCode>";
var soapre3 = "<!--Zero or more repetitions:--> <EmployeeLeaveRequestParticipantWorkAgreementIDInterval><IntervalBoundaryTypeCode>1</IntervalBoundaryTypeCode> <!--Optional:--> <LowerBoundaryWorkAgreementID schemeID=\"?\" schemeAgencyID=\"?\">1009</LowerBoundaryWorkAgreementID></EmployeeLeaveRequestParticipantWorkAgreementIDInterval>";
var soapre4 = " <!--Zero or more repetitions:--> </EmployeeLeaveRequestSelectionByParticipant></glob:EmployeeLeaveRequestByParticipantQuery> </soapenv:Body></soapenv:Envelope>";
var soapRequest = soapre1+soapre2+soapre3+soapre4;
var authstr = 'Basic ' +Titanium.Utils.base64encode('S0009231839'+':'+ 'm8390967743!');
var soapxhr = Ti.Network.createHTTPClient();
soapxhr.setRequestHeader('SOAPAction',soapRequest);
soapxhr.open("POST","http://erp.esworkplace.sap.com/sap/bc/srt/pm/sap/ecc_empleavereqparctqr/800/default_profile/2/binding_t_http_a_http_ecc_empleavereqparctqr_default_profile");
soapxhr.setRequestHeader('Authorization', authstr);
soapxhr.setRequestHeader('Content-Type','text/xml','charset=utf-8');
soapxhr.send();
soapxhr.onload = function(e)
{
Ti.API.info('abcd');
//get the xml data and let it roll!
var doc = this.responseXML;
Ti.API.info(doc);
}
soapxhr.onerror = function (e){
alert('Error');
Ti.API.info(e);
}
Unable to load the response Its directly getting error
[INFO] {
source = "[object TiNetworkClient]";
type = error;
}
Any one advice how to fix the issue!
# Thanks in advance
In all browser its saying error! but i found some wsdl and soap request so in order to open the response i need to pass the method name to the http request ! then it working

Categories