I created Jira issue by using jira liberary
<dependency>
<groupId>com.atlassian.jira</groupId>
<artifactId>jira-rest-java-client-app</artifactId>
<version>5.2.1</version>
</dependency>
but while creating I am not able to set Assignee or AssigneeName for created JiraIssue
below is my code
BasicUser user = projectType.get().getLead();
System.out.println(user.getDisplayName());
builder = new IssueInputBuilder(project, issueType, issueDTO.getIssueSummery());
builder.setProject(project);
builder.setDescription(issueDTO.getIssueDescription());
IssueInput input = builder.build();
IssueRestClient client = restClient.getIssueClient();
BasicIssue issue = client.createIssue(input).claim();
//input = IssueInput.createWithFields(new FieldInput(IssueFieldId.ASSIGNEE_FIELD, ComplexIssueInputFieldValue.with("name", "Wraplive User")));
builder.setPriorityId(1L);
builder.setAssigneeName("Wraplive User");
IssueInput issueInput = builder.build();
client.updateIssue(issue.getKey(), issueInput);
I tried builder.setAssignee(user); // here it sets AssigneeName as Project lead which I don't require, I want to set another user or logged in username.
Can anyone help me where I am going wrong.
I tried with FieldInput which is commented in above code.
public JiraRestClient getJiraRestClient()
{
return new AsynchronousJiraRestClientFactory().createWithBasicHttpAuthentication(getJiraUri(), JIRA_USERNAME, JIRA_PASSWORD);
}
public URI getJiraUri()
{
return URI.create(JIRA_URL);
}
//loadConnectionProperties();
restClient = getJiraRestClient();
BasicProject project = null;
IssueType issueType = null;
IssueInputBuilder builder = null;
try
{
final Iterable<BasicProject> projects = restClient.getProjectClient().getAllProjects().claim();
for(BasicProject projectStr : projects)
{
if(projectStr.getKey().equalsIgnoreCase(PROJECT_KEY))
{
project = projectStr;
}
}
Promise<Project> projectType = restClient.getProjectClient().getProject(PROJECT_KEY);
for(IssueType type : (projectType.get()).getIssueTypes())
{
if(type.getName().equalsIgnoreCase(Issue_Type))
{
issueType = type;
}
}
builder = new IssueInputBuilder(project, issueType, issueDTO.getIssueSummery());
builder.setProject(project);
builder.setDescription(issueDTO.getIssueDescription());
builder.setPriorityId(1L);
***builder.setFieldInput(new FieldInput("assignee", ComplexIssueInputFieldValue.with("accountId", "557058:0fa57746-30a2-498c-9e34-9306679d0be7")));***
IssueInput input = builder.build();
IssueRestClient client = restClient.getIssueClient();
BasicIssue issue = client.createIssue(input).claim();
System.out.println(issue.getKey());
LOG.error("Jira Created for " + issueDTO.getIssueSummery() + " ID is :: " + issue.getKey());
}
catch(Exception e)
{
e.printStackTrace();
return false;
}
return true;
Related
I have integrated AWS Java SDK in my applcaition.Unfoutunately am getting "Internal Failure. Please try your request again" as the response.
This is how I have implemeneted it.
Using Maven, added this in pom.xml
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>transcribe</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bom</artifactId>
<version>2.10.12</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
And in code,
String localAudioPath = "/home/****.wav";
String key = config.awsSecretAccessKey;
String keyId = config.awsAccessKeyId;
String regionString = config.awsRegion; //"ap-south-1"
String outputBucketName = config.awsOutputBucket;
Region region = Region.of(regionString);
String inputLanguage = "en-US";
LanguageCode languageCode = LanguageCode.fromValue(inputLanguage);
AwsCredentials credentials = AwsBasicCredentials.create(keyId, key);
AwsCredentialsProvider transcribeCredentials=StaticCredentialsProvider.create(credentials);
AWSCredentialsProvider s3AwsCredentialsProvider = getS3AwsCredentialsProvider(key, keyId);
String jobName = subJob.getId()+"_"+subJob.getProgram_name().replace(" ", "");
String fileName = jobName + ".wav";
AmazonS3 s3 =
AmazonS3ClientBuilder.standard().withRegion(regionString).withClientConfiguration(new
ClientConfiguration()).withCredentials(s3AwsCredentialsProvider).build();
s3.putObject(outputBucketName, fileName, new File(localAudioFilePath));
String fileUri = s3.getUrl(outputBucketName, fileName).toString();
System.out.println(fileUri);
Media media = Media.builder().mediaFileUri(fileUri).build();
String mediaFormat = MediaFormat.WAV.toString();
jobName = jobName +"_"+ System.currentTimeMillis();
Settings settings = Settings.builder()
.showSpeakerLabels(true)
.maxSpeakerLabels(10)
.build();
StartTranscriptionJobRequest request = StartTranscriptionJobRequest.builder()
.languageCode(languageCode)
.media(media)
.mediaFormat(mediaFormat)
.settings(settings)
.transcriptionJobName(jobName)
.build();
TranscribeAsyncClient client = TranscribeAsyncClient.builder()
.region(region)
.credentialsProvider(transcribeClientCredentialsProvider)
.build();
CompletableFuture<StartTranscriptionJobResponse> response =
client.startTranscriptionJob(request);
System.out.println(response.get().toString());
GetTranscriptionJobRequest jobRequest =
GetTranscriptionJobRequest.builder().transcriptionJobName(jobName).build();
while( true ){
CompletableFuture<GetTranscriptionJobResponse> transcriptionJobResponse =
client.getTranscriptionJob(jobRequest);
GetTranscriptionJobResponse response1 = transcriptionJobResponse.get();
if (response1 != null && response1.transcriptionJob() != null) {
if (response1.transcriptionJob().transcriptionJobStatus() ==
TranscriptionJobStatus.FAILED) {
//It comes here and gives response1.failureReason = "Internal Failure. Please try your request again".
break;
}
}
}
private AWSCredentialsProvider getS3AwsCredentialsProvider(String key, String keyId) {
return new AWSCredentialsProvider() {
#Override
public AWSCredentials getCredentials() {
return new AWSCredentials() {
#Override
public String getAWSAccessKeyId() {
return keyId;
}
#Override
public String getAWSSecretKey() {
return key;
}
};
}
#Override
public void refresh() {
}
};
}
The same thing is working with Python SDK. Same region, same wav file, same language, same settings, same output bucket etc. What am doing wrong??
Your flow looks correct. It may be an issue with the audio file you are uploading to AWS. I suggest you check it once.
I'm trying to access the details of the Facebook pages I'm an admin on through restfb. I can get my user details but when I try to get the details from 'me/accounts' it just returns null.
I've tried using different types and classes but still won't show what I need. However it works fine using the Facebook Graph API tool
private void authUser(ActionEvent event) {
String appId = "(My App ID)";
String domain = "https://www.google.com";
String authUrl = "https://graph.facebook.com/oauth/authorize?type=user_agent&client_id="+appId+"&redirect_uri="+domain+"&scope=ads_management, ads_read, business_management, email, groups_access_member_info, leads_retrieval, manage_pages, pages_manage_cta, pages_manage_instant_articles, pages_messaging, pages_messaging_phone_number, pages_messaging_subscriptions, pages_show_list, publish_pages, publish_to_groups, publish_video, read_audience_network_insights, read_insights, read_page_mailboxes, user_age_range, user_birthday, user_events, user_friends, user_gender, user_hometown, user_likes, user_link, user_location, user_photos, user_posts, user_status, user_tagged_places, user_videos";
System.setProperty("webdriver.chrome.driver", "chromedriver");
WebDriver driver = new ChromeDriver();
driver.get(authUrl);
String accessToken;
String accessToken2 = null;
while(true){
if(!driver.getCurrentUrl().contains("facebook")){
String url = driver.getCurrentUrl();
accessToken = url.replaceAll(".*#access_token=(.+)&.*","$1");
int indexOfLast = accessToken.lastIndexOf("&");
if(indexOfLast >=0) accessToken2 = accessToken.substring(0, indexOfLast);
System.out.println(accessToken);
System.out.println(accessToken2);
driver.quit();
driver = null;
FacebookClient fbClient = new DefaultFacebookClient(accessToken2, com.restfb.Version.VERSION_3_2);
User user = fbClient.fetchObject("me", User.class, Parameter.with("fields", "name, email"));
User account = fbClient.fetchObject("me/accounts", User.class, Parameter.with("fields", "name"));
name.setText(user.getName());
id.setText(user.getId());
if (user.getEmail() == null) {
email.setText("Unable to show email");
} else {
email.setText(user.getEmail());
}
if (account.getName()== null) {
System.out.println("Null");
} else {
System.out.println(account.getName());
}
}
}
}
I am looking for a way how to get app versionCode and VersionName from google play with package name via java app in PC.
I have seen: https://androidquery.appspot.com/ but it not working anymore and also https://code.google.com/archive/p/android-market-api/ started to making problems and also stopped working, and it requer device ID.
Can you help me with some simple solution or API for this?
Very important, i need versionCode and VersionName and VersionName is relatively easy to get by parsing html google play app site. The versionCode is very important.
There is no official Google Play API, Playstore uses an internal protobuf API which is not documented and not open. IMHO, you could :
use an open source library that reverse engineer the API
scrap apk download sites that have already extracted this information (most likely via the same protobuf Google Play API)
Note that there is a Google Play developer API but you can't list your apks, versions, apps. It's essentially used to manage the app distribution, reviews, edits etc..
Google play internal API
play-store-api Java library
This library uses Google Play Store protobuf API (undocumented and closed API) and requires an email/password to generate a token that can be reused to play with the API :
GplaySearch googlePlayInstance = new GplaySearch();
DetailsResponse response = googlePlayInstance.getDetailResponse("user#gmail.com",
"password", "com.facebook.katana");
AppDetails appDetails = response.getDocV2().getDetails().getAppDetails();
System.out.println("version name : " + appDetails.getVersionString());
System.out.println("version code : " + appDetails.getVersionCode());
with this method :
public DetailsResponse getDetailResponse(String email,
String password,
String packageName) throws IOException, ApiBuilderException {
// A device definition is required to log in
// See resources for a list of available devices
Properties properties = new Properties();
try {
properties.load(getClass().getClassLoader().getSystemResourceAsStream("device-honami" +
".properties"));
} catch (IOException e) {
System.out.println("device-honami.properties not found");
return null;
}
PropertiesDeviceInfoProvider deviceInfoProvider = new PropertiesDeviceInfoProvider();
deviceInfoProvider.setProperties(properties);
deviceInfoProvider.setLocaleString(Locale.ENGLISH.toString());
// Provide valid google account info
PlayStoreApiBuilder builder = new PlayStoreApiBuilder()
.setDeviceInfoProvider(deviceInfoProvider)
.setHttpClient(new OkHttpClientAdapter())
.setEmail(email)
.setPassword(password);
GooglePlayAPI api = builder.build();
// We are logged in now
// Save and reuse the generated auth token and gsf id,
// unless you want to get banned for frequent relogins
api.getToken();
api.getGsfId();
// API wrapper instance is ready
return api.details(packageName);
}
device-honami.properties is device property file that is required to identify device characteristics. You have some device.properties file sample here
The OkHttpClientAdapter can be found here
Dependencies used to run this example :
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
compile 'com.github.yeriomin:play-store-api:0.19'
compile 'com.squareup.okhttp3:okhttp:3.8.1'
}
Scrap third part apk download sites
http://apk-dl.com
You could get the version name & version code from http://apk-dl.com (of course unofficial) by scraping the page with jsoup for the required package name :
String packageName = "com.facebook.katana";
Document doc = Jsoup.connect("http://apk-dl.com/" + packageName).get();
Elements data = doc.select(".file-list .mdl-menu__item");
if (data.size() > 0) {
System.out.println("full text : " + data.get(0).text());
Pattern pattern = Pattern.compile("(.*)\\s+\\((\\d+)\\)");
Matcher matcher = pattern.matcher(data.get(0).text());
if (matcher.find()) {
System.out.println("version name : " + matcher.group(1));
System.out.println("version code : " + matcher.group(2));
}
}
https://apkpure.com
Another possibility is scrapping https://apkpure.com :
String packageName = "com.facebook.katana";
Elements data = Jsoup.connect("https://apkpure.com/search?q=" + packageName)
.userAgent("Mozilla")
.get().select(".search-dl .search-title a");
if (data.size() > 0) {
Elements data2 = Jsoup.connect("https://apkpure.com" + data.attr("href"))
.userAgent("Mozilla")
.get().select(".faq_cat dd p");
if (data2.size() > 0) {
System.out.println(data2.get(0).text());
Pattern pattern = Pattern.compile("Version:\\s+(.*)\\s+\\((\\d+)\\)");
Matcher matcher = pattern.matcher(data2.get(0).text());
if (matcher.find()) {
System.out.println("version name : " + matcher.group(1));
System.out.println("version code : " + matcher.group(2));
}
}
}
https://api-apk.evozi.com
Also, https://api-apk.evozi.com has an internal JSON api but :
sometimes it doesn't work (return Ops, APK Downloader got access denied when trying to download) mostly for non popular app
it has mechanism in place against scraping bot (random token generated in JS with a random variable name)
The following is returning the version name and code with https://api-apk.evozi.com FWIW :
String packageName = "com.facebook.katana";
String data = Jsoup.connect("https://apps.evozi.com/apk-downloader")
.userAgent("Mozilla")
.execute().body();
String token = "";
String time = "";
Pattern varPattern = Pattern.compile("dedbadfbadc:\\s+(\\w+),");
Pattern timePattern = Pattern.compile("t:\\s+(\\w+),");
Matcher varMatch = varPattern.matcher(data);
Matcher timeMatch = timePattern.matcher(data);
if (varMatch.find()) {
Pattern tokenPattern = Pattern.compile("\\s*var\\s*" + varMatch.group(1) + "\\s*=\\s*'(.*)'.*");
Matcher tokenMatch = tokenPattern.matcher(data);
if (tokenMatch.find()) {
token = tokenMatch.group(1);
}
}
if (timeMatch.find()) {
time = timeMatch.group(1);
}
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("https://api-apk.evozi.com/download");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("t", time));
params.add(new BasicNameValuePair("afedcfdcbdedcafe", packageName));
params.add(new BasicNameValuePair("dedbadfbadc", token));
params.add(new BasicNameValuePair("fetch", "false"));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
JsonElement element = new JsonParser().parse(EntityUtils.toString(response.getEntity()));
JsonObject result = element.getAsJsonObject();
if (result.has("version") && result.has("version_code")) {
System.out.println("version name : " + result.get("version").getAsString());
System.out.println("version code : " + result.get("version_code").getAsInt());
} else {
System.out.println(result);
}
Implementation
You could implement it on a backend of yours that communicates directly with your Java application, this way you could maintain the process of retrieving version code/name if one of the above method fails.
If you are only interested in your own apps, a cleaner solution would be :
to set up a backend which will store all your current app version name / version code
all developer/publisher in your company could share a publish task (gradle task) which will use the Google Play developer API to publish apk and that gradle task would include a call to your backend to store the version code / version name entry when the app is published. The main goal would be to automate the whole publication with storage of the app metadata on your side.
Apart from using JSoup, we can alternatively do pattern matching for getting the app version from playStore.
To match the latest pattern from google playstore ie
<div class="BgcNfc">Current Version</div><span class="htlgb"><div><span class="htlgb">X.X.X</span></div>
we first have to match the above node sequence and then from above sequence get the version value. Below is the code snippet for same:
private String getAppVersion(String patternString, String inputString) {
try{
//Create a pattern
Pattern pattern = Pattern.compile(patternString);
if (null == pattern) {
return null;
}
//Match the pattern string in provided string
Matcher matcher = pattern.matcher(inputString);
if (null != matcher && matcher.find()) {
return matcher.group(1);
}
}catch (PatternSyntaxException ex) {
ex.printStackTrace();
}
return null;
}
private String getPlayStoreAppVersion(String appUrlString) {
final String currentVersion_PatternSeq = "<div[^>]*?>Current\\sVersion</div><span[^>]*?>(.*?)><div[^>]*?>(.*?)><span[^>]*?>(.*?)</span>";
final String appVersion_PatternSeq = "htlgb\">([^<]*)</s";
String playStoreAppVersion = null;
BufferedReader inReader = null;
URLConnection uc = null;
StringBuilder urlData = new StringBuilder();
final URL url = new URL(appUrlString);
uc = url.openConnection();
if(uc == null) {
return null;
}
uc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
inReader = new BufferedReader(new InputStreamReader(uc.getInputStream()));
if (null != inReader) {
String str = "";
while ((str = inReader.readLine()) != null) {
urlData.append(str);
}
}
// Get the current version pattern sequence
String versionString = getAppVersion (currentVersion_PatternSeq, urlData.toString());
if(null == versionString){
return null;
}else{
// get version from "htlgb">X.X.X</span>
playStoreAppVersion = getAppVersion (appVersion_PatternSeq, versionString);
}
return playStoreAppVersion;
}
I got this solved through this. Hope that helps.
Jsoup takes too long, its inefficient, for short easy way with pattermatching:
public class PlayStoreVersionChecker {
public String playStoreVersion = "0.0.0";
OkHttpClient client = new OkHttpClient();
private String execute(String url) throws IOException {
okhttp3.Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public String getPlayStoreVersion() {
try {
String html = execute("https://play.google.com/store/apps/details?id=" + APPIDHERE!!! + "&hl=en");
Pattern blockPattern = Pattern.compile("Current Version.*([0-9]+\\.[0-9]+\\.[0-9]+)</span>");
Matcher blockMatch = blockPattern.matcher(html);
if(blockMatch.find()) {
Pattern versionPattern = Pattern.compile("[0-9]+\\.[0-9]+\\.[0-9]+");
Matcher versionMatch = versionPattern.matcher(blockMatch.group(0));
if(versionMatch.find()) {
playStoreVersion = versionMatch.group(0);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return playStoreVersion;
}
}
public class Store {
private Document document;
private final static String baseURL = "https://play.google.com/store/apps/details?id=";
public static void main(String[] args) {
}
public Store(String packageName) {
try {
document = Jsoup.connect(baseURL + packageName).userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:64.0) Gecko/20100101 Firefox/64.0").get();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public String getTitle() {
return document.select("h1.AHFaub > span").text();
}
public String getDeveloper() {
return document.selectFirst("span.UAO9ie > a").text();
}
public String getCategory() {
Elements elements = document.select("span.UAO9ie > a");
for (Element element : elements) {
if (element.hasAttr("itemprop")) {
return element.text();
}
}
return null;
}
public String getIcon() {
return document.select("div.xSyT2c > img").attr("src");
}
public String getBigIcon() {
return document.select("div.xSyT2c > img").attr("srcset").replace(" 2x", "");
}
public List<String> getScreenshots() {
List<String> screenshots = new ArrayList<>();
Elements img = document.select("div.u3EI9e").select("button.Q4vdJd").select("img");
for (Element src : img) {
if (src.hasAttr("data-src")) {
screenshots.add(src.attr("data-src"));
} else {
screenshots.add(src.attr("src"));
}
}
return screenshots;
}
public List<String> getBigScreenshots() {
List<String> screenshots = new ArrayList<>();
Elements img = document.select("div.u3EI9e").select("button.Q4vdJd").select("img");
for (Element src : img) {
if (src.hasAttr("data-src")) {
screenshots.add(src.attr("data-srcset").replace(" 2x", ""));
} else {
screenshots.add(src.attr("srcset").replace(" 2x", ""));
}
}
return screenshots;
}
public String getDescription() {
return document.select("div.DWPxHb > span").text();
}
public String getRatings() {
return document.select("div.BHMmbe").text();
}
}
Imports
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
This script will return
Category (Personalization for example)
Developer Name
App Icon
App Name
Screenshots (Thumbnail and Full preview)
Description
You can also check the full source code here
I am trying to update a Confluence page using this code:
https://bitbucket.org/jaysee00/confluence-rest-api-example/src/master/src/main/java/com/atlassian/api/examples/Main.java
Code is:
public class Confluence {
/**
* Demonstrates how to update a page using the Conflunence 5.5 REST API.
*/
private static final Logger LOGGER = Logger.getLogger(Confluence.class);;
private static final String BASE_URL = "http://confluence:8080";
private static final String USERNAME = "admin";
private static final String PASSWORD = "admin";
private static final String ENCODING = "utf-8";
private String getContentRestUrl(Long contentId, String[] expansions)
throws UnsupportedEncodingException {
String expand = URLEncoder.encode(StringUtils.join(expansions, ","),
ENCODING);
return String
.format("%s/rest/api/content/%s?expand=%s&os_authType=basic&os_username=%s&os_password=%s",
BASE_URL, contentId, expand,
URLEncoder.encode(USERNAME, ENCODING),
URLEncoder.encode(PASSWORD, ENCODING));
}
public void publish() throws ClientProtocolException, IOException, Exception {
final long pageId = 36307446;
HttpClient client = new DefaultHttpClient();
// Get current page version
String pageObj = null;
HttpEntity pageEntity = null;
try {
String restUrl = getContentRestUrl(pageId,
new String[] { "body.storage", "version", "ancestors" });
HttpGet getPageRequest = new HttpGet(restUrl);
HttpResponse getPageResponse = client.execute(getPageRequest);
pageEntity = getPageResponse.getEntity();
pageObj = IOUtils.toString(pageEntity.getContent());
LOGGER.info("Get Page Request returned "
+ getPageResponse.getStatusLine().toString());
LOGGER.info(pageObj);
LOGGER.info((int)pageObj.trim().charAt(0));
} finally {
if (pageEntity != null) {
EntityUtils.consume(pageEntity);
}
}
// Parse response into JSON
JSONObject page = new JSONObject(pageObj.trim());
// Update page
// The updated value must be Confluence Storage Format
// NOT HTML.
page.getJSONObject("body").getJSONObject("storage")
.put("value", "hello, world");
int currentVersion = page.getJSONObject("version").getInt("number");
page.getJSONObject("version").put("number", currentVersion + 1);
// Send update request
HttpEntity putPageEntity = null;
try {
HttpPut putPageRequest = new HttpPut(getContentRestUrl(pageId,
new String[] {}));
StringEntity entity = new StringEntity(page.toString());
entity.setContentType("application/json");
putPageRequest.setEntity(entity);
HttpResponse putPageResponse = client.execute(putPageRequest);
putPageEntity = putPageResponse.getEntity();
System.out.println("Put Page Request returned "
+ putPageResponse.getStatusLine().toString());
System.out.println("");
System.out.println(IOUtils.toString(putPageEntity.getContent()));
} finally {
EntityUtils.consume(putPageEntity);
}
}
}
The response is alway 'HTTP 404 - Page not found'. I have changed the page id to one I know exists in Confluence.
An exception follows when it tries to parse the response into a JSON object:
avvvaorg.json.JSONException: A JSONObject text must begin with '{' at character 1
at org.json.JSONTokener.syntaxError(JSONTokener.java:496)
at org.json.JSONObject.<init>(JSONObject.java:180)
at org.json.JSONObject.<init>(JSONObject.java:403)
at com.openet.report.publish.Confluence.publish(Confluence.java:74)
at com.openet.report.miner.ReportMiner.generateSummary(ReportMiner.java:268)
at com.openet.report.miner.ReportMiner.runReport(ReportMiner.java:251)
at com.openet.report.miner.ReportMiner.main(ReportMiner.java:138)
Updating confluence pages using REST is not supported by Confluence 4.3.1. The API is much more limited:
https://docs.atlassian.com/atlassian-confluence/REST/4.3.1/
You can however update confluence using XML RPC:
public void publish() throws IOException {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date today = Calendar.getInstance().getTime();
XWikiXmlRpcClient rpc = new XWikiXmlRpcClient(CONFLUENCE_URI);
try {
rpc.login(USER_NAME, PASSWORD);
//The info macro would get rendered an info box in the Page
Page page = new Page();
page.setSpace("Some space");
page.setTitle("Testing XML RPC calls in confluence_" + df.format(today));
//page.setContent(
String s = String.format("||Heading 1||Heading 2||Heading 3||%s|col A1|col A2|col A3|", "\r\n");
page.setContent(s);
page.setParentId(PAGEID);
rpc.storePage(page);
} catch (XmlRpcException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated catch block
}
This requires the following libraries:
import org.apache.xmlrpc.XmlRpcException;
import org.codehaus.swizzle.confluence.Page;
import org.w3c.dom.Document;
import org.xwiki.xmlrpc.XWikiXmlRpcClient;
Note that these libraries are not in the standard maven repository. You will have to update your repository manager (artifactory in my case) to sync with the XWiki maven repo. You will also need the service rocket plugin (https://community.servicerocket.com/servicerocket/topics/the-license-could-not-be-verified-there-is-no-license-certificate-installed-for-customware-scaffolding-plugin-for-confluence) configured correctly on Confluence.
I have a simple GWT app that needs to get some JSON data from another server. I've followed a couple of tutorials to get to this point. When I try to compile it, I get errors
[ERROR] Line 44: No source code is available for type
com.google.gwt.json.client.JSONValue; did you forget to inherit a
required module?
[ERROR] Line 44: No source code is available for type com.google.gwt.json.client.JSONParser; did you forget to inherit a
required module?
[ERROR] Line 46: No source code is available for type com.google.gwt.json.client.JSONArray; did you forget to inherit a
required module?
[ERROR] Line 49: No source code is available for type com.google.gwt.json.client.JSONObject; did you forget to inherit a
required module?
I know I had to add
<inherits name="com.google.gwt.http.HTTP" />
to my .gwt.xml file, but couldn't figure out what to add to get it to recognize the JSON stuff. What am I missing, please?
Relevant code:
private SearchResult[] parseResponse(String jsonResponse) {
ArrayList<SearchResult> retArray = new ArrayList<SearchResult>();
JSONValue jval = JSONParser.parseStrict(jsonResponse);
JSONArray resultArray = jval.isArray();
for(int i=0; i<resultArray.size(); i++) {
JSONObject resultObj = resultArray.get(i).isObject();
String title = resultObj.get("title").isString().stringValue();
JSONArray roleArray = resultObj.get("roles").isArray();
String roleNames = new String();
for(int j=0; j< roleArray.size(); j++) {
if(roleArray.get(j).isNumber().doubleValue() == 1.0) {
// this role is present
String currRole = Constants.getRoleNameForNum(j);
roleNames += currRole;
}
}
SearchResult sr = new SearchResult(title, roleNames);
retArray.add(sr);
}
return retArray.toArray(new SearchResult[0]);
}
private void doSearch() {
clearTable();
final String searchTerms = searchTextBox.getText().toLowerCase().trim();
searchTextBox.setFocus(true);
final int roleNum = roleChooserBox.getSelectedIndex();
final String roleName = roleChooserBox.getItemText(roleNum);
String url = JSON_URL + "?" + ROLE_TXT + roleNum + "&" + QUERY_TXT + "'" + searchTerms + "'";
url = URL.encode(url);
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
Request request = builder.sendRequest(null, new RequestCallback() {
#Override
public void onError(Request request, Throwable exception) {
displayError("Couldnt' retrieve JSON");
}
#Override
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
SearchResult[] results = parseResponse(response.getText());
updateTable(results, roleName);
} else {
displayError("Couldn't retrieve JSON (" + response.getStatusText()
+ ")");
}
}
});
} catch (RequestException e) {
displayError("Couldn't retrieve JSON");
}
`
After further trial and error, adding
<inherits name="com.google.gwt.json.JSON" />
to my .gwt.xml file did the trick. I'm disappointed that I couldn't find any information in the documentation explaining that. It would have saved a lot of time.