How to get location details from IP address integer value - java

I am converting IP address in to its corresponding number. Now I want to know the location details i.e. long and lat, time zone etc. Is it possible in Java. Do i have to use some external jar for database ?

IP addresses themselves don't have location info. However a number of databases/services exist that have this mapping.
See this blog entry for a number of different options. There are a number of APIs and databases to connect to for this, and you have the option of downloading such info locally to avoid remote lookups.

So as others have correctly pointed out an IP address does not contain any of this 'metadata' about location. You will need to either rely on a third party to get this information, retrieve this information yourself, or go without it. Writing the library to scrape that information should be possible in Java.

ipAddress = request.getRemoteAddr();
GeoLocation gl = new GeoLocation();
gl.GetGeoLocationByIP(ipAddress);
String country = gl.Country;
refer

For getting location from IP address you have to buy the IP databases
where they will periodically update the IP table.
However if you want, you can get the location details viz city,region,country,longitude,latitude from request header.
It's only available for GAE user.
For more details go through
GAE ReleaseNotes
public static HashMap<String, Object> getLocationDetails(HttpServletRequest request)
{
HashMap<String, Object> locationMap = null;
String country = "",city="",region="",latitude="",longitude="",temp="",state="",title="",address="",zip="";
boolean primary = true;
try
{
locationMap = new HashMap<String, Object>();
country = request.getHeader("X-AppEngine-Country");
region = request.getHeader("X-AppEngine-Region");
city = request.getHeader("X-AppEngine-City");
temp = request.getHeader("X-AppEngine-CityLatLong");
latitude = (temp.split(","))[0];
longitude = (temp.split(","))[1];
log.info("country>>"+country+"region>>"+region+"city>>"+city+"temp>>"+temp+"latitude>>"+latitude+"longitude>>"+longitude);
locationMap.put("city" , city);
locationMap.put("state" , region);
locationMap.put("country" , country);
locationMap.put("latitude" , latitude);
locationMap.put("longitude" , longitude);
log.info("locationMap==>"+locationMap);
}catch (Exception e)
{
log.log(Level.SEVERE,"Exception while getting location"+e.getMessage(),e);
}
return locationMap;
}

Related

How to translate words in android studio app?

I have used geocoder to get the address through the location. However, the city name is in English and I want to show it in Arabic.
This is the code to get the address :
public String getAddress(double LATITUDE, double LONGITUDE) {
String city = "";
try {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null && addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0);
city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
}
} catch (IOException e) {
e.printStackTrace();
}
return city;
}
And then this is where I show the city name in a TextView :
String country_and_city = getAddress(latitude, longitude);
TextView city_name = findViewById(R.id.city);
city_name.setText(country_and_city);
Here, the city name will be displayed in English, how can I translate it or use other methods to show it in Arabic? For example, maybe using google-translate api or something if that is even possible
In order to use the Google Cloud Translation API, you need to have a project which has this API enabled, so you can make authenticated calls. You can set it up here.
Google provide a lot of sample codes, here, which you can use. The code below is used to translate a string Spanish(es) to German(de),
Translation translation =
translate.translate(
"Hola Mundo!",
Translate.TranslateOption.sourceLanguage("es"),
Translate.TranslateOption.targetLanguage("de"),
// Use "base" for standard edition, "nmt" for the premium model.
Translate.TranslateOption.model("nmt"));
System.out.printf("TranslatedText:\nText: %s\n", translation.getTranslatedText());
This article explains in details how to integrate the API within your Android Studio project, it can give you a better overview of the whole process.
Lastly, I should point out that according to the documentation,
Prices are pro rata (proportional and incremental). Charges are scaled to the number of characters actually provided to Cloud Translation. For example, if you send 575,000 characters for processing within a month, you are charged $1.50. The first 500,000 characters are free, and then you are charged for the additional 75,000 characters sent for detection, translation, or both.
As another alternative you can also check the googletrans library, which according to the documentation:
Googletrans is a free and unlimited python library that implemented Google Translate API. This uses the Google Translate Ajax API to make calls to such methods as detect and translate.

Network error on some devices after build

