How do you include a port number when using Embarcadero C++ TRESTRequest - rest

Here's the compulsory code snippet:
UnicodeString SeizonshaRest::doStuff(UnicodeString strEmail, UnicodeString strPassword)
{
restclient->BaseURL = "http://localhost";
restrequest->Resource = ":60800/home/login";
restrequest->Params->AddItem("email", strEmail);
restrequest->Params->AddItem("password", strPassword);
UnicodeString strId;
restrequest->Execute();
strId = respMain->Content;
return strId;
}
I know this is the wrong way to do it.
What's the correct way to add a port number please?

The port number is attached to the server hostname that the client connects to, not to the resource that the client requests once connected.
Try this:
restclient->BaseURL = "http://localhost:60800";
restrequest->Resource = "home/login";
If you read the documentation, it says:
TCustomRESTClient.BaseURL
Specifies the base URL for all API calls.
All resources and parameters of your requests will be appended to this URL. Please, be aware that a trailing forward slash ("/") is added to the value of the BaseURL property.
TCustomRESTRequest.Resource
This property is added to the base URL to establish a complete URL for the HTTP request.
Important: The Resource value should meet the following limitations:
Does not include the scheme or domain mame.
Does not include the leading slash.
So, your original code would have produced the request URL as http://localhost/:60800/home/login, but the correct URL is http://localhost:60800/home/login instead.

I really wanted to post my code as I can find NO examples of this ANYWHERE
contact.h:
#ifndef contactH
#define contactH
#include <System.Classes.hpp>
#include <IPPeerClient.hpp>
#include <REST.Client.hpp>
//---------------------------------------------------------------------------
class contact;
class contact
{
public:
contact();
~contact() {};
String connect(String query);
TRESTClient *clientContact;
TRESTRequest *reqContact;
TRESTResponse *respContact;
private:
};
contact.cpp:
String contact::connect(String query)
{
clientContact = new TRESTClient(NULL);
reqContact = new TRESTRequest(NULL);
respContact = new TRESTResponse(NULL);
reqContact->Client = clientContact;
reqContact->Response = respContact;
UnicodeString strUrl = "http://myawesomeurl:5150";
reqContact.Resource = query;
clientContact->BaseURL = strUrl;
UnicodeString strInspect;
reqContact->Execute();
strInspect = respContact->Content;
return strInspect;
}
I hope this helps someone as stuck for examples as I was.

Related

coinbase api always 401 unauthorized

I have waited faithfully for well over 48 hours since generating api keys as suggested and no matter what I do, every coinbase api call gives 401 Unauthorized
I have checked basic non-authentication required calls like /time and /exchange_rates and they work fine
I am using coinbase and not coinbase pro so this is a simple api key and header based call
Have triple checked the hashing and decoding requirements, and nothing is apparent as an issue
Rather than asking to resolve coding problems from the standard examples, the ask is either
Is anyone aware of general authorization issues with the coinbase service right now ? (nothing published by coinbase)
Is there anything outside of the general code samples and documentation that needs to be done to get this damn thing authorizing ?
Any and all help appreciated.
References used :
https://developers.coinbase.com/docs/wallet/api-key-authentication#
Have added the basic code used for completeness here :
// Remove insecure protocols (SSL3, TLS 1.0, TLS 1.1)
ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3;
ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Tls;
ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Tls11;
// Add TLS 1.2
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
HttpClient client = new HttpClient();
string sTimeStamp = Convert.ToInt64(DateTime.Now.Ticks).ToString("F0", CultureInfo.InvariantCulture);
client.BaseAddress = new Uri(sUrl + sOperation);
var convertedString = Convert.FromBase64String(sAPI_EXCHANGE_SECRET);
var prehash = sTimeStamp + "GET" + sOperation + ""; // no content for now
string sSignature = HashString(prehash, convertedString);
// bunch of headers for coinbase
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("User-Agent", "CryptoAppClient"); // arbitrary user agent name
client.DefaultRequestHeaders.Add("CB-ACCESS-KEY", sAPI_EXCHANGE_KEY);
client.DefaultRequestHeaders.Add("CB-VERSION", sAPI_EXCHANGE_VERSION);
client.DefaultRequestHeaders.Add("CB-ACCESS-SIGN", sSignature);
client.DefaultRequestHeaders.Add("CB-ACCESS-TIMESTAMP", sTimeStamp);
// set up the actual call
HttpResponseMessage response = client.GetAsync("").Result;
.....
//----------------------------------------------------------------------------
private string HashString(string str, byte[] secret)
{
var bytes = System.Text.Encoding.UTF8.GetBytes(str);
using (var hmaccsha = new HMACSHA256(secret))
{
return Convert.ToBase64String(hmaccsha.ComputeHash(bytes));
}
}
Finally go it sorted, combination of timestamp value wrong and the right .net functions to encrypt the message

