Connection request failed while connecting to sharepoint online - sharepoint

I am trying to connect sharepoint online i used the following code but the response it is showing is request failed . I tried the following code
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0-RC2' )
import groovyx.net.http.*;
import static groovyx.net.http.ContentType.*;
import static groovyx.net.http.Method.*;
import groovyx.net.http.HTTPBuilder;
import static groovyx.net.http.Method.GET;
import static groovyx.net.http.ContentType.TEXT;
import groovyx.net.http.RESTClient
import groovy.util.slurpersupport.GPathResult
import static groovyx.net.http.ContentType.URLENC
import groovyx.net.http.URIBuilder
def authSite = new HTTPBuilder( 'https://xyzsharepoint.com' );
authSite.auth.basic 'username', 'password';
authSite.request(GET) { req->
response.success = { resp->
println'request was successful'
assert resp.status<400
}
response.failure = { resp ->
println'request failed'
assert resp.status>=400
}
}
Suggest me where I went wrong.

Related

List a sharepoint folder using python office365 containing more than 5000 files

from office365.runtime.auth.client_credential import ClientCredential
from office365.runtime.client_request_exception import ClientRequestException
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File
import io
import datetime
import pandas as pd
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File
import io
import datetime
import pandas as pd
app_principal = {
'client_id': 'xxxxxxxxxxxxxxxxxxxxxxx',
'client_secret': 'xxxxxxxxxxxxxxxxxxxxxxx'
}
sp_site = 'https://<domain>.sharepoint.com/sites/TSM839/'
relative_url = "/sites/TSM839/Shared Documents"
client_credentials = ClientCredential(app_principal['client_id'], app_principal['client_secret'])
ctx = ClientContext(sp_site).with_credentials(client_credentials)
libraryRoot = ctx.web.get_folder_by_server_relative_path(relative_url)
ctx.load(libraryRoot)
ctx.execute_query()
files = libraryRoot.files
ctx.load(files)
ctx.execute_query()
len(files)
use case : Fetch the names of all the files in SharePoint folder
This program works perfectly when the number of files in the SharePoint folder is < 5000, when it is > 5000, getting below exception

Scriptrunner/ Copying Project while logged-in as another user

I want to use my script, so that it will be executed by someone who is not me, but another user (ServiceUser) in the Jira Instance.
This is my functioning code, but I do not know how to make someone else execute it.
import com.atlassian.jira.project.Project
import com.atlassian.jira.project.ProjectManager
import com.atlassian.jira.project.AssigneeTypes
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.user.ApplicationUser
import com.atlassian.jira.component.ComponentAccessor
import com.onresolve.scriptrunner.canned.jira.admin.CopyProject
import org.apache.log4j.Logger
import com.atlassian.jira.bc.projectroles.ProjectRoleService
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.security.roles.ProjectRole
import com.atlassian.jira.util.SimpleErrorCollection
import com.atlassian.jira.security.roles.ProjectRoleManager
import com.atlassian.jira.project.ProjectManager
import com.atlassian.jira.project.Project
import com.atlassian.jira.security.roles.ProjectRoleActor
import com.atlassian.jira.bc.project.ProjectCreationData
import com.atlassian.jira.bc.project.ProjectService
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.project.AssigneeTypes
import com.atlassian.jira.project.type.ProjectTypeKey
// the key for the new project
def projectKey = "EXA987"
def projectName = "EXA987"
def log = Logger.getLogger("com.onresolve.jira.groovy.MyScript")
Thread executorThread = new Thread(new Runnable() {
void run() {
def copyProject = new CopyProject()
def inputs = [
(CopyProject.FIELD_SOURCE_PROJECT) : "SWTEMP",
(CopyProject.FIELD_TARGET_PROJECT) : projectKey,
(CopyProject.FIELD_TARGET_PROJECT_NAME) : projectName,
(CopyProject.FIELD_COPY_VERSIONS) : false,
(CopyProject.FIELD_COPY_COMPONENTS) : false,
(CopyProject.FIELD_COPY_ISSUES) : false,
(CopyProject.FIELD_COPY_DASH_AND_FILTERS) : false,
]
def errorCollection = copyProject.doValidate(inputs, false)
if(errorCollection.hasAnyErrors()) {
log.warn("Couldn't create project: $errorCollection")
}
else {
def util = ComponentAccessor.getUserUtil()
def adminsGroup = util.getGroupObject("jira-administrators")
assert adminsGroup // must have jira-administrators group defined
def admins = util.getAllUsersInGroups([adminsGroup])
assert admins // must have at least one admin
ComponentAccessor.getJiraAuthenticationContext().setLoggedInUser(util.getUserByName(admins.first().name))
copyProject.doScript(inputs)
}
}
})
executorThread.start()
I stumbled upon other codes, using things like
def oldLoggedInUser = jiraAuthenticationContext.getLoggedInUser()
jiraAuthenticationContext.setLoggedInUser(serviceUser)
jiraAuthenticationContext.setLoggedInUser(oldLoggedInUser)
but it was not succesful for me.
I have used following solution to change user during script execution:
def authContext = ComponentAccessor.getJiraAuthenticationContext();
def currentUser = authContext.getLoggedInUser();
def superuser=ComponentAccessor.getUserManager().getUserByKey("ANOTHER_USER_ACCOUNT")
authContext.setLoggedInUser(superuser);
// < do the needed work>
authContext.setLoggedInUser(currentUser);
I had first issues as my used another account had not needed Jira access rights (and I got funny "user must be logged in" errors)

