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.
Related
I try to use Windows Azure like a Storage fom Salesforce.com.
I cheked the documentation and I only can see call the calls to azure rest api from SDK (Java, .Net, JS, etc) examples.
I need integrate Salesforce with Windows Azure Storage but, Azure don't have a SDK for Salesforce.com
From Salesforce.com is allow the calls to rest services but the process to call Azure Rest Services require one o more librarys.
Exameple:
Authentication for the Azure Storage Services require of:
Headers: Date Header and Authorization Header
The Authorization Header require two elments
SharedKey
Account Name
Authorization="[SharedKey|SharedKeyLite] :"
SharedKey and Account Name give a conversion:
HMAC-SHA256 conversion
over UTF-8 encoded
For this convertion the documentation referes to SDK Librarys in others words Java Class or .Net Class type helper that in Salesforce.com not exist.
Please, I need a example to call the authentification service without sdk
Sorry for my bad English.
Visit: https://learn.microsoft.com/en-us/rest/api/storageservices/fileservices/authentication-for-the-azure-storage-services
I need a example to call the authentification service without sdk
We could generate signature string and specify Authorization header for the request of performing Azure storage services without installing SDK. Here is a simple working sample to list the containers, you could refer to my generateAuthorizationHeader function and Authentication for the Azure Storage Services to construct the signature string.
string StorageAccount = "mystorageaccount";
string StorageKey = "my storage key";
string requestMethod = "GET";
string mxdate = "";
string storageServiceVersion = "2014-02-14";
protected void btnlist_Click(object sender, EventArgs e)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(string.Format(CultureInfo.InvariantCulture,
"https://{0}.blob.core.windows.net/?comp=list",
StorageAccount
));
req.Method = requestMethod;
//specify request header
string AuthorizationHeader = generateAuthorizationHeader();
req.Headers.Add("Authorization", AuthorizationHeader);
req.Headers.Add("x-ms-date", mxdate);
req.Headers.Add("x-ms-version", storageServiceVersion);
using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
{
var stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string content = reader.ReadToEnd();
StringReader theReader = new StringReader(content);
DataSet theDataSet = new DataSet();
theDataSet.ReadXml(theReader);
DataTable dt = theDataSet.Tables[2];
}
}
public string generateAuthorizationHeader()
{
mxdate = DateTime.UtcNow.ToString("R");
string canonicalizedHeaders = string.Format(
"x-ms-date:{0}\nx-ms-version:{1}",
mxdate,
storageServiceVersion);
string canonicalizedResource = string.Format("/{0}/\ncomp:list", StorageAccount);
string stringToSign = string.Format(
"{0}\n\n\n\n\n\n\n\n\n\n\n\n{1}\n{2}",
requestMethod,
canonicalizedHeaders,
canonicalizedResource);
HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(StorageKey));
string signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
String authorization = String.Format("{0} {1}:{2}",
"SharedKey",
StorageAccount,
signature
);
return authorization;
}
Besides, please refer to Azure Storage Services REST API Reference to know more about programmatic access to Azure Storage Services via REST APIs.
I find a way to solve this.
You should use Shared Sing, here explain me:
Enter to Portal Azure
Open the Account Storage
In the General Information click on "Share sing access"
Enable all permissions that you need (In my case only Enable "File")
Enable all resources permission that you need (In my case onl Enable "Service, Container and Object")
Define and Start Date and End Date (This is the space of time that Shared Key will be valid)
Define protocol type (In my case use HTTPS)
Clic on "Generate SAS" button
After this process you will get a token like this:
?sv=2016-05-31&ss=f&srt=sco&sp=rwdlc&se=2017-11-28T04:29:49Z&st=2017-02-18T20:29:49Z&spr=https&sig=rt7Loxo1MHGJqp0F6ryLhYAmOdRreyiYT418ybDN2OI%3D
You have to use this Token like Autentication
Example Call Code List a Content:
public with sharing class CallAzureRestDemo {
public string token = '&sv=2016-05-31&ss=f&srt=sco&sp=rwdlc&se=2017-02-19T04:00:44Z&st=2017-02-18T20:00:44Z&spr=https&sig=GTWGQc5GOAvQ0BIMxMbwUpgag5AmUVjrfZc56nHkhjI%3D';
//public Integer batchSize;
public CallAzureRestDemo(){}
public void getlistcontent(String endpoint)
{
// Create HTTP GET request
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint(endpoint+token);
Http http = new Http();
HTTPResponse res;
System.debug(LoggingLevel.INFO, '##RESPONSE: '+res);
// only do this if not running in a test method
if(!Test.isRunningTest())
{
System.debug(LoggingLevel.INFO, 'Sending the message to Azure');
res = http.send(req);
System.debug(LoggingLevel.INFO, 'http.send result status: ' + res.getStatus());
}
else
{
System.debug(LoggingLevel.INFO, 'Running in a test so not sending the message to Azure');
}
}
}
Example TestMethod:
#isTest
private class Test_CallAzureRestDemo {
static testMethod void myUnitTest() {
CallAzureRestDemo oRest = new CallAzureRestDemo();
try{
//Call the method and set endpoint
oRest.getlistcontent('https://accountstoragecomex.file.core.windows.net/?comp=list');
}catch(Exception e){
System.debug('##'+e);
}
}
}
Example to Response:
20:15:47.64 (79388244)|CALLOUT_REQUEST|[100]|System.HttpRequest[Endpoint=https://accountstoragecomex.file.core.windows.net/?comp=list&sv=2016-05-31&ss=f&srt=sco&sp=rwdlc&se=2017-02-19T04:00:44Z&st=2017-02-18T20:00:44Z&spr=https&sig=GTWGQc5GOAvQ0BIMxMbwUpgag5AmUVjrfZc56nHkhjI%3D, Method=GET]
20:15:47.64 (395755012)|CALLOUT_RESPONSE|[100]|System.HttpResponse[Status=OK, StatusCode=200]
Example Call Service "FILE - Get List Share"
Call To List Content
One more time, Sorry for my bad english.
Can any body share a java client code which makes a Rest calls to IBM Cloud BPM. Basically I want to know how to authenticate IBM Cloud BPM.
I tried the following code but it is not working
String user_info_url="https://ustrial01.bpm.ibmcloud.com/bpm/dev/rest/bpm/wle/v1/user/current?includeInternalMemberships=true&parts=all";
logger.info("user_info_url :" + user_info_url);
HttpClient client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet(user_info_url);
String authData = "rajesh.kohir123#gmail.com" + ":" + "password";
String encoded = new sun.misc.BASE64Encoder().encode(authData .getBytes());
get.setHeader("Content-Type", "application/json");
get.setHeader("Accept", "application/json");
get.setHeader("Authorization", "Basic " + encoded);
HttpResponse cgResponse = client.execute(get);
if(cgResponse.getStatusLine().getStatusCode() != 200) {
logger.info("IBM Rest call failed");
}
if(cgResponse.getStatusLine().getStatusCode() == 200) {
logger.info("IBM Rest call Succeded");
String content = EntityUtils.toString(cgResponse.getEntity());
logger.info(content);
}
Any help is greatly appreciated
I ran your code and just made the changes in URL. It worked. I hope this helps you.
Following is the URL I used to execute an exposed service :
https://vhost031.bpm.ibmcloud.com/bpm/dev/rest/bpm/wle/v1/service/OMS#Greetings
I used the following code to add the parameters :
String parameters = "{'name':'pramod'}";
URIBuilder builder = new URIBuilder("https://vhost031.bpm.ibmcloud.com/bpm/dev/rest/bpm/wle/v1/service/OMS#Greetings");
List nameValuePairs = new ArrayList();
nameValuePairs.add(new BasicNameValuePair("action", "start"));
nameValuePairs.add(new BasicNameValuePair("params", parameters));
nameValuePairs.add(new BasicNameValuePair("createTask", "false"));
nameValuePairs.add(new BasicNameValuePair("parts", "all"));
builder.setParameters(nameValuePairs);
HttpGet get = new HttpGet(builder.build());
Download the download.zip form the post.
Look at the SampleBPDProcessTests.java - Line no 103
JSONObject results = bpmClient.runBPD(BPD_ID, PROCESS_APP_ID, bpdArgs);
The actual Java Code for Rest call is available as part of "bpm-rest-client.jar"
Try this concept.
Sample Java code to start a process:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://ustrial03.bpm.ibmcloud.com:443/bpm/dev/rest/bpm/wle/v1/process?
processAppId=3u092jr02j-djaodaj.u092302c166c1&bpdId=25.jklaklaa-539a-4150-
b63e-9ef94e96e521&action=start")
.put(null)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.addHeader("Accept", "application/json")
.addHeader("Connection", "keep-alive")
.addHeader("Authorization", "Basic YXJrYX24223232hQGRlbG9pdHRlLmNvbTpkZWZjb240QA==")
.addHeader("Cache-Control", "no-cache")
.addHeader("Postman-Token", "f46c1525-7a75-954c-9265-bb2b21a57f16")
.build();
Response response = client.newCall(request).execute();
A full explanation of REST integration with BPM Cloud can be found in my answer at:
How to run IBM BPM Rest api call from Post man client
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();
}
So I am new to GWT and am not sure what the best programming practices are for what I am trying to do. In my web application the user will be able to upload a data file, my application needs to be able to access this file, do some stuff to it, and then let the user download the manipulated file.
So far I have been able to successfully upload a file with an upload servlet with this doPost method:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);
fileUpload.setSizeMax(FILE_SIZE_LIMIT);
List<FileItem> items = fileUpload.parseRequest(req);
for (FileItem item : items) {
if (item.isFormField()) {
logger.log(Level.INFO, "Received form field:");
logger.log(Level.INFO, "Name: " + item.getFieldName());
logger.log(Level.INFO, "Value: " + item.getString());
} else {
logger.log(Level.INFO, "Received file:");
logger.log(Level.INFO, "Name: " + item.getName());
logger.log(Level.INFO, "Size: " + item.getSize());
}
if (!item.isFormField()) {
if (item.getSize() > FILE_SIZE_LIMIT) {
resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, "File size exceeds limit");
return;
}
String fileName = item.getName();
if (fileName != null) {
fileName = FilenameUtils.getName(fileName);
}
fileName = getServletContext().getRealPath("/uploadedFiles/" + fileName);
byte[] data = item.get();
FileOutputStream fileOutSt = new FileOutputStream(fileName);
fileOutSt.write(data);
fileOutSt.close();
if (!item.isInMemory())
item.delete();
}
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e);
throw new ServletException(e);
}
}
When I look in my war folder, the uploadedFiles folder is created successfully and files are put there.
At this point I am a bit stuck, I have been researching but cannot seem to find a clear concise answer on what is the best way for me to access the uploaded files on the client side in order to manipulate them and then allow the user to download them. Maybe I am approaching this wrong, I am not sure. If someone could point me in the right direction or show me some good examples of the right way to do things that would be great, thanks.
To access the file in client side you need a new servlet or the same you are using with a doGet method.
The client should ask for the file via an Anchor or an Image depending on the file type but adding a parameter so as the server is able to identify the file. Normally you can use the name of the FileInput you used for uploading or maybe you could return a tag from the server.
I would recommend to you to take a try to gwt-upload, it would save a lot of time to you.
I solved my problem. When the file was successfully uploaded, I stored the file name. Later I used a RPC to access the file on the server. I passed the file name to the RPC so that it knows what file I am working on, then it looks for that file in the upload folder. So I can create the java file like this,
File file = new File((this.getServletContext().getRealPath("uploadedFiles") + File.separator + fileName));
and manipulate it how I see fit.
I'm having problems when I try to do a HTTP Post in my Plugin (in PostUpdate). I'm getting the "The Operation Has Timed Out"-Error...
Here below you have the C#-code :
//PUBLISH TO ROBAROV
WebRequest webRequest = WebRequest.Create(newUri);
webRequest.Timeout = 2000;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
Stream os = null;
try
{
webRequest.ContentLength = bytes.Length;
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
}
catch (WebException ex)
{
throw new Exception(ex.Message);
}
finally
{
if (os != null)
{
os.Close();
}
}
//ERROR HAPPENS HERE
string responseText = "";
try
{ // get the response
WebResponse webResponse = webRequest.GetResponse();
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
responseText = sr.ReadToEnd().Trim();
}
catch (WebException ex)
{
throw new Exception("Error with response : " + ex.Message);
}
The error happens when I'm trying to get the response => webRequest.GetResponse();!
I've tried the code out in a simple "Class"-library and there it works like a charm! Is there something I'm doing wrong? The HTTP Post is to a webpage that's not in the same domain....
UPDATE :
Same happens when I do the following with a webclient... And it works in a normal "Console"-application :
private string HttpPostTest(string URL)
{
WebClient webClient = new WebClient();
System.Collections.Specialized.NameValueCollection formData = new System.Collections.Specialized.NameValueCollection();
formData["state"] = "yes";
byte[] responseBytes = webClient.UploadValues(URL, "POST", formData);
string Result = Encoding.UTF8.GetString(responseBytes);
return Result;
}
I'm getting the following error in the "Event Viewer" :
Inner Exception: System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Crm.Setup.DiffBuilder, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
It looks like it can't find a CRM assembly: Microsoft.Crm.Setup.DiffBuilder.dll, is this something which you explicitly call methods from? If so I'd check if the assembly is registered with the plug-in (some instructions below). If not then there are some errors associated with this library from roll up 6, which roll up are you using? You may consider roll up 7 if you are not using that.
Is your plug-in registered in the database or on disk?
If registered on disk then you will need your external assembly in the /server/bin/assembly directory under the CRM installation folder.
If it is registered in the database and you are including a custom external assembly (the error suggests that an assembly cannot be loaded, so this sounds possible), then you will have to ILMerge your assemblies before registering them in the database. This would explain why it works for your local console application and not when run as a plug-in.
If this is the case then you can follow a script like below to ILMerge and register your 'combined' assembly:-
http://www.2wconsulting.com/2010/11/using-ilmerge-with-crm-plugin-assemblies/