need code to Convert rupee to dollar in java - java

I am writing an application java ,
is any way to write a java code to convert rupee to u.s. dollar and it shoud fetch the current u.s. dollar.
I need the program in java
Thanks

Google is our friend. I found this webservice which offers currency conhttp://www.webservicex.net/WS/WSDetails.aspx?WSID=10

You'll either hardcode the exchange rate in your application or database, or you'll be fetching that in real time (or asynchronously & cache every x minutes) from a third party site, for example http://www.google.com/search?q=1+usd+in+inr

In order to do this you would need to fetch the current exchange rate from a web service. The easiest way, if you just need to fetch a page, is something like this:
InputStream is = new URL("http://someexchangesite.com...").openStream();
Then read and parse the InputStream to find the exchange rate, and then use it with some simple multiplication!

Please find the below code which returns json response for getting Conversion Rate.
HttpClient client = new HttpClient();
NameValuePair arg1 = new NameValuePair("method","runJob");
//Change your currency types here in which you would want to convert
NameValuePair arg2 = new NameValuePair("from","USD");
NameValuePair arg3 = new NameValuePair("to", "PKR");
//getting the method
GetMethod method = new GetMethod("http://rate-exchange.appspot.com/currency");
method.setQueryString(new NameValuePair[]{arg1, arg2, arg3});
//executes the link
client.executeMethod(method);
//getting response in string
JSONObject obj = new JSONObject(method.getResponseBodyAsString());
//getting rate from the json response
double rate = obj.getDouble("rate");
//closing conncetion
method.releaseConnection();
//returning value
return rate;

Related

Why getScore() api of EntityAnnotation class returns zero all time?

I am using google vision api for Text Detection of images which gives response in JSON format. So this response belongs to com.google.cloud.vision.v1.EntityAnnotation.From EntityAnnotation object I am trying to get the value using getScore() of EntityAnnotation. But every time it returns 0 and I am expecting some float value rather than just 0. Has anybody faced similar issue ? To understand the google vision text detection api, you can go through this https://cloud.google.com/vision/docs/ocr Help appreciated.Thanks.
I tried the same input with LABEL_DETECTION tag provided by google vision api. For that it returns some values between 0 to 1 rather than just zero. But it's not working for same input with TEXT_DETECTION tag. I tested on windows-10
try (FileInputStream inputStream = new FileInputStream(filePath); ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
final ByteString imageBytes = ByteString.readFrom(inputStream);
final Image image = Image.newBuilder().setContent(imageBytes).build();
final Feature feature = Feature.newBuilder().setType(TEXT_DETECTION).build();
final AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feature).setImage(image)
.build();
requests.add(request);
final BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
final List < AnnotateImageResponse > responseList = response.getResponsesList();
result = responseList.get(0).getTextAnnotationsList();
}
final EntityAnnotation annotation = result.get(0);
final Float score = annotation.getScore();
There is no score for TEXT_DETECTION. Try expanding the "response" to see an example of attributes being returned for TEXT_DETECTION: https://cloud.google.com/vision/docs/ocr
You may be interested in DOCUMENT_TEXT_DETECTION and full_text_annotation, which has confidence.

XML-RPC struct in java

i want to create request xml-rpc struct in java, my code is like this
public String xmlprc() throws XmlRpcException, MalformedURLException{
ReqModelTest req = new ReqModelTest();
String test="";
Object paramsR = new Object();
Vector params = new Vector();
req.setvalue1("value1");
req.setvalue2("value2");
req.setvalue3("value3");
req.setvalue4("value4");
req.setvalue5("value5");
params.add(req);
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
try {
config.setServerURL(new URL("myurl"));
XmlRpcClient client = new XmlRpcClient();
client.setConfig(config);
paramsR = (Object)client.execute("mymethod", params);
} catch (MalformedURLException | XmlRpcException e) {
log.info(e);
}
log.info(paramsR.toString());
test = paramsR.toString();
return test;
}
but when i run it, it shows error org.apache.xmlrpc.XmlRpcException: Failed to generate request: Unsupported Java type: com.model.ReqModelTest. is there any way how to do it? Thank you very much
The most common error we have in these cases is not implementing Serializable interface.
The documentation tells us to follow these steps :
All primitive Java types are supported, including long, byte, short, and double.
Calendar objects are supported. In particular, timezone settings, and milliseconds may be sent.
DOM nodes, or JAXB objects, can be transmitted. So are objects implementing the java.io.Serializable interface.
Both server and client can operate in a streaming mode, which preserves resources much better than the default mode, which is based on large internal byte arrays.
Please check you are following these guidelines.
http://ws.apache.org/xmlrpc/
You need to create custom TypeFactory to handle your own data types.
Please see this link