How to encode the password in Gatling?

I have a requirement in my project to encode the password being sent in the login request. What is the best way to do it?
You can store the credentials in a file as key-value pair. Read the file in vector and then decode the value. The value can be stored in a session and can be used in your Gatling request as below:
import scala.concurrent.duration._
import io.gatling.core.Predef._
import io.gatling.core.structure.ChainBuilder
import io.gatling.http.Predef._
import io.gatling.jdbc.Predef._
import io.gatling.jsonpath._
import Headers._
import scala.collection._
import java.time.format.DateTimeFormatter
import java.time.LocalDateTime
import java.time.LocalDate
import io.gatling.core.feeder._
import java.util.Base64
import java.nio.charset.StandardCharsets
import scala.util.matching.Regex
object TestClass {
//Now you can use below code to read the credential file,
val recordsByEnv: Map[String, Seq[Record[Any]]] =
csv("/User/sandy/data/userdetails.csv").readRecords.groupBy { record =>
record("env").toString
}
val passwordByEnv: Map[String, Seq[Any]] = recordsByEnv.mapValues { records =>
records.map { record =>
record("password")
}
}
val password_v = (passwordByEnv.get("env_name").toString)
val password_encoded = password_v.substring(12, (password_v.length - 2))
val credentials = new String(Base64.getDecoder.decode(password_encoded))
//Store the decoded value in session variable
.exec(session => session.set("password", credentials))
.exec(
http("Authorization")
.post("https://XXXX.xxxxxx.com")
.header("Content-Type", "application/x-www-form-urlencoded")
.formParam("password", "${password}")
.formParam("username", "USERNAME")
)
//Below is user details file look like below
//env_name,encoded_password
}

Django channels Websocket Disconnect

