I tried so hard for a simple line of code that read a file content from enterprise github with oauth token, but could not find a example of such.
I tried https://github.com/jcabi/jcabi-github, but it does not support enterprise github?(maybe I am wrong)
Now i am trying egit:
GitHubClient client = new GitHubClient("enterprise url");
GitHubRequest request = new GitHubRequest();
request.setUri("/readme");
GitHubResponse response = client.get(request);
Then what? I only saw a getBody, maybe I need to parse it with some kinda json library? It has to be simpler..I am expecting something like: repo.get(url).getContent()
Finally figure out by reading source code..
GitHubClient client = new GitHubClient(YOURENTERPRICEURL);
client.setOAuth2Token(token);
// first use token service
RepositoryService repoService = new RepositoryService(client);
try {
Repository repo = repoService.getRepository(USER, REPONAME);
// now contents service
ContentsService contentService = new ContentsService(client);
List<RepositoryContents> test = contentService.getContents(repo, YOURFILENAME);
List<RepositoryContents> contentList = contentService.getContents(repo);
for(RepositoryContents content : test){
String fileConent = content.getContent();
String valueDecoded= new String(Base64.decodeBase64(fileConent.getBytes() ));
System.out.println(valueDecoded);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Related
Based on the link I tried tried working and here is the code I tried out
public static void SendNotification2(String appid, String pinpointEndpointId){
try {
GetEndpointRequest getEndpointRequest = new GetEndpointRequest()
.withApplicationId(appid)
.withEndpointId(pinpointEndpointId);
AmazonPinpoint pinpoint = AmazonPinpointClientBuilder.standard().withRegion(Regions.US_EAST_1).build();
GetEndpointResult endpointResult = pinpoint.getEndpoint(getEndpointRequest);
EndpointResponse endpointResponse = endpointResult.getEndpointResponse();
Map<String, String> data = new HashMap<String, String>();
data.put("message", "test");
DirectMessageConfiguration directMessageConfiguration =
new DirectMessageConfiguration().withGCMMessage(new GCMMessage().withData(data).withSilentPush(true));
AddressConfiguration addressConfiguration = new AddressConfiguration().withChannelType(ChannelType.GCM);
MessageRequest messageRequest = new MessageRequest().withMessageConfiguration(directMessageConfiguration)
.addAddressesEntry(endpointResponse.getAddress(), addressConfiguration);
SendMessagesRequest sendMessagesRequest = new SendMessagesRequest()
.withApplicationId(appid)
.withMessageRequest(messageRequest);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The code executes successfully without any error/exception but i do not see the notification.
However when i post the message from "Direct Messaging" section of pinpoint with the Endpoint Id I am able to see the notification in mobile.
Also using Amazon CLI the Notification message is delivered:
aws --region="us-east-1" pinpoint send-messages --application-id 1fd19ca6fa944a79bdd91beddb4b4f7e --message-request "{\"Context\":{},\"MessageConfiguration\":{\"DefaultMessage\":{\"Body\":\"Test from default message\",\"Substitutions\":{}},\"DefaultPushNotificationMessage\":{},\"APNSMessage\":{},\"GCMMessage\":{\"Data\":{\"message\":\"test\"},\"SilentPush\":true},\"BaiduMessage\":{},\"ADMMessage\":{},\"SMSMessage\":{}},\"Addresses\":{\"cltaa5owuOU:APA91bFOBUB5YRi_Ac6teNmuu19aoFDAByOeoVbqLmY1Yp6cZEp_aueunDU1ZPB6H50GKBfuxu300z-El_sEjxo72crYKnklI-wboxXDk180JICrif0c7R-fR4xFOm5WsQOGUJZPFLG6\":{\"ChannelType\":\"GCM\"}},\"Endpoints\":{}}
Any help will be appreciated.
Thanks
I was following the link
https://access.redhat.com/documentation/en-US/OpenShift_Enterprise/2/pdf/REST_API_Guide/OpenShift_Enterprise-2-REST_API_Guide-en-US.pdf
to build my rest api java application that will deploy a WAR binary file from a web location into my account.
I am getting
InboundJaxrsResponse{context=ClientResponse{method=POST, uri=https://openshift.redhat.com/broker/rest/application/#{myAppID}/deployments, status=422, reason=Unprocessable Entity}} as a response:
where #{myAppID} is the app uuid that I replace here for security
I am using glassfish rest api and my piece of code is:
String url_of_war = "https://code.google.com/p/web-actions/downloads/detail?name=helloworld.war";
WebTarget webtarget;
Client client
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
#Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
};
client = ClientBuilder.newBuilder().sslContext(trustAllCertificates()).hostnameVerifier(hostnameVerifier ).build();
}
URIBuilder uriBuilder = new URIBuilder();
try {
uriBuilder = uriBuilder.setScheme("https").setHost("openshift.redhat.com/broker/rest/").setPath("application/#{myAppId}/deployments");
if (getPort() > 0) {
uriBuilder = uriBuilder.setPort(getPort());
}
URI uri = uriBuilder.build();
webtarget = client.target(uri);
} catch (Exception e) {
String msg = "Could not build URI!";
throw new RuntimeException(msg, e);
}
Invocation.Builder invocationBuilder = webtarget.request(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON_TYPE);
invocationBuilder.header("Authorization", "Basic "+Base64.encodeBase64String("#{myuser}:#{mypass}".getBytes()));
Form form = new Form();
form.param("hot_deploy", "false");
form.param("force_clean_build", "false");
form.param("artifact_url", URLEncoder.encode(url_of_war, "UTF-8"));
Response response = invocationBuilder.post(Entity.form(form));
what am I doing wrong here, I am stuck in this since 30 days with no clue online, i also tried to create openshift/jboss compatible deployment folder where i placed the war file and made available for download as a copmressed .tar.gz file but same problem
your help is highly appreciated.
thank you
Binary deployments need to be in a very specific format, they can't just be a war file (or a zipped war file).
You should check out this blog article (https://blog.openshift.com/using-openshift-without-git/) about using binary deployments on OpenShift Online for further reference. I think it will help you get your code working.
I am working in .NET, using the QuickBooks V2 API to try and fetch a count of the number of Items the user's QBD.
Does anyone have a working example of how to implement the "RecordCountQuery" class to find the # of Items in QBD?
Here is one of my attempt to do so:
//
// Get a record count of the items
//
var qbItemsCount = new RecordCountQuery();
var myResults = qbItemsCount.ExecuteQuery<Item>(_oQBIDataServices.ServiceContext);
Error:
Intuit.Ipp.Exception.IdsException was unhandled by user code
HResult=-2146233088
Message= The RecordCountQuery xml must wrap an existing supported query object. Please modify your query and try again.
Source=""
ErrorCode=-2015
I gather by this that I should be using an different type in the "ExecuteQuery" method like Intuit.Ipp.Data.QBD.ItemQuery. I tried this but got a different error.
So what I am asking for is not necessarily correction to the above code, but a WORKING EXAMPLE of the RecordCountQuery class in .NET.
Thank you.
Edit - Adding .net code
RecordCountQuery query = new RecordCountQuery();
CustomerQuery custQuery = new CustomerQuery();
query.Item1 = custQuery;
List<RecordCount> customerRecordCountQuery = query.ExecuteQuery<RecordCount>(context).ToList();
string customerCount = customerRecordCountQuery[0].Count;
I hv a working java code. Please check if it is useful.
API endpoint - https://services.intuit.com/sb/recordcount/v2/{*relam_id*}
POST body
<RecordCountQuery xmlns="http://www.intuit.com/sb/cdm/v2">
<CustomerQuery/>
</RecordCountQuery>
Response
<?xml version="1.0" encoding="UTF-8"?><!--XML GENERATED by IntuitDataSyncEngine (IDS) using \\SBDomainServices\CDM\branches\3.9.0-rel-1-->
<RestResponse xmlns="http://www.intuit.com/sb/cdm/v2"
xmlns:xdb ="http://xmlns.oracle.com/xdb"
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation ="http://www.intuit.com/sb/cdm/v2 ../common/RestDataFilter.xsd"><RecordCounts>
<RecordCount>
<ObjectName>Customer</ObjectName>
<Count>392</Count>
</RecordCount>
</RecordCounts></RestResponse>
Java Code
public int testGetCount() {
int objectCount = 0;
try {
QBCustomerQuery CustomerQuery = QBObjectFactory.getQBObject(
context, QBCustomerQuery.class);
QBDRecordCountService iRecordCountSer = QBDServiceFactory
.getService(context, QBDRecordCountService.class);
List<QBRecordCountImpl> recordCounts = iRecordCountSer.getCount(
context, CustomerQuery);
Iterator<QBRecordCountImpl> iterator = recordCounts.iterator();
while (iterator.hasNext()) {
QBRecordCountImpl next = iterator.next();
objectCount = Integer.parseInt(next.getCount().toString());
}
System.out.println("Customer count - " + objectCount);
} catch (QBInvalidContextException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return objectCount;
}
Thanks
I'm trying to update a record residing in salesforce table. Im using the Java HttpClient REST API to do the same. Getting an error when we use PATCH to update a record in Salesforce.
PostMethod post = new PostMethod(
instanceUrl + "/services/data/v20.0/sobjects/" +
objectName + "/" + Id + "?_HttpMethod=PATCH"
);
[{"message":"HTTP Method 'PATCH' not allowed. Allowed are HEAD,GET,POST","errorCode":"METHOD_NOT_ALLOWED"}]
Also tried doing the following:
PostMethod post = new PostMethod(
instanceUrl + "/services/data/v20.0/sobjects/" + objectName + "/" + Id)
{
public String getName() { return "PATCH";
}
};
This also returns the same error. We are using apache tomcat with commons-httpclient-3.1.jar library. Please advise on how this can be done.
Please check if you you're using the right implementation of PATCH method, see: Insert or Update (Upsert) a Record Using an External ID.
Also check if your REST URL is correct, probably your objectId is not passed in correctly from Javascript.
The ObjectName is the Name of an Salesforce table i.e. 'Contact'. And Id is the Id of a specific record you want to update in the table.
Similar:
Can I update without an ID?
for Drupal: How to deal with SalesforceException: HTTP Method 'PATCH' not allowed. Allowed are HEAD,GET,POST
As I think you're aware, commons httpclient 3.1 does not have the PATCH method, and the library has been end-of-lifed. In your code above, you're trying to add the HTTP method as a query parameter, which doesn't really make sense.
As seen on SalesForce Developer Board, you can do something like this instead:
HttpClient httpclient = new HttpClient();
PostMethod patch = new PostMethod(url) {
#Override
public String getName() {
return "PATCH";
}
};
ObjectMapper mapper = new ObjectMapper();
StringRequestEntity sre = new StringRequestEntity(mapper.writeValueAsString(data), "application/json", "UTF-8");
patch.setRequestEntity(sre);
httpclient.executeMethod(patch);
This allows you to PATCH without switching out your httpclient library.
I created this method to send the patch request via the Java HttpClient class.
I am using JDK V.13
private static VarHandle Modifiers; // This method and var handler are for patch method
private static void allowMethods(){
// This is the setup for patch method
System.out.println("Ignore following warnings, they showed up cause we are changing some basic variables.");
try {
var lookUp = MethodHandles.privateLookupIn(Field.class, MethodHandles.lookup());
Modifiers = lookUp.findVarHandle(Field.class, "modifiers", int.class);
} catch (IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace();
}
try {
Field methodField = HttpURLConnection.class.getDeclaredField("methods");
methodField.setAccessible(true);
int mods = methodField.getModifiers();
if (Modifier.isFinal(mods)) {
Modifiers.set(methodField, mods & ~Modifier.FINAL);
}
String[] oldMethods = (String[])methodField.get(null);
Set<String> methodsSet = new LinkedHashSet<String>(Arrays.asList(oldMethods));
methodsSet.addAll(Collections.singletonList("PATCH"));
String[] newMethods = methodsSet.toArray(new String[0]);
methodField.set(null, newMethods);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
I'm kind of newbie to this...Basicly I need to run a script to download .csv files from google trends. I wrote the following code according to this reference , the code is like:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>;
nameValuePairs.add(new BasicNameValuePair("Email", "myEmail"));
nameValuePairs
.add(new BasicNameValuePair("Passwd", "myPasswd"));
nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
nameValuePairs.add(new BasicNameValuePair("source",
"Google-cURL-Example"));
nameValuePairs.add(new BasicNameValuePair("service", "xapi"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
if (line.startsWith("SID=")) {
String key = line.substring(4);
// Do something with the key
} catch (Exception e) {
}
I got the information about SID, LSID, Auth, but don't know how to use these information. I guess I should add these cookies in my following request, but don't know exactly how. I wrote another piece of code to connect to the certain URL, but I keep getting this message "You must be signed in to export data from Google Trends." The code is here if it helps:
URL url = new URL(myUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(true);
conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.addRequestProperty("Authorization", "SID"+key);
conn.addRequestProperty("Email", "myEmail");
conn.addRequestProperty("Passwd", "myPasswd");
conn.setReadTimeout(5000);
conn.connect();
I searched around and found few useful information, anyone could help?
Does it have to be in Java? In python, it's as simple as this:
from pyGTrends import pyGTrends
connector = pyGTrends('google username','google password')
connector.download_report(('keyword1', 'keyword2'))
print connector.csv()
You'll need the google trends api library.
If it has to be Java, you may want to look at the HttpClient examples from Apache. "Form based logon" and "client authentication" may both be relevant.
I have just coded this:
https://github.com/elibus/j-google-trends-api
It is an unofficial Java implementation of Google Trends API. You could use it to easily access Google Trends or you might want to have a look at the code to see it works.
Anyway the authentication flow works as follows (all the steps are required):
Fetch https://accounts.google.com/ServiceLoginAuth and parse the GALX id
Post username/password + GALX
Get http://www.google.com
Then you can access Google Trend with relaxed QoS policies for authenticated users.