i am trying to fetch few genomic coordinate using API from the web mutalyzer.nl using the method position converter, but i am getting 405 error. Can you please help?
here is my code:-
import java.lang.Object;
import org.apache.commons.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
private long checkVariant() {
long totalLines = 0;
File tempInputFile = new File(filePath + "input.tsv");
File outputFile = new File(filePath + "temp.tsv");
outputFile.append("Query String" + "\t" + "Response");
tempInputFile.withReader("UTF-8") { buf ->
buf.eachLine { line ->
if (totalLines > 0) { // skip first line
String[] words = line.split("\\t");
// fire remote query and check response...
//https://www.mutalyzer.nl/position-converter?assembly_name_or_alias=GRCh37&description=NM_024675.3%3Ac.232G%3EA
def queryTerm = "description=" + words[1];
def query = "assembly_name_or_alias=GRCh37&" + queryTerm;
final Pattern pattern = Pattern.compile("<code>(.+?)</code>");
def urlString = "https://www.mutalyzer.nl/position-converter";
def url = new URL(urlString);
println urlString;
def connection = url.openConnection();
connection.setRequestMethod("POST");
connection.doOutput = true;
def writer = new OutputStreamWriter(connection.outputStream);
println query
writer.write(query);
println query
writer.flush();
writer.close();
connection.connect();
def recaptchaResponse = connection.content.text;
final Matcher matcher = pattern.matcher(recaptchaResponse);
matcher.find();
def answerString = matcher.group(1);
//def answer = answerString.replace("Human ", "").replace(" - UCSC Genome Browser v318", "");
println "QueryTerm :=" + words[1] + " : Response := " + answerString;
outputFile.append(System.getProperty("line.separator") + words[1] + "\t" + answerString);
}
totalLines = totalLines + 1;
}
}
return totalLines;
}
can any one tell me the exact issue?
A http 405 status code means the method is not supported, i.e you're trying to post. From looking at the web pages source its a GET. Try changing
connection.setRequestMethod("POST");
To
connection.setRequestMethod("GET");
Reference to HTTP 405- http://www.checkupdown.com/status/E405.html
What does the API of this website say? Do they support HTTP POST for their APIs.
I called a HTTP GET on following URL (remember that GET has no body in request)
https://www.mutalyzer.nl/position-converter?assembly_name_or_alias=GRCh37&description=NM_003002.3%3Ac.274G%3ET and was able to receive a HTML response from them.
I drilled there site and found they have SOAP Services and REST Services exposed https://www.mutalyzer.nl/webservices where example is given. (What you may be looking is https://www.mutalyzer.nl/soap-api#src.idp856784 submitBatchJob with GET)
Create a SOAP request to invoke soap service or HTTP request to invoke it using REst
https://mutalyzer.nl/json/submitBatchJob?data=Tk1fMDAzMDAyLjM6Yy4yNzRHPlQ=&process=PositionConverter&argument=hg19
Related
I am new to OKTA.
Using the below code to get the access token.. but getting 401 unauthorized error in this line
inputBuff = new BufferedReader(new
InputStreamReader(httpsClient.getInputStream()));
String oktaURL = "https://xxx.oktapreview.com/oauth2/default/v1/token";
String urlParameters = “client_id=” + clientId+“grant_type=authorization_code&redirect_uri=”+“http://:8192/app”+"&code="+oktaCode;
URL url1 = new URL(oktaURL);
StringBuffer response = null;
String output1;
log.info("The url to get the access token:"+url1.toString());
if (url1.getProtocol() != null && url1.getProtocol().startsWith("https")){
//String encodedData = DatatypeConverter.printBase64Binary((clientId + ":" + clientSecret).getBytes("UTF-8"));
//String authorizationHeaderString = "Authorization: Basic " + encodedData;
httpsClient = (HttpsURLConnection) url1.openConnection();
httpsClient.setRequestMethod("POST");
httpsClient.setRequestProperty("Accept","application/json");
httpsClient.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes()));
httpsClient.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
httpsClient.setInstanceFollowRedirects(false);
log.info ("Send the POST request");
// Send post request
httpsClient.setDoOutput(true);
try (DataOutputStream opStream = new DataOutputStream(httpsClient.getOutputStream())) {
opStream.writeBytes(urlParameters);
opStream.flush();
}
inputBuff = new BufferedReader(new InputStreamReader(httpsClient.getInputStream())); // throwing 401 here.
log.info("Read from the input stream");
response = new StringBuffer();
while ((output1 = inputBuff.readLine()) != null) {
response.append(output1);
}
}
if (response != null) {
String theString = response.toString();
log.trace("Info:"+theString);
}
I could navigate to OKTA server's login page via /authorize URL and then authentication is successful and coming back to my application. Now trying to get access token. Please help how to solve this in java.
I just checked the okta log, it says the below right above the authenticate success log.
You forgot to put & after your actual client_id, so your string should look like
String urlParameters =
"client_id=" + clientId +
"&grant_type=authorization_code" +
"&redirect_uri=" + "http://:8192/app" +
"&code=" + oktaCode;
Solve the issue, there were 2 issues.
Removed client_id from urlParameters as its given in Authorization header
Removed default from /token endpoint as its not give in my /authorize endpoint.
I am very new in SOAP WebService development in Java and I have the following problem.
I have a webservice that expose 2 methods, the first (that is simpler) is already implemented (by an other person) and is named getVersion() and, in SoapUI have the following request:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
<soapenv:Header/>
<soapenv:Body>
<tem:getVersion/>
</soapenv:Body>
</soapenv:Envelope>
Then I have a Java project that exeute the call to the webservice and in a class I have the followin method for the previous webservice method:
public String getVersion() {
java.net.URL url = null;
java.net.URLConnection conn = null;
java.io.BufferedReader rd = null;
String soapResponse = "";
String risultato = "";
// SOAP ENVELOP for the request:
String soapRequest;
soapRequest = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">" + "<soapenv:Header/>" + "<soapenv:Body> " + "<tem:getVersion/>" + "</soapenv:Body>" + "</soapenv:Envelope>";
try {
// Try to open a connection
url = new java.net.URL(_webServiceUrl);
conn = url.openConnection();
// Set the necessary header fields
conn.setRequestProperty("SOAPAction", "http://tempuri.org/IMyService/getVersion");
conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
conn.setDoOutput(true);
// Send the request:
java.io.OutputStreamWriter wr = new java.io.OutputStreamWriter(conn.getOutputStream());
wr.write(soapRequest);
wr.flush();
// Read the response
rd = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream()));
// Put the entire response into the soapResponse variable:
String line;
while ((line = rd.readLine()) != null) {
//System.out.println(line);
soapResponse = soapResponse + line + System.getProperty("line.separator");
}
rd.close();
// elaboro la risposta
SAXBuilder builder = new SAXBuilder();
org.jdom.Document documentXML = null;
documentXML = builder.build(new StringReader(soapResponse));
XPath xPath;
Element objectElement;
//xPath = XPath.newInstance("s:Envelope/s:Body/getVersionResponse/getVersionResult");
xPath = XPath.newInstance("s:Envelope/s:Body");
xPath.addNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");
objectElement = (Element) xPath.selectSingleNode(documentXML);
if (objectElement != null) {
risultato = objectElement.getValue();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return risultato;
}
Now I have to replicate the same thing creating a new method (in the Java project that call the ws method) for the second method (that is more complex because, unlike the previous one, requires the passing some parameters) and I have some doubts about it.
So the situation is the following one: in SoapUI there is this WS method named getConfigSettings and its request is:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
<soapenv:Header/>
<soapenv:Body>
<tem:getConfigSettings>
<!--Optional:-->
<tem:login>?</tem:login>
<!--Optional:-->
<tem:password>?</tem:password>
<!--Optional:-->
<tem:ipAddress>?</tem:ipAddress>
<!--Optional:-->
<tem:clientVersion>?</tem:clientVersion>
<!--Optional:-->
<tem:lastUpdateTime>?</tem:lastUpdateTime>
</tem:getConfigSettings>
</soapenv:Body>
</soapenv:Envelope>
As you can see it requires some parameters (in SoapUi I have to replace characters with the correct parameter value)
So, in the Java project, I have create the following method that execute this call creating the SOAP Envelop for my request (but I have many doubtsa about its correctness)
public String authentication(String login, String password, String ipAddress, String clientVersion) {
java.net.URL url = null;
java.net.URLConnection conn = null;
java.io.BufferedReader rd = null;
String myResponse = "";
String soapXml;
// SOAP ENVELOP for the request:
//soapXml = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"> " + "<s:Header>" + "<Action s:mustUnderstand=\"1\" xmlns=\"http://schemas.microsoft.com/ws/2005/05/addressing/none\">http://tempuri.org/IMyService/getVersion</Action>" + "</s:Header>" + "<s:Body>" + "<getVersion xmlns=\"http://tempuri.org/\" />" + "</s:Body>" + "</s:Envelope>";
soapXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">"
+ "<soapenv:Header/>"
+ "<soapenv:Body> "
+ "<tem:login>" + login + "</tem:login>"
+ "<tem:password>" + password + "</tem:password>"
+ "<tem:ipAddress>" + ipAddress + "</tem:ipAddress>"
+ "</soapenv:Body>"
+ "</soapenv:Envelope>";
........................................................
........................................................
........................................................
DO SOME OTHER STUFF
........................................................
........................................................
........................................................
}
As you can see I have created this SOAP Envelop for my request in which I have inserted the parameter recived as input parameter of the method:
soapXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">"
+ "<soapenv:Header/>"
+ "<soapenv:Body> "
+ "<tem:login>" + login + "</tem:login>"
+ "<tem:password>" + password + "</tem:password>"
+ "<tem:ipAddress>" + ipAddress + "</tem:ipAddress>"
+ "</soapenv:Body>"
+ "</soapenv:Envelope>";
Is it correct or am I taking a wrong solution? Some suggestion?
Tnx
Andrea
Your approach looks straight forward but you need to XML-escape the strings you are inserting.
Otherwise, the receiver may not parse your request if the strings contains reserved XML characters such as <. Just consider somebody using </tem:login> as his password :)
Libraries such as Guava or Apache commons contain XML escapers, see this thread for pointers:
Best way to encode text data for XML in Java?
Alternatively, you could just include your own:
public static String xmlEscape(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < sb.length(); i++) {
char c = s.charAt(i);
if ("<&\">'".indexOf(c) != -1) {
sb.append("&#" + ((int) c) + ";");
} else {
sb.append(c);
}
}
return sb.toString();
}
So your fill code would look similar to this:
soapXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">"
+ "<soapenv:Header/>"
+ "<soapenv:Body> "
+ "<tem:login>" + xmlEscape(login) + "</tem:login>"
+ "<tem:password>" + xmlEscape(password) + "</tem:password>"
p.s. Never send login data over the net in clear text! You probably want to use https instead of http for your service.
I have a question about URI and URL
when i pass a url is work good but result is worst need help!!
as my code look like this.
import java.io.*;
import java.net.*;
import java.net.URL;
public class isms {
public static void main(String[] args) throws Exception {
try {
String user = new String ("boo");
String pass = new String ("boo");
String dstno = new String("60164038811"); //You are going compose a message to this destination number.
String msg = new String("你的哈达哈达!"); //Your message over here
int type = 2; //for unicode change to 2, normal will the 1.
String sendid = new String("isms"); //Malaysia does not support sender id yet.
// Send data
URI myUrl = new URI("http://www.isms.com.my/isms_send.php?un=" + user + "&pwd=" + pass
+ "&dstno=" + dstno + "&msg=" + msg + "&type=" + type + "&sendid=" + sendid);
URL url = new URL(myUrl.toASCIIString());
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Print the response output...
System.out.println(line);
}
rd.close();
System.out.println(url);
} catch (Exception e) {
e.printStackTrace();
}
}
}
the output in web is different..
on my java output is
你的哈达哈达!
but on my the site is
ÄãµÄ¹þ´ï¹þ´ï!
Help!!
String user = new String ("boo");
You don't need to (and shouldn't) do new String in Java—String user = "boo"; is fine.
String msg = new String("你的哈达哈达!");
Writing non-ASCII characters in your source means that you have to get the -encoding flag to javac to match the encoding you have saved your text files with. It is possible you have saved the .java file as UTF-8 but not configured your build environment to use UTF-8 at compile time.
If you are not sure that you've got this right, you can use ASCII-safe \u escapes in the meantime:
String msg = "\u4F60\u7684\u54C8\u8FBE\u54C8\u8FBE!"; // 你的哈达哈达!
Finally:
URI myUrl = new URI("http://www.isms.com.my/isms_send.php?un=" + user + "&pwd=" + pass
+ "&dstno=" + dstno + "&msg=" + msg + "&type=" + type + "&sendid=" + sendid);
When you're putting a URI together you should URL-escape each of the parameters you include in the string. Otherwise any & or other invalid character in the value will break the query. This also allows you to choose what charset is used to create the query string.
String enc = "UTF-8";
URI myUrl = new URI("http://www.isms.com.my/isms_send.php?" +
"un=" + URLEncoder.encode(user, enc) +
"&pwd=" + URLEncoder.encode(pass, enc) +
"&dstno=" + URLEncoder.encode(dstno, enc) +
"&msg=" + URLEncoder.encode(msg, enc) +
"&type=" + URLEncoder.encode(Integer.toString(type), enc) +
"&sendid=" + URLEncoder.encode(sendid, enc)
);
What the right value for enc is depends on the service you are connecting to, but UTF-8 is a good guess.
I want to send values of two variables to a PHP file from a Java applet), and I tried the following code.
try {
URL url = new URL(getCodeBase(),"abc.php");
URLConnection con = url.openConnection();
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
ps.print("score="+score);
ps.print("username="+username);
con.getInputStream();
ps.close();
} catch (Exception e) {
g.drawString(""+e, 200,100);
}
I got the following error:
java.net.UnknownServiceException:protocol doesn't support output
java.net.UnknownServiceException:protocol doesn't support output
Means that you are using a protocol that doesn't support output.
getCodeBase() refers to a file url, so something like
file:/path/to/the/applet
The protocol is file, which doesn't support outout. You are looking for a http protocol, which supports output.
Maybe you wanted getDocumentBase(), which actually returns the web page where the applet is, i.e.
http://www.path.to/the/applet
Here's some code I used with my own applet, to send values (via POST) to a PHP script on my server:
I would use it like this:
String content = "";
content = content + "a=update&gid=" + gid + "&map=" + getMapString();
content = content + "&left_to_deploy=" + leftToDeploy + "&playerColor=" + playerColor;
content = content + "&uid=" + uid + "&player_won=" + didWin;
content = content + "&last_action=" + lastActionCode + "&appletID=" + appletID;
String result = "";
try {
result = requestFromDB(content);
System.out.println("Sending - " + content);
} catch (Exception e) {
status = e.toString();
}
As you can see, I am adding up all my values to send into a "content" string, then calling my requestFromDB method (which posts my "request" values, and returns the server's response) :
public String requestFromDB(String request) throws Exception
{
// This will accept a formatted request string, send it to the
// PHP script, then collect the response and return it as a String.
URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream input;
// URL of CGI-Bin script.
url = new URL ("http://" + siteRoot + "/globalconquest/applet-update.php");
// URL connection channel.
urlConn = url.openConnection();
// Let the run-time system (RTS) know that we want input.
urlConn.setDoInput (true);
// Let the RTS know that we want to do output.
urlConn.setDoOutput (true);
// No caching, we want the real thing.
urlConn.setUseCaches (false);
// Specify the content type.
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// Send POST output.
printout = new DataOutputStream (urlConn.getOutputStream ());
printout.writeBytes (request);
printout.flush ();
printout.close ();
// Get response data.
input = new DataInputStream (urlConn.getInputStream ());
String str;
String a = "";
while (null != ((str = input.readLine())))
{
a = a + str;
}
input.close ();
System.out.println("Got " + a);
if (a.trim().equals("1")) {
// Error!
mode = "error";
}
return a;
} // requestFromDB
In my PHP script, I would only need to look at $_POST for my values. Then I would just print a response.
Note! Your PHP script MUST be on the same server as the applet for security reasons, or this will not work.
New to java, GWT and interacting with APIs. I have what I hope is a simple question.
I have successfully interacted with a REST API using the following curl command:
curl -d "OPERATION_NAME=ADD_REQUEST&TECHNICIAN_KEY=xxxxxxxxxxx&INPUT_DATA=<?xml version=%221.0%22 encoding=%22utf-8%22?><Operation><Details><requester>Me</requester><subject>Test</subject><description>Testing curl input</description></Details></Operation>" http://xx.xx.xx.xx/sdpapi/request/
Now, from a tutorial, I have the following code that I am hoping will post a request to the remote server just like the curl command above.
What I am trying to figure out (with no love from google) is how I pass the OPERATION_NAME, TECHNICIAN_KEY and INPUT_DATA parameters in when I am sending the URL. Any suggestions, tutorials, etc. will be appreciated.
The following is from my server side implementation interface:
#Override
public String postToRemoteServer(String serviceUrl)
throws HelpDeskTestException {
try {
//dividing url into host: http://some.server
//path: a/path/in/it
//and parameters: this=that&those=others
int hostStart= serviceUrl.indexOf("//");
int pathStart= serviceUrl.substring(hostStart + 2).indexOf("/");
int parameterStart= serviceUrl.substring(hostStart + 2 + pathStart).indexOf("?");
final String serverHost= serviceUrl.substring(0, hostStart + pathStart + 2);
final String serverPath= serviceUrl.substring(hostStart + 3,
hostStart + pathStart + 2 + parameterStart);
final String serverParameters= serviceUrl.substring(hostStart + pathStart + 3 + parameterStart);
final URL url = new URL(serverHost);
final URLConnection connection= url.openConnection();
connection.setDoOutput(true);
final OutputStreamWriter out= new OutputStreamWriter(connection.getOutputStream());
final BufferedReader in= new BufferedReader(new InputStreamReader(
connection.getInputStream()));
out.write("POST " + serverPath + "\r\n");
out.write("Host: " + serverHost + "\r\n");
out.write("Accept-Encoding: identity\r\n");
out.write("Connection: close\r\n");
out.write("Content-Type: application/x-www-form-urlencoded\r\n");
out.write("Content-Length: " + serverParameters.length() + "\r\n\r\n" +
serverParameters + "\r\n");
String result = "";
String inputLine;
while ((inputLine=in.readLine()) != null) {
result+= inputLine;
}
in.close();
out.close();
return result;
} catch (final Exception e) {
throw new HelpDeskTestException();
}
Consider using this library: Apache HttpClient. Here is an example of making a POST request with it.