Error 403 - Forbidden on Loading Open Street Map to Win Form with GMap.Net and C#

Trying to load OSM on windows Form using C# and GMap.Net I am getting this error
Exception:The remote server returned an error: (403) Forbidden
private void Form1_Load(object sender, EventArgs e)
{
gMapControl1.DragButton = MouseButtons.Left;
gMapControl1.CanDragMap = true;
gMapControl1.MapProvider = GMapProviders.OpenStreetMap;
gMapControl1.Position = new GMap.NET.PointLatLng(54.6961334816182, 25.2985095977783);
gMapControl1.MinZoom = 0;
gMapControl1.MaxZoom = 24;
gMapControl1.Zoom = 9;
gMapControl1.AutoScroll = true;
}
Can you please let me know why this is happening and how I can fix it?
don't forget to set the instance mode to server/cache and set it to the instance of the open street map provider instead of 'GMapProviders.OpenStreetMap'
GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerAndCache;
gMapControl1.MapProvider = GMap.NET.MapProviders.OpenStreetMapProvider.Instance;
It could also be your web proxy settings, see
https://stackoverflow.com/a/19609539/2368681
"Hi,
All libraries that send a fake user-agent and other faked headers to make the requests appear as if they are coming from web browsers are being blocked. Fix the headers and set a real User-Agent to identify your app and the requests will work again.
Please review our usage policy:
https://operations.osmfoundation.org/policies/tiles/ "
This is verbatim reply from OSM.
https://github.com/judero01col/GMap.NET/pull/45 is being used to track this issue. And hopefully a fix will be merged in a a day or two.
I changed Map Provider from "OpenStreetMapProvider" to "GoogleMapProvider" and the error disappeared.
GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerAndCache;
mapView.MapProvider = GMap.NET.MapProviders.GoogleMapProvider.Instance;

how to get url from link inside the notification email

