I want to upload a file to alfresco using the backend Webscript: alfresco/service/api/upload. Here is how I build my json:
_ticket = Login.getAlfTicket(login, psswd);
String url = "http://localhost:8080/alfresco/service/api/upload";
File file = new File("C:/the-file-name.txt");
byte[] bytes = Files.readAllBytes(file.toPath());
bytes = Base64.encodeBase64(bytes);
JSONObject json = new JSONObject();
json.put("filedata", new String(bytes));
json.put("siteid", "google");
json.put("containerId", "documentLibrary");
json.put("uploadDirectory", "/test");
I use RestTemplate to POST my json. when I run the application I get this error :
"status" :
{
"code" : 500,
"name" : "Internal Error",
"description" : "An error inside the HTTP server which prevented it from fulfilling the request."
},
"message" : "04210030 Unexpected error occurred during upload of new content.",
"exception" : "org.springframework.extensions.webscripts.WebScriptException - 04210030 Unexpected error occurred during upload of new content.",
"callstack" :
[
"" ,"org.mozilla.javascript.JavaScriptException: [object Error] (file:\/C:\/Alfresco\/tomcat\/webapps\/alfresco\/WEB-INF\/classes\/alfresco\/templates\/webscripts\/org\/alfresco\/repository\/upload\/upload.post.js#405)"
,"org.mozilla
.....
I know that the problem come from this part : json.put("filedata", new String(bytes));. Any idea why ? if it is something else please let me know !
Here is what I did at the end to make it work :
_ticket = Login.getAlfTicket("admin", "alfresco");
String url = "http://localhost:8080/alfresco/service/api/upload";
MultiValueMap<String, Object> request = new LinkedMultiValueMap<String, Object>();
FileSystemResource rsc = new FileSystemResource("<PATH_TO_FOLDER>/the-file-name.txt");
request.add("filedata", rsc);
request.add("siteid", "yoursite");
request.add("containerid", "documentLibrary");
request.add("uploaddirectory", "test");
//restTemplate is an instance of RestTemplate class
restTemplate.postForEntity(url + "?alf_ticket=" + _ticket, request,
String.class);
Hope this help.
Related
So I am trying to make a HTTP request to get access token and refresh token using following java code.
String url = "https://oauth2.googleapis.com/token?";
Map<String, String> parameters = new HashMap<>();
parameters.put("code", "4%2******");
parameters.put("client_id", "*****");
parameters.put("client_secret", "*****");
parameters.put("redirect_uri", "http://localhost");
parameters.put("grant_type","authorization_code");
parameters.put("access_type","offline");
String form = parameters.keySet().stream()
.map(key -> key + "=" + URLEncoder.encode(parameters.get(key), StandardCharsets.UTF_8))
.collect(Collectors.joining("&"));
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url))
.headers("Content-Type", "application/json")
.POST(BodyPublishers.ofString(form)).build();
HttpResponse<?> response = client.send(request, BodyHandlers.ofString());
System.out.println(response.statusCode() + response.body().toString());
But using this code gives the following error,
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unexpected token.\ncode=4%2****\n^",
"status": "INVALID_ARGUMENT"
}
}
What is the mistake that I have done here and should rectify in order to get proper results?
You are sending application/x-www-form-urlencoded data format but according to the response message you should send json. Try to change definition of form:
String form = new ObjectMapper().writeValueAsString(parameters);
I have used below code to do that.
BatchUpdateSpreadsheetRequest batchUpdateSpreadsheetRequest = new BatchUpdateSpreadsheetRequest();
DuplicateSheetRequest requestBody = new DuplicateSheetRequest();
requestBody.setNewSheetName("test");
requestBody.setSourceSheetId(sheetId);
Sheets sheetsService = createSheetsService();
batchUpdateSpreadsheetRequest.set("duplicateSheet", requestBody);
Sheets.Spreadsheets.BatchUpdate request = sheetsService.spreadsheets().
batchUpdate(spreadsheetId,batchUpdateSpreadsheetRequest);
BatchUpdateSpreadsheetResponse response = request.execute();
When I execute this, I get below error.
Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Invalid JSON payload received. Unknown name \"duplicate_sheet\": Cannot find field.",
"reason" : "badRequest"
} ],
"message" : "Invalid JSON payload received. Unknown name \"duplicate_sheet\": Cannot find field.",
"status" : "INVALID_ARGUMENT"
}
what am I doing wrong here? What is the correct way to create duplicate of sheet?
I have managed to overcome this problem by following something similar from google documentation. Below is the code I used.
BatchUpdateSpreadsheetRequest batchUpdateSpreadsheetRequest = new
BatchUpdateSpreadsheetRequest();
List<Request> requests = new ArrayList<>();
DuplicateSheetRequest requestBody = new DuplicateSheetRequest();
requestBody.setNewSheetName("test");
requestBody.setSourceSheetId(sheetId);
requests.add(new Request().setDuplicateSheet(requestBody));
Sheets sheetsService = createSheetsService();
batchUpdateSpreadsheetRequest.setRequests(requests);
Sheets.Spreadsheets.BatchUpdate request =
sheetsService.spreadsheets().batchUpdate(spreadsheetId, batchUpdateSpreadsheetRequest);
BatchUpdateSpreadsheetResponse response = request.execute();
Here is the PHP version of creating a sheet duplicate in case you need:
//Assuming you already have a $spreadsheet
$spreadsheetId = $spreadsheet->spreadsheetId;
$body = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(array(
'requests' => array(
'duplicateSheet' => array(
'sourceSheetId' => 0, //Source sheet id goes here as an integer
'insertSheetIndex' => 1, //Position where the new sheet should be inserted
'newSheetName' => 'test' //Set new name if you want
)
)
));
$spreadsheet = $service->spreadsheets->batchUpdate($spreadsheetId, $body);
Here is a C# (.net 6) version:
public void Duplicate(int SourceSheetId, string NewSheetName) {
BatchUpdateSpreadsheetRequest batchUpdateSpreadsheetRequest = new BatchUpdateSpreadsheetRequest();
batchUpdateSpreadsheetRequest.Requests = new List<Request>();
batchUpdateSpreadsheetRequest.Requests.Add(new Request() {
DuplicateSheet = new DuplicateSheetRequest() {
NewSheetName = NewSheetName,
SourceSheetId = SourceSheetId
},
});
var req = Service.Spreadsheets.BatchUpdate(batchUpdateSpreadsheetRequest, SheetID); //public SheetsService Service; property of parent class
BatchUpdateSpreadsheetResponse response = req.Execute();
}
I'm trying to save a video via the YouTube API. Basically it is already working fine, just for one exception: If I try to set the status.setPublishAt() I get
400 Bad Request
{
"code" : 400,
"errors" : [ {
"domain" : "youtube.video",
"location" : "body",
"locationType" : "other",
"message" : "The request metadata is invalid.",
"reason" : "invalidVideoMetadata"
} ],
"message" : "The request metadata is invalid."
}
The code is as follows:
YouTube.Videos.List listVideosRequest = M_YOUTUBE.videos().list("snippet,status").setId(_dbVideo.getYoutubeId());
VideoListResponse listResponse = listVideosRequest.execute();
List<Video> videoList = listResponse.getItems();
if (videoList.isEmpty()) {
return false;
}
Video video = videoList.get(0);
VideoStatus status = video.getStatus();
status.setPrivacyStatus(_dbVideo.getPrivacyStatus()); // "private"
String sPublishedAt = _dbVideo.getPublishedAt();
// sPublishAt is in ISO 8106: "2016-10-28T10:01:00.000+02:00"
if (sPublishedAt != null && sPublishedAt != "") {
// this line leads to the bad request.
status.setPublishAt(new DateTime(sPublishedAt));
} else {
status.setPublishAt(null);
}
VideoSnippet snippet = video.getSnippet();
String sTitle = _dbVideo.getTitle();
String sDescription = _dbVideo.getDescription();
String sTags = _dbVideo.getTags();
...
snippet.setTitle(sTitle);
snippet.setDescription(sDescription);
snippet.setTags(tagList);
snippet.setCategoryId(_dbVideo.getCategoryId());
YouTube.Videos.Update updateVideosRequest = M_YOUTUBE.videos().update("snippet,status", video);
updateVideosRequest.execute();
For the uploading process I am using mostly the same code and it is working there. If I decide not to set the publishAt property with a date and instead set it to null it is working fine as well. Am I missing something?
Update:
The beheviour only occurs if the video was set to public once. If i decide to set it back to private and set a new publishAt i get the BadRequest.
You have to sent all the status values, otherwise the update method will think you are trying to empty them. You have send setPrivacyStatus and publishat. But you should send all other parameter to your request. Also, if you send publishat time too close to current time it will show badRequest (400) invalidPublishAt. try to put 60 mins. It works for me.
I'm trying to connect to the transmission rpc interface via C#/Java to get some informations back.
https://trac.transmissionbt.com/browser/trunk/extras/rpc-spec.txt
Unfortunatly I have problems to get the correct HTTP-Post to access the interface.
For example if I try this in C#:
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["torrent-get"] = "id";
var response = client.UploadValues("http://ip:9091/transmission/rpc", values);
var responseString = Encoding.Default.GetString(response);
Console.WriteLine("" + responseString);
}
Or if i use:
using (var webClient = new WebClient())
{
String json = "{\"arguments\": {\"fields\": [ \"id\", \"name\", \"totalSize\" ],\"ids\": [ 7, 10 ]},\"method\": \"torrent-get\",\"tag\": 39693}";
var response = webClient.UploadString("http://192.168.240.171:9091/transmission/rpc", "POST", json);
Console.WriteLine(""+response);
}
I get the following error:
An unhandled exception of type 'System.Net.WebException' occurred in System.dll
Additional information: The Remoteserver returned an exception: (409) conflict.
You must save the X-Transmission-Session-Id provided in the 409 response and resubmit the request with a X-Transmission-Session-Id property added to your request header.
Example in java :
int index = responseString.indexOf("X-Transmission-Session-Id:");
String sessionId = responseString.substring(index + 27, index + 75);
connection.setRequestProperty("X-Transmission-Session-Id", sessionId);
This may be easy one, but I am confused.
I am trying to do HTTP POST on a server using Android Restlet, and read the reply returned from the server.
I created form using:
Form form = new Form
form.add("msg" ,"This is my message");
Now, I have clientResource as follows:
ClientResource clientResource = new ClientResource("www.example.com/my-http-post-url/");
Now, I am doing HTTP Post as:
Representation response=null;
try{
response= clientResource.post(form.getWebRepresentation(null));
System.out.println("Got response !! , response : " + response.getText());
System.out.println( "Got Context: " + clientResource.getContext() );
System.out.println( "Got Response: " + clientResource.getResponse());
System.out.println( "Got Resonse Attribute : " + clientResource.getResponseAttributes() );
System.out.println( "Got Resonse Entity: " + clientResource.getResponseEntity() );
}catch(Exception e){
e.printStackTrace();
}
I found out that the code is going inside try, but its printing :
I/org.restlet( 493): Starting the default HTTP client
I/System.out( 493): Got response !! , response : null
I/System.out( 493): Got Context: null
I/System.out( 493): Got Response: HTTP/1.1 - OK (200) - OK
I/System.out( 493): Got Resonse Attribute : {org.restlet.http.headers=[(Date,Sun, 22 Jul 2012 22:14:03 GMT), (Server,WSGIServer/0.1 Python/2.7.1+), (Vary,Authorization), (Content-Type,application/json; charset=utf-8)]}
I/System.out( 493): Got Resonse Entity: [application/json,UTF-8]
I tried sniffing the data, to see if the server is replying or not, I am confident that server is sending the response content.
Can anyone tell me, how can I find out the response content send by the server?
You're using client-side support of Restlet the right way. The response content should be contained within the response representation...
The first step is to call your REST service outside Android to see the exact response content. Can you try to do this using restclient (http://code.google.com/p/rest-client/) or curl?
Thierry
Try something like this:
I have something similar to this right now:
ClientResource clientResource = new ClientResource(url);
Request request = new Request(Method.POST, url);
clientResource.setRequest(request);
Form form = new Form();
form.set("foo", "barValue");
org.restlet.representation.Representation response = clientResource.post(form, MediaType.APPLICATION_JSON);
Representation responseEntity = clientResource.getResponseEntity();
JsonRepresentation jsonRepresentation = new JsonRepresentation(responseEntity);
JSONObject jsonObject = jsonRepresentation.getJsonObject();
String[] names = JSONObject.getNames(jsonObject);
if (jsonObject.has("errorString"))
{
String error = jsonObject.optString("errorString");
}