Im having some problems deploying my REST api written in C++ on an EC2 instance.
specifically, in my code I do the following:
server.setEndpoint("http://ec2-18-135-114-10.eu-west-2.compute.amazonaws.com:6502");
Which calls the function (a wrapper for the cpprestsdk):
void BasicController::setEndpoint(const std::string & value) {
uri endpointURI(value);
uri_builder endpointBuilder;
endpointBuilder.set_scheme(endpointURI.scheme());
if (endpointURI.host() == "host_auto_ip4") {
endpointBuilder.set_host(NetworkUtils::hostIP4());
}
else if (endpointURI.host() == "host_auto_ip6") {
endpointBuilder.set_host(NetworkUtils::hostIP6());
}
endpointBuilder.set_port(endpointURI.port());
endpointBuilder.set_path(endpointURI.path());
listener = http_listener(endpointBuilder.to_uri());
}
However, I receive the exception `URI Must contain a host name'
Ok, so I try it again with an elastic public IPv4 address:
server.setEndpoint("http://18.135.114.10:6502/");
Again, I get the same error - no host name.
The only case I can get working is on local host, which looks like
server.setEndpoint("http://127.0.1.1:6502:6502/");
Note, this file shows how the exception arises from the cpprestsdk library https://github.com/microsoft/cpprestsdk/blob/master/Release/src/http/client/http_client.cpp
This is probably a very silly question, so I appreciate an kind person giving their help
Solution, change the function to:
void BasicController::setEndpoint(const std::string & value) {
uri endpointURI(value);
uri_builder endpointBuilder;
endpointBuilder.set_scheme(endpointURI.scheme());
if (endpointURI.host() == "host_auto_ip4") {
endpointBuilder.set_host(NetworkUtils::hostIP4());
}
else if (endpointURI.host() == "host_auto_ip6") {
endpointBuilder.set_host(NetworkUtils::hostIP6());
}
else {
endpointBuilder.set_host(endpointURI.host());
}
endpointBuilder.set_port(endpointURI.port());
endpointBuilder.set_path(endpointURI.path());
listener = http_listener(endpointBuilder.to_uri());
}
and use
server.setEndpoint("http://ec2-18-135-114-10.eu-west2.compute.amazonaws.com:6502/");
Related
Has anyone used VivoxCore for unreal engine 4 and know what this error means? I'm not able to really understand what this means. I've tried reading through the source code for vivox, as well as the documentation and that error code (1105) is mentioned nowhere. Also, the company which makes this does not respond to emails, and their public forum is not active. I've tried calling them, emailing them, using the public forum, reading online for answers, and I've found nothing, so stackoverflow is my last option. I hope someone here can help me.
LogVivoxVoiceChat: Warning: onConnectFailed server:https://vdx5.www.vivox.com/api2 error:SIP Backend Required (1105)
Here is my code:
VoiceChat = (FVivoxVoiceChat*)FVivoxVoiceChat::Get();
if (!VoiceChat->IsInitialized())
{
GLog->Log("Is not initialized, trying to initialize.");
VoiceChat->Initialize();
return;
}
if (!VoiceChat->IsConnected())
{
GLog->Log("Is not connected, trying to connect.");
VoiceChat->Connect(FOnVoiceChatConnectCompleteDelegate::CreateLambda([](const FVoiceChatResult& Result)
{
}));
return;
}
FString PlayerName = PlayerState->GetPlayerName();
FString LoginToken = VoiceChat->InsecureGetLoginToken(PlayerName);
if (!VoiceChat->IsLoggedIn())
{
GLog->Log("Is not logged in, trying to login.");
VoiceChat->Login(0, PlayerName, LoginToken, FOnVoiceChatLoginCompleteDelegate::CreateLambda([](const FString& LoggedInPlayerName, const FVoiceChatResult& Result)
{
}));
return;
}
FString ChannelName = "TestChannel";
EVoiceChatChannelType ChannelType = EVoiceChatChannelType::Echo; // Echo for testing.
TOptional<FVoiceChatChannel3dProperties> Channel3dProperties;
FString JoinToken = VoiceChat->InsecureGetJoinToken(ChannelName, ChannelType, Channel3dProperties);
VoiceChat->JoinChannel(ChannelName, JoinToken, ChannelType, FOnVoiceChatChannelJoinCompleteDelegate::CreateLambda([](const FString& JoinedChannelName, const FVoiceChatResult& Result)
{
GLog->Log("JOin Channel successful");
}), Channel3dProperties);
VoiceChat->TransmitToSpecificChannel(ChannelName);
This error means that you have an outdated SDK. The SDK included in UE4 is outdated: it is using backend version 4, but the actual version is 5.
Try disabling the Vivox Interface plugin if it's enabled.
I have an Amazon EC2 with Linux Instance set up and running for my Java Web Application to consume REST requests. The problem is that I am trying to use Google Cloud Vision in this application to recognize violence/nudity in users pictures.
Accessing the EC2 in my Terminal, I set the GOOGLE_APPLICATION_CREDENTIALS by the following command, which I found in the documentation:
export GOOGLE_APPLICATION_CREDENTIALS=<my_json_path.json>
Here comes my first problem: When I restart my server, and ran 'echo $GOOGLE_APPLICATION_CREDENTIALS' the variable is gone. Ok, I set it to the bash_profile and bashrc and now it is ok.
But, when I ran my application, consuming the above code, to get the adult and violence status of my picture, I got the following error:
java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
My code is the following:
Controller:
if(SafeSearchDetection.isSafe(user.getId())) {
if(UserDB.updateUserProfile(user)==false){
throw new SQLException("Failed to Update");
}
} else {
throw new IOException("Explicit Content");
}
SafeSearchDetection.isSafe(int idUser):
String path = IMAGES_PATH + idUser + ".jpg";
try {
mAdultMedicalViolence = detectSafeSearch(path);
if(mAdultMedicalViolence.get(0) > 3)
return false;
else if(mAdultMedicalViolence.get(1) > 3)
return false;
else if(mAdultMedicalViolence.get(2) > 3)
return false;
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return true;
detectSafeSearch(String path):
List<AnnotateImageRequest> requests = new ArrayList<AnnotateImageRequest>();
ArrayList<Integer> adultMedicalViolence = new ArrayList<Integer>();
ByteString imgBytes = ByteString.readFrom(new FileInputStream(path));
Image img = Image.newBuilder().setContent(imgBytes).build();
Feature feat = Feature.newBuilder().setType(Type.SAFE_SEARCH_DETECTION).build();
AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
requests.add(request);
ImageAnnotatorClient client = ImageAnnotatorClient.create();
BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
List<AnnotateImageResponse> responses = response.getResponsesList();
for (AnnotateImageResponse res : responses) {
if (res.hasError()) {
System.out.println("Error: "+res.getError().getMessage()+"\n");
return null;
}
SafeSearchAnnotation annotation = res.getSafeSearchAnnotation();
adultMedicalViolence.add(annotation.getAdultValue());
adultMedicalViolence.add(annotation.getMedicalValue());
adultMedicalViolence.add(annotation.getViolenceValue());
}
for(int content : adultMedicalViolence)
System.out.println(content + "\n");
return adultMedicalViolence;
My REST application was built above a Tomcat8. After no success running the command:
System.getenv("GOOGLE_APPLICATION_CREDENTIALS")
I realize that my problem was in the Environment Variables to Tomcat installation. To correct this, I just created a new file setenv.sh in my /bin with the content:
GOOGLE_APPLICATION_CREDENTIALS=<my_json_path.json>
And it worked!
I have built a dll which includes a class implementing the mongoDB replicaset operations. Here is a summary of the class.
#include "mongo/client/dbclient.h"
mongoimp::mongoimp() {
mongo::client::initialize();
}
mongoimp::~mongoimp() {
mongo::client::shutdown();
}
int mongoimp::queryTRecords() {
string errmsg;
vector<mongo::HostAndPort> hosts = { mongo::HostAndPort("xx-a0.yyyy.com:xxxxx"), mongo::HostAndPort("xx-a1.yyyy.com:xxxxx") };
static mongo::DBClientReplicaSet con("xx", hosts, 0);
con.connect();
con.auth("dbname", "username", "password", errmsg);
auto_ptr<DBClientCursor> cursor = con.query("dbname.t", BSONObj());
BSONObj response;
con.logout("xx", response);
if (cursor->more()) {
BSONObj recordnm = cursor->nextSafe();
return(recordnm.getIntField("lastid"));
} else return(-1);
}
The above code is working. But here are my questions:
1) With the above setting, I can do normal mongoDB operations with the dll but since my application needs to constantly update mongoDB data (close to real-time, up to hundreds a second), I am getting error (No valid replicaset instance servers found) when updating data.
2) Only the server needs to talk to the mongoDB database. So basically I just need one connection to the database. So I want to declare the mongo::DBClientReplicaSet con as a static global variable and connect to it in the class construct function. But it seemed I cannot do it. My application cannot run at all. With that, I constantly get the following error.
Assertion failed: px != 0, file C:\Boost\include\boost-1_62\boost/smart_ptr/scoped_ptr.hpp, line 105
Does anybody know how to solve the problem?
Below is the code I tried:
static mongo::DBClientReplicaSet con("xx", { mongo::HostAndPort("xx-a0.yyyy.com:xxxxx"), mongo::HostAndPort("xx-a1.yyyy.com:xxxxx") }, 0);
mongoimp::mongoimp() {
mongo::client::initialize();
string errmsg;
con.connect();
con.auth("dbname", "username", "password", errmsg);
}
mongoimp::~mongoimp() {
BSONObj response;
con.logout("xx", response);
mongo::client::shutdown();
}
int mongoimp::queryTRecords() {
auto_ptr<DBClientCursor> cursor = con.query("dbname.t", BSONObj());
if (cursor->more()) {
BSONObj recordnm = cursor->nextSafe();
return(recordnm.getIntField("lastid"));
} else return(-1);
}
3) Last question, I noticed there is mongo/client/dbclient_rs.h" file for replicaset. But it seemed I cannot use it. With that, I am getting error for initialize() and auto_ptr cursor. How can I use the file and take full advantage of replicaset features? How can I initialize the relica set if I can use "dbclient_rs.h"? How do I do query and fetch data in that case?
Thanks a lot in advance!
For question No. 2, I remembered the reason for the error:
You need to call mongo::client::initialize before you construct any driver objects, or BSON for that matter.
But how to make that global definition possible, I still need a solution.
I have a method I need to refactor, as F.Promise has been deprecated in Play 2.5. It's pretty readable actually. It sends a request and authenticates via a custom security token and returns true if the response is 200.
public boolean verify(final String xSassToken){
WSRequest request = WS.url(mdVerifyXSassTokenURL)
.setHeader("X-SASS", xSassToken)
.setMethod("GET");
final F.Promise<WSResponse> responsePromise = request.execute();
try {
final WSResponse response = responsePromise.get(10000);
int status = response.getStatus();
if(status == 200 ) { //ok
return true;
}
} catch (Exception e) {
return false;
}
return false;
}
First thing I had to do was change this line:
final F.Promise<WSResponse> responsePromise = request.execute();
To this:
final CompletionStage<WSResponse> responsePromise = request.execute();
However, CompletionStage(T) doesn't have an equivalent get() method so I'm not sure the quickest and easiest way to get a WSResponse that I can verify the status of.
Yes, it does not. At least not directly.
What you are doing is "wrong" in the context of PlayFramework. get is a blocking call and you should avoid blocking as much as possible. That is why WS offers a non blocking API and a way to handle asynchronous results. So, first, you should probably rewrite your verify code to be async:
public CompletionStage<Boolean> verify(final String xSassToken) {
return WS.url(mdVerifyXSassTokenURL)
.setHeader("X-SASS", xSassToken)
.setMethod("GET")
.execute()
.thenApply(response -> response.getStatus() == Http.Status.OK);
}
Notice how I'm using thenApply to return a new a java.util.concurrent.CompletionStage instead of a plain boolean. That means that the code calling verify can also do the same. Per instance, an action at your controller can do something like this:
public class MyController extends Controller {
public CompletionStage<Result> action() {
return verify("whatever").thenApply(success -> {
if (success) return ok("successful request");
else return badRequest("xSassToken was not valid");
});
}
public CompletionStage<Boolean> verify(final String xSassToken) { ... }
}
This way your application will be able to handle a bigger workload without hanging.
Edit:
Since you have to maintain compatibility, this is what I would do to both evolve the design and also to keep code compatible while migrating:
/**
* #param xSassToken the token to be validated
* #return if the token is valid or not
*
* #deprecated Will be removed. Use {#link #verifyToken(String)} instead since it is non blocking.
*/
#Deprecated
public boolean verify(final String xSassToken) {
try {
return verifyToken(xSassToken).toCompletableFuture().get(10, TimeUnit.SECONDS);
} catch (Exception e) {
return false;
}
}
public CompletionStage<Boolean> verifyToken(final String xSassToken) {
return WS.url(mdVerifyXSassTokenURL)
.setHeader("X-SASS", xSassToken)
.setMethod("GET")
.execute()
.thenApply(response -> response.getStatus() == Http.Status.OK);
}
Basically, deprecate the old verify method and suggest users to migrate to new one.
I use wxFTP to make simple client and I'm stucked on how to Upload recursively my folder or do download (which would should be same as delete) from FTP server. I know how to upload single file, make FTP folder and delete file. I will appreciate an article (not necessarily in C/C++) that teaches the concept or if someone can help me here.
Code example will be appreciated but take that as secondary.
Sorry if it already asked and answered, I searched and didn't get anything that answered my question.
I translated the code in answer to this question to C++ and that was it.
Since So won't accept the answer and adds it to comments I have added Java code that I translated to C++. My current code is too long (in that it involves few functions and so not fit for SO I guess!
public void saveFilesToServer(String remoteDest, File localSrc) throws IOException {
FTPClient ftp = new FTPClient();
ftp.connect("ftp.foobar.com");
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
ftp.disconnect();
log.fatal("FTP not disconnected");
}
ftp.login("foo", "qwerty");
log.info("Connected to server .");
log.info(ftp.getReplyString());
ftp.changeWorkingDirectory(remoteDest);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
try {
upload(localSrc, ftp);
}
finally {
ftp.disconnect();
log.info("FTP disconnected");
}
}
public void upload(File src, FTPClient ftp) throws IOException {
if (src.isDirectory()) {
ftp.makeDirectory(src.getName());
ftp.changeWorkingDirectory(src.getName());
for (File file : src.listFiles()) {
upload(file, ftp);
}
ftp.changeToParentDirectory();
}
else {
InputStream srcStream = null;
try {
srcStream = src.toURI().toURL().openStream();
ftp.storeFile(src.getName(), srcStream);
}
finally {
IOUtils.closeQuietly(srcStream);
}
}
}