I want my Django app 'popinion1' to communicate via textmessage with a local machine.
pip freeze :
asgi-redis==1.4.3
asgiref==2.3.2
async-timeout==3.0.1
autobahn==18.12.1
channels==2.1.3
daphne==2.2.4
Django==2.1.3
redis==2.10.6
Twisted==18.9.0
When I do "manage.py runserver" there seems to be a connection or at least no errors
However as soon as I refresh the browser in terminal I get:
ERROR - ws_protocol - [Failure instance: Traceback: class'ValueError'>: No route found for path 'input/' [lots of lines]
ending with: WebSocket DISCONNECT /input/ [127.0.0.1:50506]
with "/input/" being my app.
Firefox inspector reports:
Firefox can't establish connection to Server with ws://127.0.0.1:8000
/input/ being my app.
my routing.py is
from django.conf.urls import url
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator, OriginValidator
from input.consumers import ChatConsumer
print('ChatConsumer: ', ChatConsumer.name)
application = ProtocolTypeRouter({
'websocket': AllowedHostsOriginValidator(
AuthMiddlewareStack(
URLRouter(
[
url(r'^input/(?P<username>[\w.#+-]+)/$', ChatConsumer),
]
)
)
)
})
the javascript in the html template:
<script>
console.log(window.location)
var loc = window.location
var wsStart = 'ws://'
if (loc.protocol == 'https:'){
wsStart = 'wss://'
}
var endpoint = wsStart + loc.host + loc.pathname
var socket = new WebSocket(endpoint)
socket.onmessage = function(e){
console.log("message", e)
}
socket.onopen= function(e){
console.log("open", e)
}
socket.onerror= function(e){
console.log("error", e)
}
socket.onclose= function(e){
console.log("close", e)
}
</script>
my consumers.py
import asyncio
import json
from django.contrib.auth import get_user_model
from channels.consumer import AsyncConsumer
from channels.db import database_sync_to_async
from .models import Thread, ChatMessage
from asgiref.sync import async_to_sync
class ChatConsumer(AsyncConsumer):
name = 'ChatConsumer'
async def websocket_connect(self, event):
print('connected! ', event)
await self.send({
"type": "websocket.accept"
})
async def websocket_receive(self, event):
print('receive! ', event)
async def websocket_disconnect(self, event):
print('disconnected! ', event)
CHANNEL_LAYERS in settings.py
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'asgi_redis.core.RedisChannelLayer',
'CONFIG': {
'hosts': [('localhost', 6379)],
},
#'ROUTING': 'popinion_project.routing.channel_routing',
}
}
so is it a wrong address in the routing.py? What's also weird is the last import of "ChatConsumer" in routing.py. It's "unresolved reference" but the print statement works.
print('ChatConsumer: ', ChatConsumer.name)
I'm following this tutorial
https://www.youtube.com/watch?v=RVH05S1qab8
I'd be happy to know how to get the websocket to connect. Hopefully provided all necessary information. Thanks in advance
The solution I used. It had something to do with the use of url.
from django.urls import re_path
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator, OriginValidator
from chat.consumers import ChatConsumer
application = ProtocolTypeRouter({
# Empty for now (http->django views is added by default)
'websocket': AllowedHostsOriginValidator(
AuthMiddlewareStack(
URLRouter(
[
re_path(r"^messages/(?P<username>[\w.#+-]+)", ChatConsumer),
]
)
)
)
})

groovy api in pin payments secret key location

im doing an api for pin payment in pin.net.au and i encounter some errors like what you see in the bottom
`#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder'`,` version='0.5.0-RC2' )
import groovyx.net.http.*
import groovyx.net.http.HttpResponseDecorator
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.*
import groovyx.net.http.HttpResponseException
import groovy.swing.SwingBuilder
import javax.swing.JFrame
import wslite.http.auth.*
class Customers {
Customers(){
def rst = new RESTClient( 'https://test-api.pin.net.au/1/')
rst.auth.basic 'mySecretKey',''
def res = rst.post( path: 'customers'){
type ContentType.XML
xml {
cards{
email('pk_qTj9Umqmlf3o7lfa6F9nWw')
card[expiry_month]('12')
card[expiry_year]('2015')
card[cvc]('123')
card[name]('patrick pl')
card[address_line1]('23 frfds')
card[address_city]('Angeles')
card[address_postcode]('2009')
card[address_state]('ph')
card[address_country]('Philippines')
}
}
}
}
public static void main(String []args){
new Customers()
}
}
when i run the code the error was
May 12, 2014 1:07:35 PM org.apache.http.impl.client.DefaultRequestDirector handleResponse
WARNING: Authentication error: Unable to respond to any of these challenges: {}
Caught: groovyx.net.http.HttpResponseException: Authorization Required
groovyx.net.http.HttpResponseException: Authorization Required
at groovyx.net.http.RESTClient.defaultFailureHandler(RESTClient.java:240)
at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:475)
at groovyx.net.http.HTTPBuilder.post(HTTPBuilder.java:335)
at groovyx.net.http.HTTPBuilder$post.call(Unknown Source)
at PinPayment.Customers.<init>(Customers.groovy:16)
at PinPayment.Customers.main(Customers.groovy:39)
how could i make the authentication work for the code to be runable??
here is the link for the docs pin.net.au
Document indicates it requires basic HTTP authn.
Calls to the Pin Payments API must be authenticated using HTTP basic
authentication, with your API key as the username, and a blank string
as the password.
Therefore:
def rst = new RESTClient( 'https://test-api.pin.net.au/1/' )
rst.auth.basic 'secretAPIKeyHereAsString', ''
i found the right code for that particular api here def http = new RESTClient('https://test-api.pin.net.au/1/') http.headers['Authorization'] = 'Basic '+"tWqZl0MHsg5nUQdB6czrDQ:".getBytes('iso-8859-1').encodeBase64()

Resources