How to get URL of deployed App Engine Project - java

I have deployed my app in App Engine using maven (https://cloud.google.com/appengine/docs/flexible/java/using-maven)
How can I programmatically get the URL of the APP?
I know it follows this format https://PROJECT_ID.REGION_ID.r.appspot.com. However, I do not know the region Id. If there is no way to get the URL, is there a way to get the region ID?
edit
I found this to be useful for this purpose:
https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps/get

This command will get the URL of the deployed App Engine:
gcloud app browse

I'm using this code on my production env to identify the URL. Getting of REGIONID dynamically using code is not possible for now. At least in my current SDK it is not available. Someday they will do that.
For now REGIONID.r is not mandatory in the URL as per the Google documentation. It might be required in future projects. This code will work for you.
https://cloud.google.com/appengine/docs/standard/python/how-requests-are-routed#region-id
import com.google.appengine.api.modules.ModulesServiceFactory;
import com.google.appengine.api.utils.SystemProperty;
import com.google.apphosting.api.ApiProxy;
public static void main(String[] args) {
String projectId = ApiProxy.getCurrentEnvironment().getAppId().indexOf("~")>-1?
ApiProxy.getCurrentEnvironment().getAppId().split("~")[1]:ApiProxy.getCurrentEnvironment().getAppId();
ModulesService ssf = ModulesServiceFactory.getModulesService();
String url = null;
if(SystemProperty.environment.value()!=SystemProperty.Environment.Value.Production) {
url = "http://localhost:PORT_NUMBER";
}
if(ssf.getDefaultVersion(ssf.getCurrentModule()).equals(ssf.getCurrentVersion())) {
//This is default version
url = "https://" + projectId + ".appspot.com";
}
//The URL with the current version ID
url = "https://" + ssf.getCurrentVersion() + "-dot-" + projectId + ".appspot.com";
//The URL with the module name, current version name
url = "https://" + ssf.getCurrentVersion() + "-dot-" + ssf.getCurrentModule() + "-dot-" + projectId + ".appspot.com";
}

Related

azure storage metrics at container level

I am referring to documentation provided by azure at
https://learn.microsoft.com/en-us/azure/storage/common/storage-metrics-in-azure-monitor#read-metric-values-with-the-net-sdk
I have made changes and make the code work for java using azure-mgmt-monitor dependency. Here is the code
public void listStorageMetricDefinition() {
String resourceId = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{storageAccountName}";
String subscriptionId = "*****************************";
String tenantId = "*****************************";
String applicationId = "*****************************";
String accessKey = "*****************************";
ApplicationTokenCredentials credentials = (ApplicationTokenCredentials) new ApplicationTokenCredentials(
applicationId, tenantId, accessKey, AzureEnvironment.AZURE).withDefaultSubscriptionId(subscriptionId);
MonitorManagementClientImpl clientImpl = new MonitorManagementClientImpl(credentials);
Date startTime = DateTime.now().minusMinutes(30).toDate();
Date endTime = DateTime.now().toDate();
//DateTime must be in below format
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String startInterval = dateFormat.format(startTime);
String endInterval = dateFormat.format(endTime);
String timespan = startInterval + "/" + endInterval;
Period interval = Period.minutes(1);
String metricNames = "Egress";
String aggregation = "Total";
Integer top = null;
String orderby = null;
String filter = null;
String metricNamespace = null;
ResponseInner response = clientImpl.metrics().list(resourceId, timespan, interval, metricNames, aggregation,
top, orderby, filter, null, metricNamespace);
List<MetricInner> value = response.value();
for (MetricInner metric : value) {
System.out.println("id " + metric.id());
System.out.println("name " + metric.name().value());
System.out.println("type " + metric.type());
System.out.println("unit " + metric.unit());
List<TimeSeriesElement> timeseries = metric.timeseries();
timeseries.forEach(ts -> {
ts.data().forEach(dt -> {
System.out.println(dt.timeStamp() + "--" + dt.total());
});
});
}
}
By using above I am able to read the metrics values at storage account level, but how can I find the metrics at container level? e.g. if I have 3 containers inside my storage account, I need to find the metrics for each container instead for complete storage account.
Please suggest if there are other ways to find metrics at container level.
There is not direct way of doing this, but one can achieve this by configuring monitoring for the storage account. Follow the below link to configure monitoring,
https://learn.microsoft.com/en-us/azure/storage/common/storage-monitor-storage-account
Once storage account is configured for monitoring, it will create a new container with name $logs in your storage account. This new container is not visible in azure portal but you can view and explore this new container using Azure Storage Explorer tool. The link to download the tool is given below.
https://azure.microsoft.com/en-us/features/storage-explorer/
The logs inside the $logs container are segregated on the basis of date and time in separate folders.
/blob/yyyy/MM/dd/HHmm/000000.log
/blob/yyyy/MM/dd/HHmm/000001.log
where mm is always going to be 00.
The schema for logs can be found in azure documentation at location.
https://learn.microsoft.com/en-us/rest/api/storageservices/storage-analytics-log-format
One can read the log file using the schema format and create useful metrics out if it.

Adding an attachment on Azure CosmosDB

I am looking for some help on how to add an attachment on CosmosDB. Here is the little background.
Our application is currently on IBM Bluemix and we are using CloudantDB. We use CloudanDB to store attachments (PDF file). We are no moving to Azure PaaS App Service and planning to use CosmosDB. I am looking for help on how to create an attachment on CosmosDB using Java API. What API do I need to use? I want to do a small POC.
Thanks,
Well Personally i feel In Azure, if you go want to put files into documentDb, you will pay high for the query cost. Instead it would be normal practice to use Azure blob and save the link in a field, and then return url if its public or binary data if you want it to be secured.
However, You could store it using
var myDoc = new { id = "42", Name = "Max", City="Aberdeen" }; // this is the document you are trying to save
var attachmentStream = File.OpenRead("c:/Path/To/File.pdf"); // this is the document stream you are attaching
var client = await GetClientAsync();
var createUrl = UriFactory.CreateDocumentCollectionUri(DatabaseName, CollectionName);
Document document = await client.CreateDocumentAsync(createUrl, myDoc);
await client.CreateAttachmentAsync(document.SelfLink, attachmentStream, new MediaOptions()
{
ContentType = "application/pdf", // your application type
Slug = "78", // this is actually attachment ID
});
WORKING WITH ATTACHMENTS
I have answered a similar question here
What client API I can use?
You could follow the cosmos db java sdk to CRUD attachment.
import com.microsoft.azure.documentdb.*;
import java.util.UUID;
public class CreateAttachment {
// Replace with your DocumentDB end point and master key.
private static final String END_POINT = "***";
private static final String MASTER_KEY = "***";
public static void main(String[] args) throws Exception, DocumentClientException {
DocumentClient documentClient = new DocumentClient(END_POINT,
MASTER_KEY, ConnectionPolicy.GetDefault(),
ConsistencyLevel.Session);
String uuid = UUID.randomUUID().toString();
Attachment attachment = getAttachmentDefinition(uuid, "application/text");
RequestOptions options = new RequestOptions();
ResourceResponse<Attachment> attachmentResourceResponse = documentClient.createAttachment(getDocumentLink(), attachment, options);
}
private static Attachment getAttachmentDefinition(String uuid, String type) {
return new Attachment(String.format(
"{" +
" 'id': '%s'," +
" 'media': 'http://xstore.'," +
" 'MediaType': 'Book'," +
" 'Author': 'My Book Author'," +
" 'Title': 'My Book Title'," +
" 'contentType': '%s'" +
"}", uuid, type));
}
}
In the documentation it says, total file size we can store is 2GB.
"Azure Cosmos DB allows you to store binary blobs/media either with
Azure Cosmos DB (maximum of 2 GB per account) " Is it the max we can
store?
Yes.The size of attachments is limited in document db. However, there are two methods for creating a Azure Cosmos DB Document Attachment.
1.Store the file as an attachment to a Document
The raw attachment is included as the body of the POST.
Two headers must be set:
Slug – The name of the attachment.
contentType – Set to the MIME type of the attachment.
2.Store the URL for the file in an attachment to a Document
The body for the POST include the following.
id – It is the unique name that identifies the attachment, i.e. no two attachments will share the same id. The id must not exceed 255 characters.
Media – This is the URL link or file path where the attachment resides.
The following is an example
{
"id": "device\A234",
"contentType": "application/x-zip-compressed",
"media": "www.bing.com/A234.zip"
}
If your files are over limitation , you could try to store them with second way. More details, please refer to blog.
In addition, you could notice that cosmos db attachments support
garbage collect mechanism,it ensures to garbage collect the media when all of the outstanding references are dropped.
Hope it helps you.

How to get the browser name alone from client in java?

I tried using
String userAgent=req.getHeader("user-agent");
and also the following
#GET
#Path("/get")
public Response addUser(#HeaderParam("user-agent") String userAgent) {
return Response.status(200)
.entity("addUser is called, userAgent : " + userAgent)
.build();
}
But I need only, browser name as chrome,firefox,IE.Please help,if anyone know.
UPDATE : Got answer
public String browser(#HeaderParam("user-agent") String userAgent){
UserAgent browserName = UserAgent.parseUserAgentString(userAgent);
String browser=browserName.toString();
System.out.println(browser)
}
Getting information out of user agent strings is somewhat of a black art. Easiest is probably to use a library to parse the user agent string and extract the needed information.
I've used UADetector in the past with good results, but there are undoubtedly other libraries out there.
The following sample is from the UADetector documentation:
UserAgentStringParser parser = UADetectorServiceFactory.getResourceModuleParser();
ReadableUserAgent agent = parser.parse(request.getHeader("User-Agent"));
out.append("You're a <em>");
out.append(agent.getName());
out.append("</em> on <em>");
out.append(agent.getOperatingSystem().getName());
out.append("</em>!");

How to map url in java web application

I have a question about java web applications.
Is there a way to map url: index.jsp?lng=en to: index/en?
Take the host name from the request object if you are getting HttpServletRequest OR you can use regex to get the host name. en is a request parameter value which you can get using request.getParameter("lng")
URL aURL = new URL("index.jsp?lng=en");
System.out.println("hostname = " + aURL.getHost()); //index
then return String with hostName + "/" + paramValue

java rest jersey redirection for oauth2 not working

I am writing a java rest module, with jersey 2, whose first step is to get user credentials from an external Oauth2 server. When I try to redirect the user to the authentications service I see that url is correctly generated but It stays in the place. This is the code i am executing:
#GET
public String inOk(
#DefaultValue("") #QueryParam("code") String inoauthcode)
{
String oauthserv = "https://xxx";
String oauthclientid = "xxx";
String oauthsecret = "xxxx";
String oauthredirect = "http://myapp/url";
String oauthurl = "xxxx";
String redurl = "http";
String authurl = "http";
if (inoauthcode.equals("")) {
redurl = oauthserv + "?response_type=code&client_id=" + oauthclientid + "&redirect_uri=" + oauthredirect;
URI uri = UriBuilder.fromUri(redurl).build();
Response.temporaryRedirect(uri);
}
authurl = oauthurl + inoauthcode + "&redirect_uri=" + oauthredirect + "&client_id=" + oauthclientid + "&client_secret=" + oauthsecret;
...REST OF CODE ...
}
If I write the generated url to the screen It works perfectly but the temporaryRedirect command is doing nothing (aparently).
What am I doing wrong? Did I forget something? This code is almost directly copied from similar questions asked in this forum, but I can't get it to work.
It was an easy one this time, but took long to figure out.
The output of the function should not be a String but a Response:
public String inOk(
The redirection command should look like this:
return Response.seeOther(uri).build();
And now it works.

Categories

Resources