I'm developing an Web JEE5 Application, I need to log the http post and get parameters, What is the best way?
At the beginning I tried with HttpRequest->getQueryString, but it doesn't work with post parameters,
then I wrote a code that uses HttpRequest->getParameterMap (see below)
Map<String,String[]> parametersName=theRequest.getParameterMap();
int count=0;
for (String paramName : parametersName.keySet()) {
String[] paramValues=parametersName.get(paramName);
if(count>0)
allParameter.append("&");
allParameter.append(paramName);
allParameter.append("=");
for (int i = 0; i < paramValues.length; i++) {
allParameter.append(paramValues[i]);
if(paramValues.length>1)
allParameter.append(",");
}
count++;
}
It works but it seems too complicated (compared with getQueryString) for the works to do.
Is there a better/faster way?
All HTTP (and application servers) support access.log - the log file that stores the HTTP requests and responses details. Just configure it.
you can also do it like this:
Enumeration parms = request.getHeaderNames();
String parmname;
String parmval;
while (parms.hasMoreElements()) {
parmname = (String)parms.nextElement();
parmval = request.getHeader(parmname);
Logger.log(parmname + " - " + parmval);
}
Related
I am trying to get the index status for a very large index using the Java API. In the background, I am updating the same index with large amounts of data
I have tried
IndicesStatsResponse indicesStatsResponse = client.admin().indices()
.prepareStats(index_name).all().execute().actionGet();
but this does not return the correct size because it is a very large index. However using the REST call, I got the correct answer.
GET /index_name/_stats
Perhaps I need to use some kind of listener mechanism, so I tried
IndicesStatsRequest req = new IndicesStatsRequest();
req.all();
client.admin().indices().stats(req, new ActionListener<IndicesStatsResponse>()
{
#Override
public void onResponse(IndicesStatsResponse response)
{
long s = response.getIndex(indexName).getTotal().getStore().getSizeInBytes();
System.out.println(indexName + " " + s);
}
..
});
but this threw org.elasticsearch.common.util.concurrent.EsRejectedExecutionException
I also tried
IndicesStatsRequest req = new IndicesStatsRequest();
req.all();
ActionFuture<IndicesStatsResponse> statsResponseFeature = client.admin().indices().stats(req.clear().flush(true).refresh(true));
IndicesStatsResponse statsResponse = statsResponseFeature.get(1, TimeUnit.MINUTES);
But this did not retrieve any useful information.
Strangely enough, when I run it in debug mode in Eclipse, it works perfectly. So maybe there is some flush mechanism I am missing.
What is the way out?
I would like to know how to get the API end point of a TestStep in SoapUI Xml using Java.
I have used the following,
for (int i=0; i<numberOfTestSteps; i++) {
WsdlTestStep testStep = testCase.getTestStepAt(i);
WsdlTestCaseRunner runner = new WsdlTestCaseRunner(testCase, new StringToObjectMap());
runner.runTestStep(testStep);
List<TestStepResult> resultList = runner.getResults();
for (TestStepResult result : resultList) {
String endPoint = ((MessageExchange)result).getEndpoint();
System.out.println("End Point = " + endPoint);
}
}
It only gives "www.test.com:8080". But I need the API end point as in the image.
Please someone help me to solve this.
Below should give you what you are looking for:
String resourcePath = ((MessageExchange)result).getResource().getFullPath();
System.out.println("Resource Path = " + resourcePath);
You may look at respective SoapUI's API
There is very simply way too if you wish to show that value from with SoapUI Project itself.
In the test case, there might be a REST Request Test step type. Add a Script Assertion as shown below:
log.info messageExchange.endpoint
I'm trying to code a little program in Java, with a small UI, that lets you use some google search's keyword to improve your search.
I have 2 text field (one for the site and one for the keywords) and 2 date pickers to let the user select the date range for the searching result .
When I press the search button it will connect to the following url:
"https://www.google.it/search?q=" + site + Keywords + daterange
site = "site:SITE_MAIN_URL"
keywords are the keywords i am looking for
daterange = "daterange:JULIAN_DATE_1 - JULIAN_DATE_2"
after all this I fetch the first 10 result, but here's the problem...
If I select no dates I can easily fetch the links
If I set the daterange I get the HTTP 503 error that is the one for service unavailable (if I paste the generated URL on my web browser everything works fine)
(the User Agent is set to mozilla 5.0)
EDIT: didn't post any code :P
//here i generate the site
site = "site:" + website_field.getText();
//here i convert the dates using a class found on the net
d1 = (int) DateLabelFormatter.dateToJulian(date1);
d2 = (int) DateLabelFormatter.dateToJulian(date2);
daterange += "+daterange:" + d1 + "-" + d2;
//here i generate the keywords
keywords = keyword_field.getText();
String[] keyword = keywords.split(" ");
for (int i = 0; i < keyword.length; i++) {
tempKeyword += "+" + keyword[i];
}
//the query
query = "https://www.google.it/search?q=" + site + tempKeyword + daterange;
//the connection (wrapped in a try-catch)
Document jSoupDoc = Jsoup.connect(query).userAgent("Mozilla/5.0").timeout(5000).get();
//fetching the links
Elements links = jSoupDoc.select("a[href]");
Element link;
for (int i = 0; i < links.size(); i++) {
link = links.get(i);
String temp = link.attr("href");
// filtering the first 10 google links
if (temp.contains("url")) //donothing
if (temp.contains("webcache")) { //donothing
} else {
String[] splitTemp = temp.split("=");
String[] splitTemp2 = splitTemp[1].split("&sa");
System.out.println(splitTemp2[0]);
}
}
After executing all this (NotSoWellWritten)code if i select no date, and i use just the "site" and the "keywords" I can see on the console the first 10 result found on the google search page.
If i select a daterange from the datepickers i get the 503 error.
If you wanna try a working query, here's one that search on facebook.com the keyword "dog" starting from the 1st of november to the 15th generated with this "tool"
https://www.google.it/search?q=site:facebook.com+dog+daterange:2457328-2457342
`
I have no problems using the following code:
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Main
{
public static void main(String[] args) throws IOException
{
// the connection (wrapped in a try-catch)
Document jSoupDoc = Jsoup.connect("https://www.google.it/search?q=site:facebook.com+dog+daterange:2457328-2457342").userAgent("Mozilla/5.0").timeout(5000).get();
// fetching the links
Elements links = jSoupDoc.select("a[href]");
Element link;
for (int i = 0; i < links.size(); i++)
{
link = links.get(i);
String temp = link.attr("href");
// filtering the first 10 google links
if (temp.contains("url") && !temp.contains("webcache"))
{
String[] splitTemp = temp.split("=");
String[] splitTemp2 = splitTemp[1].split("&sa");
System.out.println(splitTemp2[0]);
}
}
}
}
The code gives this as output on my computer:
https://www.facebook.com/uniladmag/videos/1912071728815877/
https://it-it.facebook.com/DogEvolutionAsd
https://it-it.facebook.com/DylanDogSergioBonelliEditore
https://www.facebook.com/DelawareCountyDogShelter/
https://www.facebook.com/LostDogAlert/
https://it-it.facebook.com/pages/Toelettatura-Vanity-DOG/270854126382923
https://it-it.facebook.com/washdogsgm
https://www.facebook.com/thedailystar/videos/1193933410623520/
https://www.facebook.com/OakhurstDogPark/
https://www.facebook.com/bigdogdinerco/
A 503 error usually means that the web server is having temporary issues. Specifically:
503: The Web server (running the Web site) is currently unable to handle the HTTP request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay.
If this code works but your original code still does not, then your code is not generating the URL you posted and you should investigate further.
Besides the coding style, I don't see any functional problems with the provided code and it supplies the answers correctly (tested it locally). The problem might reside in the dateToJulian which I don't know what it returns and how the result is cast to int (if information is lost).
Also, consider the case in which the keywords contain dangerous characters and they are unescaped. They should be sanitized beforehand.
Another possibility is that Google is rejecting your queries if you are sending too many too fast. If this was done using a visual browser, you'd get a "We want to make sure you're not a robot." and a CAPTCHA page. That is why I'd recommend leveraging the Google API for your searches. See this SO for more info: How can you search Google Programmatically Java API
I don't have soap ui pro. I am testing the web service. The actual implementation is i need pass one error code on the request, and the corresponding error description should be displayed on the response. I need to add this assertion. Every time the description in the response varies.
Here is the thing i want exactly...
Every time i need to run the same request but the error code (which is input) only should be changed on each time and the description varies on the response. How to validate this? Is there any way to do this without data source.
Regards,
Chandra
This is the way i have created.. is there any way to improve the code to do better way;
import java.io.File;
File file = new File('c:/customers.csv');
InputStream inputFile = new FileInputStream(file);
String[] lines = inputFile.text.split('\n');
List<String[]> rows = lines.collect {it.split(',')}
log.info('There are ' + rows.size() + ' customers to be inserted');
for(int i = 0; i < rows.size(); i++) {
String[] row = rows.get(i);
String errorcode = row[0];
// log.info(errorcode)
String errorDescription = row[1];
//log.info(errorDescription)
testRunner.testCase.testSuite.project.setPropertyValue('errorcode', errorcode);
testRunner.testCase.testSuite.project.setPropertyValue('errorDescription', errorDescription);
testRunner.runTestStepByName("createCard-1");
log.info(errorcode +"Finsihed")
}
I am going to use RESTful Web Services and HttpClient to access Facebook API REST Server.
Am somewhat of a newbie to REST and Facebook APIs...
Question(s):
Verification / Authorization
(1) If I have a session key sent by a client app, how do I verify and authenticate that the user exists and then query for his / her friends on the server side?
How can I be access these Facebook RESTful end points:
http://wiki.developers.facebook.com/index.php/Users.getInfo
and
http://wiki.developers.facebook.com/index.php/Friends.getLists
via a HTTP GET Request? Meaning, what does the full URL look like including parameters?
(2) What would the full RESTful URL look like to grab the APIs (which I have listed above)?
Posting to a Friend's Wall
(3) After verification / authorization, querying users friends, how (which API) would I use to a post to a Friend's Wall?
(4) Is there any additional parameters that I need to append to the Facebook RESTful Server's URL?
HTTP Client
(5) Do I include the RESTful web service calls to these Facebook APIs inside my Java program through HttpClient?
Happy programming and thank you for taking the time to read this...
I can't answer all your questions but the method calls are made via http://api.facebook.com/restserver.php so a call to users.getInfo looks like this
http://api.facebook.com/restserver.php?method=users.getinfo
You also need to pass in your api key and any other parameters the method needs. But rather than make the http calls yourself there must be some Java library that abstracts all this away for you.
As for this being a REST API - there's one web service endpoint with method scoping in the URL and all calls are made via HTTP GET or POST.
Frankly, this is RPC over HTTP and about as far from REST as you can get (no pun intended!). Facebook should change their API documentation, it's just plain wrong.
In terms of creating the URL, I've used this code which seems to work pretty well...
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;
// Written by Stuart Davidson, www.spedge.com
public class JSONComm
{
private final String JSON_URL = "http://api.facebook.com/restserver.php";
private final String fbSecretKey = "xxx";
private final String fbApiKey = "xxx";
private final String fbApiId = "xxx";
private int callId = 0;
public int getNextCall() { callId++; return callId; }
public String getApiKey() { return fbApiKey; }
public String getApiId() { return fbApiId; }
public String getRestURL(HashMap<String, String> args)
{
String url = JSON_URL + "?";
for(String arg : args.keySet()) { url = url + arg + "=" + args.get(arg) + "&"; }
String sig = getMD5Hash(args);
url = url + "sig=" + sig;
return url;
}
public String getMD5Hash(HashMap<String, String> args)
{
String message = "";
Vector<String> v = new Vector<String>(args.keySet());
Collections.sort(v);
Iterator<String> it = v.iterator();
while(it.hasNext())
{
String tmp = it.next();
message = message + tmp + "=" + args.get(tmp);
}
message = message + fbSecretKey;
try{
MessageDigest m = MessageDigest.getInstance("MD5");
byte[] data = message.getBytes();
m.update(data,0,data.length);
BigInteger i = new BigInteger(1,m.digest());
return String.format("%1$032X", i).toLowerCase();
}
catch(NoSuchAlgorithmException nsae){ return ""; }
}
}
Make sure you see the critical components - the fact that the arguments are alphabetically sorted, and that the whole thing is encrypted using MD5, but the string that is encrypted is slightly different than the URL string.
Also note that the API keys need to be filled in!
So, to get the URL for the method User.getInfo and return the first and last names, I'd do the following...
public String getFbURL(String callback, Long playerId)
{
HashMap<String, String> args = new HashMap<String, String>();
args.put("api_key", jsonComm.getApiKey());
args.put("call_id", "" + jsonComm.getNextCall());
args.put("v", "1.0");
args.put("uids", "" + playerId);
args.put("fields", "first_name,last_name");
args.put("format", "JSON");
args.put("method", "Users.getInfo");
args.put("callback", "" + callback);
return jsonComm.getRestURL(args);
}
Hope this helps :)