how to read FAKE JSON response from ticker API of unocoin bitcoin exchange?

First of all i am sorry if i am wrong that the response is fake JSON ...
the api i am using is ticker api of unocoin
https://www.unocoin.com/trade?all
I have been working on a website which takes the rate from various indian bitcoin exchanges and plot the graphs for easy visualization.So far i have added 3 exchanges and got their rate from their TICKER API,the response i got is just plane text and no other surprises..
all these exchanges like
ZEBPAY: https://www.zebapi.com/api/v1/market/ticker/btc/inr
Koinex: https://koinex.in/api/ticker
made my life easier but
making a get request to unocoin api gives me a html page with only an iframe in body tag and i am not able to directly(or indirectly) use data in my code.
there is an alternate method to get access to many features but it requires me to register and feed my ACCESS TOKEN in every request which i don't prefer right now.
to make api calls i am using java and code is given belowe:
private static String sendGet(String host,String apiEndpoint) throws Exception {
URL obj = new URL(host+apiEndpoint);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println(responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return(response.toString());
}
just a note: i got google recaptcha if i make a lot of request in small time frame
the result from above code is
<html><head><META NAME="robots" CONTENT="noindex,nofollow"><script src="/_Incapsula_Resource?SWJIYLWA=2977d8d74f63d7f8fedbea018b7a1d05"></script><script>(function() { var z="";var b="7472797B766172207868723B76617220743D6E6577204461746528292E67657454696D6528293B766172207374617475733D227374617274223B7661722074696D696E673D6E65772041727261792833293B77696E646F772E6F6E756E6C6F61643D66756E6374696F6E28297B74696D696E675B325D3D22723A222B286E6577204461746528292E67657454696D6528292D74293B646F63756D656E742E637265617465456C656D656E742822696D6722292E7372633D222F5F496E63617073756C615F5265736F757263653F4553324C555243543D363726743D373826643D222B656E636F6465555249436F6D706F6E656E74287374617475732B222028222B74696D696E672E6A6F696E28292B222922297D3B69662877696E646F772E584D4C4874747052657175657374297B7868723D6E657720584D4C48747470526571756573747D656C73657B7868723D6E657720416374697665584F626A65637428224D6963726F736F66742E584D4C4854545022297D7868722E6F6E726561647973746174656368616E67653D66756E6374696F6E28297B737769746368287868722E72656164795374617465297B6361736520303A7374617475733D6E6577204461746528292E67657454696D6528292D742B223A2072657175657374206E6F7420696E697469616C697A656420223B627265616B3B6361736520313A7374617475733D6E6577204461746528292E67657454696D6528292D742B223A2073657276657220636F6E6E656374696F6E2065737461626C6973686564223B627265616B3B6361736520323A7374617475733D6E6577204461746528292E67657454696D6528292D742B223A2072657175657374207265636569766564223B627265616B3B6361736520333A7374617475733D6E6577204461746528292E67657454696D6528292D742B223A2070726F63657373696E672072657175657374223B627265616B3B6361736520343A7374617475733D22636F6D706C657465223B74696D696E675B315D3D22633A222B286E6577204461746528292E67657454696D6528292D74293B6966287868722E7374617475733D3D323030297B706172656E742E6C6F636174696F6E2E72656C6F616428297D627265616B7D7D3B74696D696E675B305D3D22733A222B286E6577204461746528292E67657454696D6528292D74293B7868722E6F70656E2822474554222C222F5F496E63617073756C615F5265736F757263653F535748414E45444C3D313539373232303738303038363836383835372C31313637303136303238393537363439373530392C373430383533373634363033313237303235322C353332303936222C66616C7365293B7868722E73656E64286E756C6C297D63617463682863297B7374617475732B3D6E6577204461746528292E67657454696D6528292D742B2220696E6361705F6578633A20222B633B646F63756D656E742E637265617465456C656D656E742822696D6722292E7372633D222F5F496E63617073756C615F5265736F757263653F4553324C555243543D363726743D373826643D222B656E636F6465555249436F6D706F6E656E74287374617475732B222028222B74696D696E672E6A6F696E28292B222922297D3B";for (var i=0;i<b.length;i+=2){z=z+parseInt(b.substring(i, i+2), 16)+",";}z = z.substring(0,z.length-1); eval(eval('String.fromCharCode('+z+')'));})();</script></head><body><iframe style="display:none;visibility:hidden;" src="//content.incapsula.com/jsTest.html" id="gaIframe"></iframe></body></html>
i just want the response just like i get in my browser after visiting
https://www.unocoin.com/trade?all
The website is protected by an anti-scraping script called Incapsula that tries to run a small Javascript bit, but since you are using Java it won't be able to run it, unless you are using Selenium or like the V8 engine, but this is a bit not recommended because you are somehow breaking the rules of what they considered to be intrusive for them, but my recommendation:
Talk with the guys from unocoin.com and ask them to whitelist your IP if they are okay with you scraping their site.
Instead of using the API, you can do it by scraping the Unocoin Ticker API All Rates webpage. This would break if there is some change in the website, but till then it works.
It can be implemented via WebKit using WKWebView, WKNavigationDelegate protocol and then injecting some JavaScript.
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
#IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.isHidden = true
webView.navigationDelegate = self
let myURL = URL(string: "https://www.unocoin.com/trade?all")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
}
// For checking if website has loaded
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
// Injecting JS to fetch HTML inside <body>
webView.evaluateJavaScript("document.body.innerHTML", completionHandler: {
(html: Any?, error: Error?) in
if error == nil && html != nil {
// Perform string manipulation and parse JSON to get data
} else {
// Error while fetching data
}
})
}
}

