com.box.sdk.BoxAPIException: The API returned an error code: 404 - box

I used function to create metadata with template. but it throw exception
com.box.sdk.BoxAPIException: The API returned an error code: 404
createMetadata(typename, scope, metadata);

I did this and it seems to work.
BoxFile file = new BoxFile(api, "113280761775");
file.createMetadata(new Metadata().add("/test", "test"));
Metadata metadata = file.getMetadata();
System.out.println("printing out meta-data: " + metadata.get("/test"));

Related

RESTful client in Unity - validation error

I have a RESTful server created with ASP.Net and am trying to connect to it with the use of a RESTful client from Unity. GET works perfectly, however I am getting a validation error when sending a POST request. At the same time both GET and POST work when sending requests from Postman.
My Server:
[HttpPost]
public IActionResult Create(User user){
Console.WriteLine("***POST***");
Console.WriteLine(user.Id+", "+user.sex+", "+user.age);
if(!ModelState.IsValid)
return BadRequest(ModelState);
_context.Users.Add(user);
_context.SaveChanges();
return CreatedAtRoute("GetUser", new { id = user.Id }, user);
}
My client:
IEnumerator PostRequest(string uri, User user){
string u = JsonUtility.ToJson(user);
Debug.Log(u);
using (UnityWebRequest webRequest = UnityWebRequest.Post(uri, u)){
webRequest.SetRequestHeader("Content-Type","application/json");
yield return webRequest.SendWebRequest();
string[] pages = uri.Split('/');
int page = pages.Length - 1;
if (webRequest.isNetworkError || webRequest.isHttpError){
Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
}
else{
Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
}
}
}
I was trying both with the Json conversion and writing the string on my own, also with the WWWForm, but the error stays.
The error says that it's an unknown HTTP error. When printing the returned text it says:
"One or more validation errors occurred.","status":400,"traceId":"|b95d39b7-4b773429a8f72b3c.","errors":{"$":["'%' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0."]}}
On the server side it recognizes the correct method and controller, however, it doesn't even get to the first line of the method (Console.WriteLine). Then it says: "Executing ObjectResult, writing value of type 'Microsoft.AspNetCore.Mvc.ValidationProblemDetails'".
Here're all of the server side messages:
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 POST http://localhost:5001/user application/json 53
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
Executing endpoint 'TheNewestDbConnect.Controllers.UserController.Create (TheNewestDbConnect)'
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
Route matched with {action = "Create", controller = "User"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Create(TheNewestDbConnect.Data.Entities.User) on controller TheNewestDbConnect.Controllers.UserController (TheNewestDbConnect).
info: Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor[1]
Executing ObjectResult, writing value of type 'Microsoft.AspNetCore.Mvc.ValidationProblemDetails'.
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Executed action TheNewestDbConnect.Controllers.UserController.Create (TheNewestDbConnect) in 6.680400000000001ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
Executed endpoint 'TheNewestDbConnect.Controllers.UserController.Create (TheNewestDbConnect)'
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 11.3971ms 400 application/problem+json; charset=utf-8
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
I have no idea what is happening and how to solve it. Any help will be strongly appreciated!
Turned out I was just missing an upload handler. Adding this line solved it: webRequest.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(JsonObject));

IBM Cloud Object Storage Java Client - IllegalArgument exception