I installed the app after build on different devices (Android) the app opens up fine but when sending network request only one of the device is able to send successfully the others remain unresponsive.
Am using the Rest.post() to send that particular request.
Using codename one 6.0 but updated it this morning so I will be using the recent version.
Note: the situation happened before the update. i added a bunch of things while trying to locate the problem.
Here is the code:
//...Login button ActionListner
gui_Button_login.addActionListener((ae)->{
gui_Infinite_Progress.setVisible(true);
gui_Infinite_Progress.setEnabled(true);
gui_Button_login.setEnabled(false);
gui_Text_Field_username.setEnabled(false);
gui_Text_Field_Password.setEnabled(false);
if(doLogin()){
Handle.UserFeed = new UserFeedForm();
Handle.UserFeed.show();
}else{
gui_Button_login.setEnabled(true);
gui_Text_Field_username.setEnabled(true);
gui_Text_Field_Password.setEnabled(true);
gui_Infinite_Progress.setVisible(false);
gui_Infinite_Progress.setEnabled(false);
}
});
//...Do login function
private boolean doLogin(){
String usr_username = gui_Text_Field_username.getText();
String usr_password = gui_Text_Field_Password.getText();
Map<String, Object> signInData = new HashMap<>();
signInData.put("usr_username", usr_username);
signInData.put("usr_password", usr_password);
String signInDataJSON = JSONParser.mapToJson(signInData);
gui_Span_Label_Debug.setText(gui_Span_Label_Debug.getText() +"\nData:\n"+ signInDataJSON);
gui_Span_Label_Debug.setText(gui_Span_Label_Debug.getText() +"\nSending...");
Response<Map> response = Rest.post(Data.API_SIGNIN_URL)
.jsonContent()
.body(signInDataJSON)
.acceptJson()
.onErrorCodeJSON(err->{
ToastBar.showErrorMessage(err.getResponseErrorMessage(), Data.MESSAGE_ERROR_TIMEOUT);
//gui_Span_Label_Debug.setText(gui_Span_Label_Debug.getText() +"\nError:\n"+ err.getResponseErrorMessage());
}).getAsJsonMap();
Map<String, Object> responseData = response.getResponseData();
if(response.getResponseCode() == 0){
ToastBar.showErrorMessage("Please check your internet!", Data.MESSAGE_ERROR_TIMEOUT);
}
gui_Span_Label_Debug.setText(gui_Span_Label_Debug.getText() +"\nResponse Code:\n"+ response.getResponseCode());
gui_Span_Label_Debug.setText(gui_Span_Label_Debug.getText() +"\nResponse Error Msg:\n"+ response.getResponseErrorMessage());
if(responseData == null){
return false;
}
if(((String)responseData.get("status")).equalsIgnoreCase("error")){
ToastBar.showErrorMessage((String)responseData.get("msg"), Data.MESSAGE_ERROR_TIMEOUT);
return false;
}
if(((String)responseData.get("status")).equalsIgnoreCase("success")){
ToastBar.showMessage((String)responseData.get("msg"), FontImage.MATERIAL_CHECK_CIRCLE, Data.MESSAGE_SUCCESS_TIMEOUT);
Handle.LoggedInUserData = (Map<String, Object>) responseData.get("data");
Handle.Authority = (String)Handle.LoggedInUserData.get("jwt");
return true;
}
return false;
}
//...
Data.API_SIGNIN_URL is a string containing address accessible via internet e.g. http://94.543.23.4/
I'm guessing you are trying to connect via an IP to a specific machine and it isn't working. This machine is probably visible only within your internal network and the other devices aren't connected to the internal network or choose a route via cell towers.
well i added the build hint android.xpermissions and set the value to android.permission.INTERNET\=true,android.permission.WRITE_EXTERNAL_STORAGE\=true,android.permission.READ_EXTERNAL_STORAGE\=true.
Its working but seems redundant to me since according to codenameone docs Internet permission is inserted by default. i added the storage just to avert possible similar situation

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.

Find all the attached volumes for an EC2 instance