Generate ImapMessage from Response Object

I've created a custom command to retrieve multiple objects in the same request (in order to solve some performance issues), instead of using the folder method .getMessage(..) which in my case retrieved an ImapMessage object:
Argument args = new Argument();
args.writeString(Integer.toString(start) + ":" + Integer.toString(end));
args.writeString("BODY[]");
FetchResponse fetch;
BODY body;
MimeMessage mm;
ByteArrayInputStream is = null;
Response[] r = protocol.command("FETCH", args);
Response status = r[r.length-1];
if(status.isOK()) {
for (int i = 0; i < r.length - 1; i++) {
...
}
}
Currently I'm validating if the object is a ImapResponse like this:
if (r[i] instanceof IMAPResponse) {
IMAPResponse imr = (IMAPResponse)r[i];
My question is, how can I turn this response into an ImapMessage?
Thank you.
Are you trying to download the entire message content for multiple messages at once? Have you tried using IMAPFolder.FetchProfileItem.MESSAGE? That will cause Folder.fetch to download the entire message content, which you can then access using the Message objects.
I haven't succeeded yet to convert it into a IMAPMessage but I'm now able transform it into a MIME Message. It isn't perfect but I guess it will have to work for now:
FetchResponse fetch = (FetchResponse) r[i];
BODY body = (BODY) fetch.getItem(0);
ByteArrayInputStream is = body.getByteArrayInputStream();
MimeMessage mm = new MimeMessage(session, is);
Then, it can be used to get information like this:
String contentType = mm.getContentType();
Object contentObject = mm.getContent();
There are also other methods to get information like the sender, date, etc.

Restlet: Retrieving http body in verifier

When I want retrieve the http body of a post in my Request Verifier it kinda resets my entity and I get a nullpointer exception when I want to get the http body in my resource class.
Verifier:
JsonRepresentation jsonrep;
try {
Representation entity = request.getEntity();
jsonrep = new JsonRepresentation(entity);
//bug: entity resets when getJsonObject is being called.
JSONObject jsonobj = jsonrep.getJsonObject();
if(companyId != jsonobj.getInt("id_companies")){
return Verifier.RESULT_INVALID;
}
...
AppResource:
#Post
public Representation addApp(Representation rep) throws Exception{
//rep is null
JsonRepresentation jsonrep = new JsonRepresentation(rep);
When I dont't call:
JSONObject jsonobj = jsonrep.getJsonObject();
it just works fine.
Is anybody facing the same issue or got a solution for it?
Thanks in advance!
In fact, by default, the representation is an InputRepresentation that doesn't store the representation content.
In your case, the simplest way is to wrap the representation into a StringRepresentation within your verifier:
Representation entity = request.getEntity();
StringRepresentation sEntity = new StringRepresentation(entity);
request.setEntity(sEntity);
JsonRepresentation jsonrep = new JsonRepresentation(sEntity);
Then, the string representation will be automatically provided to your server resource method...
Hope it helps you.
Thierry

Categories