I am looking to write a script with web driver where I need to wait for the notification email and then need to get the URL from link of that email.
Pattern for recognising a URL (based off RFC 3986)
private static final Pattern urlPattern = Pattern.compile(
"(?:^|[\\W])((ht|f)tp(s?):\\/\\/|www\\.)"
+ "(([\\w\\-]+\\.){1,}?([\\w\\-.~]+\\/?)*"
+ "[\\p{Alnum}.,%_=?&#\\-+()\\[\\]\\*$~#!:/{};']*)",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
//Usage: email content goes as input here..
Matcher matcher = urlPattern.matcher("foo bar http://example.com baz");
while (matcher.find()) {
int matchOffsetStart = matcher.start(1);
int matchOffsetEnd = matcher.end();
// now you have the offsets of a URL match
}
UPDATE:
If you want to read message header like FROM and so on, I would suggest to use Mime4J
Message msg = new Message(new FileInputStream("mime.msg"));
msg.getFrom() would give you from. Similarly you can extract whatever you want.
Refer for more details here

Wicket 6.x https with other host

I have a webpage with a area where users can login. This area
www.host.com/mypage/myarea
should be under https.
The problem is that my https is running on a another host:
www.something-foo.host.com/mypage/myarea
. (loadbalancer stuff...??? I dont know why)
My try is to annotate the Pages with #RequireHttps, an than rewrite the urls of the Pages.
But how and where? Has someone please an example?
Thanks for your help.
Well if you really want to this with Wicket your best option would be to write an implementation of IRequestMapperDelegate and set them during the onInit() process of your WicketApplication.
To give you an idea how to do this I've written an example of raping the HttpsMapper of Wicket:
setRootRequestMapper(new HttpsMapper(getRootRequestMapper(), new HttpsConfig(8080, 8443)) {
private final static String SUBDOMAIN = "www.something-foo.";
#Override
protected Scheme getSchemeOf(Request request) {
HttpServletRequest req = (HttpServletRequest) ((WebRequest) request).getContainerRequest();
// well that's basically cheating and not so nice... but we're not allowed to overwrite mapRequest()
// but that means that every request that doesn't start with the subdomain will be treated as HTTP aka
// insecure.
if (req.getServerName().startsWith(SUBDOMAIN) == false) {
return Scheme.HTTP;
}
return super.getSchemeOf(request);
}
#Override
protected String createRedirectUrl(IRequestHandler handler, Request request, Scheme scheme) {
// stolen from super implementation
HttpServletRequest req = (HttpServletRequest) ((WebRequest) request).getContainerRequest();
String url = scheme.urlName() + "://";
// except the part where we insert the subdomain
url += SUBDOMAIN;
url += req.getServerName();
if (!scheme.usesStandardPort(getConfig())) {
url += ":" + scheme.getPort(getConfig());
}
url += req.getRequestURI();
if (req.getQueryString() != null) {
url += "?" + req.getQueryString();
}
return url;
}
});
Depending on your question I can't really determine if this is a good solution ... it really depends on how many frameworks are working on top of Wicket. Since you didn't mention anything else I'm assuming none.

Sending protocol buffers via REST

I am trying to implement protocol buffers for client/server using REST.
I am still a bit confused if I need to send protocol buffers request in byte format?
I mean, in my client code, do I need to serialize object to byte array?
For example
protoRequest.build.toByteArray()
And in the server, do I need to c
#POST
#Consumes("application/octet-stream")
public byte[] processProtoRequest(byte[] protoRequest) {
ProtoRequest.Builder request = ProtoRequest.newBuilder();
request.mergeFrom(protoRequest)
}
Is this the right thing to do?
Thanks
David
You can use input stream for this purpose. Server Side Code will be look like the below code
#POST
public Response processProtoRequest(#Context HttpServletRequest req) {
ProtoRequest protoRequestObj = ProtoRequest.parseFrom(req.getInputStream());
///process protoRequestObj and convert into byte arry and send to clinet
return Response.ok(protoRequestObj.toByteArray(),
MediaType.APPLICATION_OCTET_STREAM).status(200).build();
}
client side will look like this:
ProtoRequest protoRequestObj = ProtoRequest.newBuilder(). //protocol buffer object
setSessionId(id).
setName("l070020").
build();
DefaultHttpClinet httpClinet = new DefaultHttpClinet();
HttpPost request = new HttpPost("http://localhost:8080/maven.work/service/mainServices/protoRequest");
request.addHeader("accept","application/octet-stream");
request.setEntity(protoRequestObj.toByteArray());
HttpResponse response = httpClient.execute(request);
I have written a Step by Step tutorial about how to produce/consume a protocol buffer stream in a web service, using Jersey as the client JAX-RS implementation. I hope it will help you. :)
Server side :
#GET
#Path("/{galaxy}")
#Consumes(MediaType.TEXT_HTML)
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getInfo(#PathParam("galaxy") String galaxyName){
if(StringUtils.equalsIgnoreCase("MilkyWay", StringUtils.remove(galaxyName, ' '))){
// The following method would call the DTO Galaxy builders.
Galaxy milkyWay = MilkyWayFactory.createGalaxy();
// This is the important line for you where where the generated toByteArray() method takes responsibility of serializing the instance into a Protobuf format stream
return Response.ok(milkyWay.toByteArray(),MediaType.APPLICATION_OCTET_STREAM).status(200).build();
}
return Response.status(Status.NOT_FOUND).build();
}
Client side :
String serverContext = "learning-protobuf3-ws-service";
String servicePath = "ws/universe/milkyway";
String serviceHost = "localhost";
Integer servicePort = 8080;
javax.ws.rs.client.Client client = javax.ws.rs.client.ClientBuilder.newClient();
javax.ws.rs.client.WebTarget target = client.target("http://"+serviceHost+":"+servicePort+"/"+serverContext)
.path(servicePath);
InputStream galaxyByteString = target.request(MediaType.TEXT_HTML)
.header("accept",MediaType.APPLICATION_OCTET_STREAM)
.get(InputStream.class);
Galaxy galaxy = Galaxy.parseFrom(IOUtils.toByteArray(galaxyByteString));
You could encode the result of SerializeToString using base64.