I have the following code to get the tock price from yahoo finance.hk
But it always return time out error
please help
public GetStockPriceFromWebOneByOne(String url){
this.url = url;
}
private void setDataFromAAStock() throws IOException, InterruptedException{
Document document = Jsoup.connect(url).ignoreHttpErrors(true).timeout(timeOut*1000).get(); // s
//TimeUnit.SECONDS.sleep(2);
Elements answerers = document.select("div.yfi_rt_quote_summary div.yfi_rt_quote_summary_rt_top.sigfig_promo_0 span.time_rtq_ticker");
// Elements answerers = document.select(".content .inline_block.vat.float_l .boxForex .font26 .neg .arr_ud.arrow_d6");
for (Element answerer : answerers) {
//System.out.print(answerer.text()+"\n");
price = answerer.text();
// splitString(answerer.text());
}
}
public String getDataFromAAStock() throws IOException, InterruptedException{
setDataFromAAStock();
return price;
}
I did not check with yahoo finance hk, but you maybe should try to set a plausible browser userAgent string when connecting to it. See the docs
Document document = Jsoup.connect(url)
.ignoreHttpErrors(true)
.timeout(timeOut*1000)
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
Addendum:
Of course, you can turn off the timeout altogether by using:
Document document = Jsoup.connect(url)
.ignoreHttpErrors(true)
.timeout(0)
Did you look at the network traffic between the browser and the site with the browser developer tools? It might help you to analyze the underlying problem.
I would split the
Document document = Jsoup.connect(url).ignoreHttpErrors(true).timeout(timeOut*1000).get();
into
Connection connect = Jsoup.connect(url)
.ignoreHttpErrors(true)
.timeout(timeOut*1000);
// use this for chrome
.userAgent("Mozilla");
System.out.println("Connection made BEFORE document.");
Document document = connect.get();
System.out.println("Connection made AFTER document.");
I think there is an issue with your "Connection" because of the .get() which may need a .userAgent("Mozilla"); BEFORE you call .get();.
Related
I am using the method "GetPointsByQueryAsync" when I use it for a small number of test cases (as input) it is working fine but when I use it for a large number of test cases (as input), it messes up like some test points will miss, when I try to get miss points separately, it works fine. I have posted this issue on the Visual studio community, they refuse to fix it and said it is not our policy to look into this issue. I have a test case count of 3000 and a test point count of 15000.
https://developercommunity.visualstudio.com/t/Missing-Test-Points-using-Net-sdk/10215409
using Microsoft.TeamFoundation.TestManagement.WebApi;
public List<TestPoint> GetTestPoints(Uri uri, string oAuthAccessToken, List<int> testcaseIds)
{
TestPointsQuery outputQuery= null;
try
{
VssOAuthAccessTokenCredential mCredential = new VssOAuthAccessTokenCredential(oAuthAccessToken);
VssConnection connection =
new VssConnection(uri, mCredential);
TestManagementHttpClient testManagementHttpClient = connection.GetClient<TestManagementHttpClient>();
TestPointsQuery query = new TestPointsQuery();
PointsFilter filter = new PointsFilter();
filter.TestcaseIds = testcaseIds;
query.PointsFilter = filter;
outputQuery = testManagementHttpClient.GetPointsByQueryAsync(query, WIProject.Id).Result;
}
catch (Exception e)
{
Console.WriteLine(e);
}
return outputQuery.Points;
}
I'm having trouble trying to consume the Response of an HTTP Endpoint which Streams real-time events continously. It's actually one of Docker's endpoints: https://docs.docker.com/engine/api/v1.40/#operation/SystemEvents
I am using Apache HTTP Client 4.5.5 and it just halts indefinitely when I try to consume the content InputStream:
HttpEntity entity = resp.getEntity();
EntityUtils.consume(entity);//it just hangs here.
//Even if I don't call this method, Apache calls it automatically
//after running all my ResponseHandlers
Apparently, it can be done by using JDK's raw URL: Stream a HTTP response in Java
But I cannot do that since local Docker communicates over a Unix Socket which I only managed to configure in Apache's HTTP Client with a 3rd party library for Unix Sockets in Java.
If there is a smarter HTTP Client library which I could switch to, that would also be an option.
Any ideas would be greatly appreciated. Thank you!
I managed to solve this issue by generating an infinite java.util.stream.Stream of JsonObject from the response InputStream (I know the json reading part is not the most elegant solution but there is no better way with that API and also, Docker doesn't send any separator between the jsons).
final InputStream content = response.getEntity().getContent();
final Stream<JsonObject> stream = Stream.generate(
() -> {
JsonObject read = null;
try {
final byte[] tmp = new byte[4096];
while (content.read(tmp) != -1) {
try {
final JsonReader reader = Json.createReader(
new ByteArrayInputStream(tmp)
);
read = reader.readObject();
break;
} catch (final Exception exception) {
//Couldn't parse byte[] to Json,
//try to read more bytes.
}
}
} catch (final IOException ex) {
throw new IllegalStateException(
"IOException when reading streamed JsonObjects!"
);
}
return read;
}
).onClose(
() -> {
try {
((CloseableHttpResponse) response).close();
} catch (final IOException ex) {
//There is a bug in Apache HTTPClient, when closing
//an infinite InputStream: IOException is thrown
//because the client still tries to read the remainder
// of the closed Stream. We should ignore this case.
}
}
);
return stream;
I am trying to connect a to Neo4j Aura instance from a .NET core 2.2 web api. I understand I need the Neo4j .Net Driver v4.0.0-alpha01, but I do not seem to be able to connect. There aren't very many examples out there as this driver is new and so is Aura.
I keep getting:
Failed after retried for 6 times in 30000 ms. Make sure that your database is online and retry again.
I configure the driver as such
public void ConfigureServices(IServiceCollection services)
{
string uri = "neo4j://1234567.databases.neo4j.io:7687";//not actual subdomain
string username = "neo4j";
string password = "seeeeeeecret";//not actual password
services.AddCors();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSingleton(GraphDatabase.Driver(uri, AuthTokens.Basic(username, password)));
}
and in my test controller i run this
private async Task<string> Neo4JTestAsync()
{
string db = "MyDb";
string message = "TESTMESSAGE";
IAsyncSession session = _driver.AsyncSession(o => o.WithDatabase(db));
try
{
var greeting = session.WriteTransactionAsync(async tx =>
{
var result = tx.RunAsync("CREATE (a:Greeting) " +
"SET a.message = $message " +
"RETURN a.message + ', from node ' + id(a)",
new { message });
var res = await result;
return "return something eventually";
});
return await greeting;
}
catch (Exception e)
{
return e.Message; // throws "Failed after retried for 6 times in 30000 ms. Make sure that your database is online and retry again"
}
finally
{
await session.CloseAsync();
}
}
I can't get the exact error message you do - but I'm pretty sure this is due to encryption - one of the big differences between the 1.x and 4.x drivers is the default position on Encryption - which is now off by default.
So you'll want to change your initialisation to:
services.AddSingleton(GraphDatabase.Driver(uri, AuthTokens.Basic(username, password), config => config.WithEncryptionLevel(EncryptionLevel.Encrypted)));
That should get you going. Also - make sure you stick with the neo4j:// protocol, as that'll route you properly.
Have you tried bolt:// in the connection string?
string uri = "bolt://1234567.databases.neo4j.io:7687";//not actual subdomain
I am trying to test ActiveMQ connection and return a value. it crashes on line:
httpResponse = client.execute(theHttpGet);
It is not my code I am trying to debug it. Can anyone help me to understand why the code is using HttpGet?
public ActivemqBrokerInfo(String serverAddress, int port, String apiUrl, int timeout) {
// Default Activemq location
this.serverAddress = String.format("http://%s:%s/%s", serverAddress, port, apiUrl);
int timeoutInMs = timeout;
HttpClientBuilder builder = HttpClientBuilder.create();
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutInMs).build();
builder.setDefaultRequestConfig(requestConfig);
client = builder.build();
}
public ActivemqBrokerInfo(String serverAddress) {
this(serverAddress, DEFAULT_PORT, DEFAULT_API_URL, DEFAULT_TIMEOUT);
}
#Override
public boolean testConnection() {
HttpGet theHttpGet = new HttpGet(serverAddress);
theHttpGet.addHeader("test-header-name", "test-header-value");
HttpResponse httpResponse = null;
try{
httpResponse = client.execute(theHttpGet);// Code is crashing on this line
} catch (IOException ex){
LOGGER.error("Broker down: ", ex);
}
return httpResponse != null;
}
When ActiveMQ runs is normally starts an embedded web server. This web server is used to host the web admin console as well as the Jolokia endpoint which acts as an HTTP facade in front of the broker's MBeans. In other words, any client can send HTTP requests to specially formed URLs on the broker to get results from the underlying management beans. This is exactly what your bit of code appears to be doing. It appears to be sending an HTTP request to the Jolokia endpoint (i.e. api/jolokia) in order to determine if the broker is alive or not.
Based on the information provided it is impossible to determine why testConnection() is not returning successfully since you've included no information about the configuration or state of the broker.
I recommend you add additional logging to see what may be happening and also catch Exception rather than just IOException.
I am trying to write a function that takes an input URL of any Stack Overflow link, gets the source code of the page, parses it, gets the accepted answer, and also gets the answer with the most upvotes.
I am new to this and I don't know how to do this. This is what I've tried out. It just returns the first answer using jsoup.
protected void doHtmlParse(String url) {
// TODO Auto-generated method stub
Document doc;
try {
doc = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com")
.get();
Element answer = doc.select("td[class=answercell]").get(0);
System.out.println("Answer is \n" + answer.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I only need to display the answer part, but it has to be the accepted answer. How do I approach this?
You don't really need to parse html. Use their REST API.
Have a look.
Here's an example. Note the is_accepted attribute.
EDIT:
Well, after you've got the chosen answer through the API, you could do this:
String answer = document.getElementById("answer-"+id).outerHtml();
I am now able to get the accepted answer via this code.
protected void doHtmlParse(String url) {
// TODO Auto-generated method stub
Document doc;
try {
doc = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com")
.get();
Element answer = doc.select("div[class=answer accepted-answer]").first();
Elements tds = answer.getElementsByTag("td");
for(Element td : tds) {
String clasname = td.attr("class");
if(clasname.equals("answercell")) {
System.out.println("\n\nAccepted answerrr is \n" + td.text());
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}