I'm following sample provided here https://console.bluemix.net/docs/services/cloud-object-storage/libraries/java.html#java
Created the following code:
SDKGlobalConfiguration.IAM_ENDPOINT = "https://iam.bluemix.net/oidc/token";
String bucketName = "mybucket_name";
String api_key = "api_key_taken_fro_the_service_credential_json";
String service_instance_id = "service_id_taken_from_the_bucket_policies_page";
String endpoint_url = "http://s3.mel01.objectstorage.softlayer.net";
String location = "mel01";
System.out.println("Current time: " + new Timestamp(System.currentTimeMillis()).toString());
_cos = createClient(api_key, service_instance_id, endpoint_url, location);
listObjects(bucketName, _cos);
listBuckets(_cos);
the listObjects and listBuckets are exact c&p from that referred page.
I'm getting Invalid argument exception, as follows:
Listing objects in bucket mybucket_name
[INFO ] FFDC1015I: An FFDC Incident has been created: "com.ibm.cloud.objectstorage.services.s3.model.AmazonS3Exception: Invalid Argument (Service: Amazon S3; Status Code: 400; Error Code: InvalidArgument; Request ID: 3bb36c4c-8de4-4f39-98f4-a1bfd3aa8972), S3 Extended Request ID: null com.ibm.ws.webcontainer.servlet.ServletWrapper.init 181" at ffdc_18.04.12_13.02.15.0.log
[ERROR ] SRVE0271E: Uncaught init() exception created by servlet [gas.servlet.BlmxS3Servlet] in application [s3]: com.ibm.cloud.objectstorage.services.s3.model.AmazonS3Exception: Invalid Argument (Service: Amazon S3; Status Code: 400; Error Code: InvalidArgument; Request ID: 3bb36c4c-8de4-4f39-98f4-a1bfd3aa8972), S3 Extended Request ID: null
at com.ibm.cloud.objectstorage.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1588)
at com.ibm.cloud.objectstorage.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1258)
at com.ibm.cloud.objectstorage.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1030)
at com.ibm.cloud.objectstorage.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:742)
at com.ibm.cloud.objectstorage.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:716)
at com.ibm.cloud.objectstorage.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:699)
at com.ibm.cloud.objectstorage.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:667)
at com.ibm.cloud.objectstorage.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:649)
at com.ibm.cloud.objectstorage.http.AmazonHttpClient.execute(AmazonHttpClient.java:513)
at com.ibm.cloud.objectstorage.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:3635)
at com.ibm.cloud.objectstorage.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:3582)
at com.ibm.cloud.objectstorage.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:3576)
at com.ibm.cloud.objectstorage.services.s3.AmazonS3Client.listObjects(AmazonS3Client.java:761)
at gas.servlet.BlmxS3Servlet.listObjects(BlmxS3Servlet.java:94)
at gas.servlet.BlmxS3Servlet.init(BlmxS3Servlet.java:63)
at javax.servlet.GenericServlet.init(GenericServlet.java:244)
at [internal classes]
What argument might be invalid? No clue from the log nor ffdc.
UPDATE
The bucket name is correct, otherwise I'm getting:
[ERROR ] SRVE0271E: Uncaught init() exception created by servlet [gas.servlet.BlmxS3Servlet] in application [s3]: com.ibm.cloud.objectstorage.services.s3.model.AmazonS3Exception: The specified bucket does not exist. (Service: Amazon S3; Status Code: 404; Error Code: NoSuchBucket; Request ID: bf299e50-1aac-4af7-89df-188eb4b7c60f), S3 Extended Request ID: null
your endpoint_url should be over https instead of http
There were several issues during configuring this:
1) You need to create credential with additional properties of {"HMAC":true}
2) For the configuration use:
apikey - apikey entry from the credential
service_instance_id - this is a bit misleading - as it is your Object servcie name, not id - in my case it was string Cloud Object Storage-abc
endpoint_url - bucket endpoint - in my case http://s3.mel01.objectstorage.softlayer.net - make sure that it is https and that you imported certificates to your truststore.
Then is should work.
Listing buckets is not working for me still due to "Access Denied", so I have to check the permissions for the service ID.

C# Download File from HTTP File Directory getting 401 error or 403 error

I’m trying to download several files from a local network device:
http file directory
I want to write a code that will automatically download all those .avi files to my pc drive.
I have 2 problems:
Problem 1: AUTHENTICATING using WebClient class only.
If I use WebClient class only to connect, I get a 401 Unauthorized error.
Code:
try
{
using (WebClient myWebClient = new WebClient())
{
myWebClient.UseDefaultCredentials = false;
myWebClient.Credentials = new NetworkCredential("user", "pword");
String userName = "user";
String passWord = "pword";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord));
myWebClient.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials;
Console.WriteLine("Header AUTHORIZATION: "+ myWebClient.Headers[HttpRequestHeader.Authorization].ToString());
// Download the Web resource and save it into the current filesystem folder.
Console.WriteLine("Start DL");
myWebClient.DownloadFile("http://192.168.2.72:81/sd/20170121/record000/P170121_000000_001006.avi", "P170121_000000_001006.avi");
Console.WriteLine("End DL");
}
}
catch(Exception ex)
{
Console.WriteLine("DOWNLOAD ERROR: " + ex.ToString());
}
Error Message: Failure to authenticate
401 Unauthorized Error
Problem 2: Was able to authenticate using WebProxy class but can’t download . Getting 403 Not found error.
Code:
try
{
using (WebClient myWebClient = new WebClient())
{
WebProxy wp = new WebProxy("http://192.168.2.72:81/sd/20170121/record000/",false);
wp.Credentials = new NetworkCredential("user","pword");
Console.WriteLine("Web Proxy: " + wp.Address);
myWebClient.UseDefaultCredentials = false;
myWebClient.Credentials = wp.Credentials;
myWebClient.Proxy = wp;
Console.WriteLine("Downloading File \"{0}\" from \"{1}\"\n\n", filename, wp.Address);
// Download the Web resource and save it into the current filesystem folder.
Console.WriteLine("Start DL");
myWebClient.DownloadFile("http://192.168.2.72:81/sd/20170121/record000/P170121_000000_001006.avi", "P170121_000000_001006.avi");
Console.WriteLine("End DL");
}
}
catch(Exception ex)
{
Console.WriteLine("DOWNLOAD ERROR: " + ex.ToString());
}
Error Message: 403 Not Found
DOWNLOAD ERROR: System.Net.WebException: The remote server returned an error: (404) Not Found.
at System.Net.WebClient.DownloadFile(Uri address, String fileName)
at System.Net.WebClient.DownloadFile(String address, String fileName)
at ConsoleApplication2.Program.Main(String[] args) in C:\Users\Gordon\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\Program.cs:line 139
Please help me identify if there are any mistakes in my code or is there a better way to submit credentials and download all the files.
Thanks in advance!
I'm not Dot Net developer, I'm just sharing my opinion.
In the second point you have mentioned that you are getting 403 which is the Http status code for Acces Denied. I feel your credentials are not valid or you don't have privilege to do the operation.

Alfresco 4.2.c rest api: create site giving error

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);

Intuit Reporting services (Balancesheet / profilt and loss)

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;