I am trying to create a site using alfresco 4.2.c rest api /alfresco/wcservice/api/sites (PUT)
I am using admin user so no issues with permissions.
I am able to create site successfully using the alfresco share UI
String objectToPost = "{\"shortName\":\"firm007\", \"title\":\"firm007\", \"description\":\"firm007\", \"visibility\":\"PRIVATE\", \"isPublic\":\"false\", \"sitePreset\":\"site-dashboard\"}";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> entity = new HttpEntity<String>(objectToPost,headers);
String url = PRE_URL + "/alfresco/wcservice/api/sites"+"?alf_ticket="+ TICKET;
String response = restTemplate.exchange(url,HttpMethod.POST, entity, String.class, new Object[] {}).toString();
System.out.println("Created SITE response is =" + response);
I am getting 500 Internal Server Error on client side code
and on alfresco server, I am getting following stack traces.
please can you help solve this issue.
I want to create an alfresco site, through a remote REST api call
2014-06-17 08:39:38,232 ERROR [freemarker.runtime] [http-apr-8080-exec-4] Template processing error: "Expression site.shortName is undefined on line 9, column 56 in org/alfresco/repository/site/site.lib.ftl."
Expression site.shortName is undefined on line 9, column 56 in org/alfresco/repository/site/site.lib.ftl.
The problematic instruction:
==> ${url.serviceContext + "/api/sites/" + site.shortName} escaped ${jsonUtils.encodeJSONString(url.serviceContext + "/api/sites/" + site.shortName)} [on line 9, column 17 in org/alfresco/repository/site/site.lib.ftl]
in user-directive siteJSONManagers [on line 2, column 1 in org/alfresco/repository/site/site.lib.ftl]
in user-directive siteLib.siteJSON [on line 2, column 1 in org/alfresco/repository/site/sites.post.json.ftl]
Java backtrace for programmers:
freemarker.core.InvalidReferenceException: Expression site.shortName is undefined on line 9, column 56 in org/alfresco/repository/site/site.lib.ftl.
Caused by: freemarker.core.InvalidReferenceException: Expression site.shortName is undefined on line 9, column 56 in org/alfresco/repository/site/site.lib.ftl.
at freemarker.core.TemplateObject.assertNonNull(TemplateObject.java:125)
at freemarker.core.Expression.getStringValue(Expression.java:118)
at freemarker.core.AddConcatExpression._getAsTemplateModel(AddConcatExpression.java:98)
at freemarker.core.Expression.getAsTemplateModel(Expression.java:89)
at freemarker.core.ListLiteral.getModelList(ListLiteral.java:119)
at freemarker.core.MethodCall._getAsTemplateModel(MethodCall.java:91)
at freemarker.core.Expression.getAsTemplateModel(Expression.java:89)
at freemarker.core.Expression.getStringValue(Expression.java:93)
solved this little puzzler.
I had not added the content-type as "application/json" hence the request was barking up the wrong tree and going to ftl instead of json
following code works fine creating a site in alfresco.
headers.set("Content-Type", "application/json");
String objectToPost = "{\"shortName\":\"firm008\", \"title\":\"firm008\", \"description\":\"firm008\", \"visibility\":\"PRIVATE\", \"isPublic\":\"false\", \"sitePreset\":\"site-dashboard\"}";
System.out.println(objectToPost);
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
**headers.set("Content-Type", "application/json");**
HttpEntity<String> entity = new HttpEntity<String>(objectToPost,headers);
String url = PRE_URL + "/alfresco/wcservice/api/sites"+"?alf_ticket="+ TICKET;
String response = restTemplate.exchange(url,HttpMethod.POST, entity, String.class, new Object[] {}).toString();
System.out.println("Created SITE response is =" + response);
Related
I have a legacy application written in VB6 (I Know!!) to which I am adding a DocuSign feature. I a using InterOp to run .NET code written is VS2019 VB.Net. The reason I am using 4.0.4.0 as this is the version I can successfully call using InterOp. I have all the code working except for requesting a JWT token. Does anyone have JWT code working under this version of the API ?
This is what I have working under later versions of DocuSign and am trying to replace
`Dim privatekey As Byte() = File.ReadAllBytes("docusign_private_key.key")
Dim result As Object = x.RequestJWTApplicationToken(gsSIGNERCLIENTID, docuSignAuthServer, privatekey, 1, scopes)
txtAccessToken.Text = result
'
' Second attempt at alternative
'
` Dim authToken As OAuth.OAuthToken = x.RequestJWTUserToken(gsSIGNERCLIENTID, gsUserIDGUID, docuSignAuthServer, privatekey, 1)
txtAccessToken.Text = authToken.access_token`
'
' Third attempt
'
Dim request = TryCast(System.Net.WebRequest.Create("https://account-d.docusign.com/oauth/token"), System.Net.HttpWebRequest)
request.Method = "POST"
request.Headers.Add("username", "user123")
request.Headers.Add("password", "123")
request.Headers.Add("auth_access_type", "read")
request.ContentLength = 0
Dim responseContent As String = ""
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
Using reader = New System.IO.StreamReader(response.GetResponseStream())
responseContent = reader.ReadToEnd()
End Using
End Using
'
' Fifth attempt
'
Dim apiClient5 As New ApiClient(gsBASEPATH)
Dim authToken5 As OAuth.OAuthToken = apiClient5.RequestJWTUserToken(gsINTEGRATIONKEY, gsUserIDGUID, "https://account-d.docusign.com/oauth/token", privatekey, 1, scopes)
All results in 'Error while requesting server, received a non-successful HTPC code Error with response Body'
Your second attempt is correct:
Dim authToken As OAuth.OAuthToken = x.RequestJWTUserToken(gsSIGNERCLIENTID, gsUserIDGUID, docuSignAuthServer, privatekey, 1)
txtAccessToken.Text = authToken.access_token
AuthServer has to be "account-d.docusign.com"
The privateKey has to be the exact thing you got from DocuSign, including the new lines and all. To get it use this code:
File.ReadAllBytes(path) where path is the path on the disk to a plain text file with your private key.
gsSIGNERCLIENTID should be the GUID for the user that you use that has consent. You must make sure user gave consent by building a consent URL as explained in here:
https://developers.docusign.com/platform/auth/consent/obtaining-individual-consent/
If you did all of this correctly - it should work.
my server is Flask based, my client is android studio, and i'm communication using retrofit.
The problem is that i'm not able to pass the jwt token correctly from the android to the server after logging in.
With postman it's working good:
{{url}}/auth - I'm logging in as the user, and getting the JWT token.
Later i'm adding "Authorization" header, with the Value "JWT {{jwt_token}}" and
{{url}}/users/john - I'm asking for user info, which is recieved without problems.
The endpoint from android studio:
public interface RunnerUserEndPoints {
// #Headers("Authorization")
#GET("/users/{user}")
Call<RunnerUser> getUser(#Header("Authorization") String authHeader, #Path("user") String user);
The call itself (The access_token is correct before sending!):
final RunnerUserEndPoints apiService = APIClient.getClient().create(RunnerUserEndPoints.class);
Log.i("ACCESS","Going to send get request with access token: " + access_token);
Call<RunnerUser> call = apiService.getUser("JWT" + access_token, username);
Log.i("DEBUG","Got call at loadData");
call.enqueue(new Callback<RunnerUser>() {
#Override
public void onResponse(Call<RunnerUser> call, Response<RunnerUser> response) { ....
The response error log from the server:
File "C:\Users\Yonatan Bitton\RestfulEnv\lib\site-packages\flask_restful\__init__.py", line 595, in dispatch_request
resp = meth(*args, **kwargs)
File "C:\Users\Yonatan Bitton\RestfulEnv\lib\site-packages\flask_jwt\__init__.py", line 176, in decorator
_jwt_required(realm or current_app.config['JWT_DEFAULT_REALM'])
File "C:\Users\Yonatan Bitton\RestfulEnv\lib\site-packages\flask_jwt\__init__.py", line 151, in _jwt_required
token = _jwt.request_callback()
File "C:\Users\Yonatan Bitton\RestfulEnv\lib\site-packages\flask_jwt\__init__.py", line 104, in _default_request_handler
raise JWTError('Invalid JWT header', 'Unsupported authorization type')
flask_jwt.JWTError: Invalid JWT header. Unsupported authorization type
10.0.0.6 - - [30/Sep/2017 01:46:11] "GET /users/john HTTP/1.1" 500 -
My api-client
public class APIClient {
public static final String BASE_URL = "http://10.0.0.2:8000";
private static Retrofit retrofit = null;
public static Retrofit getClient(){
if (retrofit==null){
retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
Log.i("DEBUG APIClient","CREATED CLIENT");
return retrofit;
}
}
Actually i'm really stuck. Tried to follow along all of the tutorials at retrofit's website without success.
I'm sure that there is a simple solution, I just need to add "Authorization" Header with Value "JWT " + access_token like it works in postman and that's it! Thanks.
EDIT:
The problem was the build of the access_token in my client.
I did:
JsonElement ans = response.body().get("access_token");
access_token = "JWT " + ans.toString();
Which I should have done:
JsonElement ans = response.body().get("access_token");
access_token = "JWT " + ans.getAsString();
So before it sent "JWT "ey..." " (Double "" )
And now it sends "JWT ey ... "
Let's start to look at what we know about the problem.
We know that the request is sent
We know that the server processes the request
We know that the JWT is invalid thanks to the error:
JWTError('Invalid JWT header', 'Unsupported authorization type')
If we look for that error in the flask_jwt source code, we can see that this is where our error is raised:
def _default_request_handler():
auth_header_value = request.headers.get('Authorization', None)
auth_header_prefix = current_app.config['JWT_AUTH_HEADER_PREFIX']
if not auth_header_value:
return
parts = auth_header_value.split()
if parts[0].lower() != auth_header_prefix.lower():
raise JWTError('Invalid JWT header', 'Unsupported authorization type')
elif len(parts) == 1:
raise JWTError('Invalid JWT header', 'Token missing')
elif len(parts) > 2:
raise JWTError('Invalid JWT header', 'Token contains spaces')
return parts[1]
Basically flask_jwt takes the Authorization header value and tries to split it into two. The function split can split a string by a delimiter, but if you call it without a delimiter it will use whitespace.
That tells us that flask_jwt expects a string that contains 2 parts separated by whitespace, such as space, and that the first part must match the prefix we are using (in this case JWT).
If we go back and look at your client code, we can see that when you are building the value to be put in the Authorization header you are not adding a space between JWT and the actual token:
apiService.getUser("JWT" + access_token, username);
This is what you should have been doing:
apiService.getUser("JWT " + access_token, username);
Notice the space after JWT?
I am trying to write automated tests for a REST API using apache HTTP client, we are using Facebook as an affiliate to log in.
I have used this question as a starting point:
apache HttpClient to access facebook
But it is using lots of deprecated methods.
I have switched all of these out but I am finding that it is not working.
to validate I have written a method to print out the body response and I am viewing that by making it into a HTML document. When I load that page it has the facebook error message of:
Cookies Required
Cookies are not enabled on your browser. Please enable cookies in your browser preferences to continue.
My code:
CookieStore cs = new BasicCookieStore();
HttpClientContext context = HttpClientContext.create();
HttpGet httpget = new HttpGet("http://www.facebook.com/login.php");
HttpResponse response= HttpClientBuilder.create().setDefaultCookieStore(cs).build().execute(httpget);
System.out.println("Login form get: " + response.getStatusLine());
HttpPost httpost = new HttpPost("https://www.facebook.com/login.php");
context.setCookieStore(cs);
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("email", "******"));
nvps.add(new BasicNameValuePair("pass", "*****"));
nvps.add(new BasicNameValuePair("lsd", "AVptst2v"));
httpost.setHeader("User-Agent", "Mozilla/5.0");
httpost.setHeader("Host", "www.facebook.com");
httpost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpost.setHeader("Accept-Language", "en-US,en;q=0.5");
httpost.setHeader("Cookie", cs.toString());
httpost.setHeader("Connection", "keep-alive");
httpost.setHeader("Referer", "https://www.facebook.com/login");
httpost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpost.setEntity(new UrlEncodedFormEntity(nvps));
response = HttpClientBuilder.create().setDefaultCookieStore(cs).build().execute(httpost,context);
System.out.println("Login form post: " + response.getStatusLine());
System.out.println(printBodyOfResponse(response));
To answer my own question, I found that creating a context and passing that through with each request carried the session, I see lots of answers saying that cookie management is automatic, but for me the only solution was to pass the context throughout
BasicHttpContext context = new BasicHttpContext();
HttpGet get = new HttpGet("http://www.facebook.com/login.php");
HttpResponse response= HttpClientBuilder.create().build().execute(get,context);
System.out.println("Login form get: " + response.getStatusLine());
HttpPost httpost = new HttpPost("https://www.facebook.com/login.php?login_attempt=1");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("email",PropertiesUtil.loadSiteProperty("FB_email")));
nvps.add(new BasicNameValuePair("pass", PropertiesUtil.loadSiteProperty("FB_password")));
httpost.setHeader("User-Agent", "Mozilla/5.0");
httpost.setHeader("Host", "www.facebook.com");
httpost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpost.setHeader("Accept-Language", "en-US,en;q=0.5");
httpost.setHeader("Connection", "keep-alive");
httpost.setHeader("Referer", "https://www.facebook.com/login");
httpost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpost.setEntity(new UrlEncodedFormEntity(nvps));
response = HttpClientBuilder.create().build().execute(httpost,context);
i am using the following code to get the balancesheet and profilt and loss data from quickbooks.
OAuthRequestValidator oauth = new OAuthRequestValidator(accessToken, accessTokenSecret,
consumerKey, consumerSecret);
ServiceContext serviceContext = new ServiceContext(realmId, IntuitServicesType.QBO, oauth);
serviceContext.IppConfiguration.Message.Request.SerializationFormat =
Intuit.Ipp.Core.Configuration.SerializationFormat.Json;
ReportService reportService = new ReportService(serviceContext);
reportService.accounting_method = "Accrual";
reportService.start_date = "2014-01-01";
reportService.end_date = "2014-06-01";
Report report = reportService.ExecuteReport("BalanceSheet");
it compiles well, but when it runs it gives the following error.
"
**Ids service endpoint was not found.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: Intuit.Ipp.Exception.EndpointNotFoundException: Ids service endpoint was not found.
Source Error:
Line 133: reportService.start_date = "2014-01-01";
Line 134: reportService.end_date = "2014-06-01";
Line 135: Report report = reportService.ExecuteReport("BalanceSheet");
Line 136:
Line 137:"**
Please use the correct date format YYYY-MM-DD.
Please use response format as JSON as xml is not supported. Your code will work then.
serviceContext.IppConfiguration.Message.Response.SerializationFormat = Intuit.Ipp.Core.Configuration.SerializationFormat.Json;
I'm trying to create a HTTP Client to upload a file following this example: http://java.dzone.com/articles/file-upload-apache-httpclient
When I run the application to upload the file on my RESTFul service, I get:
HTTP ERROR 500
Problem accessing /file/upload. Reason:
Server ErrorCaused by:java.lang.NullPointerException
at com.nice.rest.UploadFileService.uploadFile(UploadFileService.java:33)
...
Where line 33 is:
public class UploadFileService {
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
#FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail) {
//line 33: String uploadedFileLocation = "/mnt/folder/"+ fileDetail.getFileName();
System.out.println("uploadedFileLocation : "+uploadedFileLocation);
// save it
writeToFile(uploadedInputStream, uploadedFileLocation);
String output = "200 OK<br />" + uploadedFileLocation;
return Response.status(200).entity(output).build();
}
Surprisingly, when I upload a file using a html form it works fine:
form action="http://X.X.X.X:8080/file/upload" method="post" enctype="multipart/form-data"
What's wrong?
thanks!!
When you build your multi-part entity, make sure that the #FormDataParam annotation value contains the name of the part within the multipart.
It looks like the part you're looking for doesn't exist hence the NullPointerException.
Please post your client code if possible showing how you construct the multi-part entity