I'm using the below code to get all the available volumes under EC2. But I can't find any Ec2 api to get already attached volumes with an instance. Please let me know how to get all attached volumes using instanceId.
EC2Api ec2Api = computeServiceContext.unwrapApi(EC2Api.class);
List<String> volumeLists = new ArrayList<String>();
if (null != volumeId) {
volumeLists.add(volumeId);
}
String[] volumeIds = volumeLists.toArray(new String[0]);
LOG.info("the volume IDs got from user is ::"+ Arrays.toString(volumeIds));
Set<Volume> ec2Volumes = ec2Api.getElasticBlockStoreApi().get()
.describeVolumesInRegion(region, volumeIds);
Set<Volume> availableVolumes = Sets.newHashSet();
for (Volume volume : ec2Volumes) {
if (volume.getSnapshotId() == null
&& volume.getStatus() == Volume.Status.AVAILABLE) {
LOG.debug("available volume with no snapshots ::" + volume.getId());
availableVolumes.add(volume);
}
}
The AWS Java SDK now provides a method to get all the block device mappings for an instance. You can use that to get a list of all the attached volumes:
// First get the EC2 instance from the id
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest().withInstanceIds(instanceId);
DescribeInstancesResult describeInstancesResult = ec2.describeInstances(describeInstancesRequest);
Instance instance = describeInstancesResult.getReservations().get(0).getInstances().get(0);
// Then get the mappings
List<InstanceBlockDeviceMapping> mappingList = instance.getBlockDeviceMappings();
for(InstanceBlockDeviceMapping mapping: mappingList) {
System.out.println(mapping.getEbs().getVolumeId());
}
You can filter the output of the EC2 DescribeVolumes API call. There are various attachment.* filters available, the one you want is filtering by attached instance ID. Try the following code:
Multimap<String, String> filter = ArrayListMultimap.create();
filter.put("attachment.instance-id", instanceId);
filter.put("attachment.status", "attached");
Set<Volume> volumes = ec2Api.getElasticBlockStoreApi().get()
.describeVolumesInRegionWithFilter(region, volumeIds, filter);
The filter is a Multimap with the keys and values you want to filter on. You can actually specify the same filter multiple times, for example to get all volumes attached to a number of different instances.
You can use volumeAttachmentApi.listAttachmentsOnServer() to do this.
NovaApi novaApi = context.unwrapApi(NovaApi.class);VolumeApi volumeApi = novaApi.getVolumeExtensionForZone(region).get();
VolumeAttachmentApi volumeAttachmentApi = novaApi.getVolumeAttachmentExtensionForZone(region).get();
volumeAttachmentApi.listAttachmentsOnServer(serverId)

Appending perforce permission table through java results in blank permission table

I am trying to grant permission to a group on a folder in Perforce. However, the permission table that is created/updated from Java in Perforce is empty.
Following are the steps that I do -
//Get the server object.
IOptionsServer server = ServerFactory.getOptionsServer("p4java://<ip>:1666", null);
server.connect();
server.setUserName("<username>"); // this is a super user
server.login("<password>");
//Create a user group and add users.
IUserGroup ug = new UserGroup();
String groupName = "<usergroup_somename>;
ug.setName(groupName);
List<String> userList = new ArrayList<>();
userList.add("<username1>");
userList.add("<username2>");
userList.add("<username3>");
ug.setUsers(userList);
server.createUserGroup(ug);
//Get the permission table.
GetProtectionEntriesOptions gpo = new GetProtectionEntriesOptions();
gpo.setAllUsers(true);
List<IProtectionEntry> peList = server.getProtectionEntries(null, gpo);
//Create a new Protection entry
IProtectionEntry pe = new ProtectionEntry();
pe.setGroup(true);
pe.setName(groupName);
depotFilePath = "//depottest/Level1/Level2/..."; // the folders exist in Perforce
pe.setPath(depotFilePath);
pe.setMode("write");
pe.setHost("*");
pe.setPathExcluded(false);
pe.setOrder(peList.size());
pe.setType(EntryType.INCLUDE);
//Add the new created permission into the fetched Permission table list.
peList.add(pe);
//Create/Update the Permission table using either of the following methods separately or in combination creates a blank permission table.
server.createProtectionEntries(peList);
server.updateProtectionEntries(peList);
According to the documentation the methods in the end should create/replace/update the Permission table, however, this does not happen and instead the permission table in the Perforce server is deleted/blank.
I may be missing something. Can someone please give some suggestions on how to fix this?
P.S. I have tried using only the updateProtectionEntries(peList) method or the server.createProtectionEntries(peList) method and both together and still the pemission table in the Perforce server is blank.
Perforce has forums where you can ask questions: forums.perforce.com
At one time (depends on P4Java and server versions) incorrect order values could lose data. There's also a spaces-in-path problem.
This works for me:
peList.add(pe);
// fix order values and spaces-in-path quoting
int i = 0;
for (IProtectionEntry pe : peList) {
pe.setOrder(i++);
if (pe.getPath().indexOf(" ") >= 0) {
// this bug should be fixed in 2014.X (no promises)
if (pe.isPathExcluded()) {
pe.setPath("\"-" + pe.getPath() + "\"");
pe.setPathExcluded(false);
} else {
pe.setPath("\"" + pe.getPath() + "\"");
}
}
}
try {
String createProtectionEntries = server.createProtectionEntries(peList);

Categories

Resources