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();
}
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'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);
I am trying to create an instance with the Google Java API however I am getting an error:
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Invalid value for field 'resource.machineType': 'https://www.googleapis.com/compute/v1/projects/...snip.../zones/europe-west1-a/machineTypes/n1-standard-1'. Cross-project references for this resource type are not allowed.",
"reason" : "invalid"
} ],
"message" : "Invalid value for field 'resource.machineType': 'https://www.googleapis.com/compute/v1/projects/...snip.../zones/europe-west1-a/machineTypes/n1-standard-1'. Cross-project references for this resource type are not allowed."
}
The code I am using:
Compute compute = getComputeService();
// uri reveals: https://www.googleapis.com/compute/v1/projects/...projectid.../zones/europe-west1-a/machineTypes/n1-standard-1
String uri = GOOGLE_BASE + this.project + "/zones/" + zone + INSTANCETYPES + type;
Instance instance = new Instance();
instance.setName(name);
instance.setZone(zone);
instance.setMachineType(uri);
List<AttachedDisk> disks = new ArrayList<AttachedDisk>();
AttachedDisk boot = new AttachedDisk();
boot.setAutoDelete(false);
boot.setType(disk.getType());
boot.setBoot(true);
boot.setDeviceName(disk.getName());
disks.add(boot);
List<NetworkInterface> interfaces = new ArrayList<NetworkInterface>();
NetworkInterface nat = new NetworkInterface();
nat.setName("External NAT");
nat.setNetwork("ONE_TO_ONE_NAT");
instance.setNetworkInterfaces(interfaces);
instance.setDisks(disks);
Instances.Insert request = compute.instances().insert(name, zone, instance);
Operation result = request.execute();
As per this link, I believe that your request should look like:
Instances.Insert request = compute.instances().insert(this.project, zone, instance);
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.