Grab IMG source from HTML link - java

I have this HTML code that I took from IMDB.
<img alt="Johnny Depp" height="209" src="https://m.media-amazon.com/images/M/MV5BMTM0ODU5Nzk2OV5BMl5BanBnXkFtZTcwMzI2ODgyNQ##._V1_UY209_CR3,0,140,209_AL_.jpg" width="140">
My question is how can I get the link of the image with <img src=,so the result will be:
"<img src="https://m.mediaamazon.com/images/M/MV5BMTM0ODU5Nzk2OV5BMl5BanBnXkFtZTcwMzI2ODgyNQ##._V1_UY209_CR3,0,140,209_AL_.jpg">
Thanks !

For parsing or scraping from URL, you need to add JSoup library.
Add the dependency in your gradle file.
implementation 'org.jsoup:jsoup:latest_version'
Then you can write a method to connect and get the HTML code.
private String getHTMLCode() {
try {
Document doc = Jsoup.connect("http://www.yourURL.com/").get();
Element imageElement = document.select("img").first();
String absoluteUrl = imageElement.absUrl("src"); //absolute URL on src
String srcValue = imageElement.attr("src"); // exact content value of the attribute.
} catch (IOException e) {
//For getting error print error in LOG
Log.d(TAG, e.getLocalizedMessage());
Log.e(TAG, "Failed to load HTML code", e);
Toast.makeText(this, "Failed to load HTML code",
Toast.LENGTH_SHORT).show();
}
}
For further documentation you can get help from the official site.

Related

Get JpegImage.aspx captcha from URL in android

I am relatively new to programming. I need to fill a form on a url through an Android APP with:
Dropdown menu
TextField
Captacha (Image and TextField)
I will use post requests through JSOUP for 1 and 2.
For 3:
I have gone through the html of the page and the captcha image seems like this:
img id="ctl00_ContentPlaceHolder1_capchaImage" src="JpegImage.aspx"
style="height:50px;width:100%;"
I'm currently able to get captcha image url but unable to display it in Android ImageView. Following is my code:
try {
Bitmap captchaimg = null;
String B = "https://whatever.com";
Document doc2 = Jsoup.connect(B).get();
Element captcha = doc2.select("#ctl00_ContentPlaceHolder1_capchaImage").first();
imgsrc = captcha.attr("abs:src");
System.out.println("\nsrc : " + imgsrc);
InputStream inputStream = new URL(imgsrc).openStream();
captchaimg = BitmapFactory.decodeStream(inputStream);
}
catch (IOException e)
{
builder.append("Error : ").append(e.getMessage()).append("\n");
}
runOnUiThread(new Runnable()
{
#Override
public void run() {
imagev.setImageBitmap(captchaimg);
});
This is the problem that I am actually having.
P.S. The source code of the aspx captcha is given on this site CAPTCHA

How to get a shared link of recently uploaded file when using box in Android?

How can I get a shared link of a recently uploaded file when using box in Android.
mFileApi.getCreateSharedLinkRequest(fileId).setCanDownload(true)
.setAccess(BoxSharedLink.Access.OPEN)
.toTask().addOnCompletedListener(new BoxFutureTask.OnCompletedListener<BoxFile>() {
#Override
public void onCompleted(BoxResponse<BoxFile> response) {
if (response.isSuccess()) {
BoxFile boxFile = response.getResult();
String downloadUrl = boxFile.getSharedLink().getDownloadURL();
Log.e("downloadurl", "onCompleted: " + downloadUrl);
//This return me a web link to show the Box page to download the file
} else {
Toast.makeText(MainActivity.this, "error while getting sharelink", Toast.LENGTH_SHORT).show();
}
}
}).run();
You must first create the link, it is not created automatically. See this answer how to do it: How to create shared link in box using java sdk

How to display DynamicReports in browser without download to cliend drive?

I have to display some reports with Dynamic Reports. I use NetBeans and Tomcat 7. Eventually, all must be uploaded to cloud OpenShift. I used DynamicReports to create simple report (code snippet):
Connection conn=null;
try {
Class.forName(DBConnStrings.driver);
conn = DriverManager.getConnection(DBConnStrings.url + DBConnStrings.dbName+DBConnStrings.sslState, DBConnStrings.userName, DBConnStrings.password);
} catch (Exception e) {
e.printStackTrace();
}
JasperReportBuilder report = DynamicReports.report();
report
.columns(
Columns.column("Tank Id", "id", DataTypes.integerType()),
Columns.column("Tank Name", "name", DataTypes.stringType()),
Columns.column("Label", "label", DataTypes.stringType()),
Columns.column("Description", "descrshort", DataTypes.stringType()));
report.setDataSource("SELECT id, name, label, descrshort FROM "+ DBConnStrings.dbName +".tbltankslist", conn);
try {
//show the report
//report.show();
//export the report to a pdf file
report.toPdf(new FileOutputStream("c:/report.pdf"));
} catch (DRException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
This code located in a Servlet. It works. I get JasperViewer at first and a report.pdf on my HDD. But I don't want it. First I do not want to see JasperViewer, second I do not want to download file to client HDD. How to display report inside web-browser only?
Here is the question Jasper Reports. It is about jasper reports + iReport and I have no idea how to use that information for DynamicReports - at first, second there is also "download pdf to client drive" approach, but I need to show it inside the browser.
use the following code in your file which redirect towards jasper invocation page, so that your jasperPDF should open in new tab instead of downloading.
JasperInvocation.jsp => file in which you invoke jasperReport
<form method="POST" action="JasperInvocation.jsp" target="_blank">
Please find following code , I have implemented in Dynamic report(Jasper Api) , Its working for me :-
#RequestMapping(value="/pdfDownload", method = RequestMethod.GET)
public void getPdfDownload(HttpServletResponse response) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
report().columns().setDataSource().show()
.toPdf(buffer);
byte[] bytes = buffer.toByteArray();
InputStream inputStream = new ByteArrayInputStream (bytes);
IOUtils.copy(inputStream, response.getOutputStream());
response.setHeader("Content-Disposition", "attachment; filename=Accepted1.pdf");
response.flushBuffer();
}

Android - Unhandled java.net.MalformedURLException

I'm getting a MalformedURLException some code in my Android Studio project. My aim is to get and display an image from a web page, and the URL seems to be fine, but it's giving me this error.
I have already put the code in a try,catch, but that is still giving me the error.
Here is the code to grab the image and display it:
try
{
url = new URL(items.get(position).getLink());
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
}
catch (IOException e)
{
throw new RuntimeException("Url Exception" + e);
}
holder.itemTitle.setText(items.get(position).getTitle());;
holder.itemHolder.setBackgroundDrawable(new BitmapDrawable(bmp));
items.get(position).getLink() is meant to get the link that is being displayed in a ListView, but even something like URL url = new URL("https://www.google.com") doesn't work.
Thanks.
your url is formatted without the protocol at the beginning try
url = new URL("http://"+items.get(position).getLink());
sometimes the url string may have special characters, in which case you need to encode it properly please see this.
And also, the url you posted in the comment is not an image.
it is exception beacuse of url class
add antoher catch like
catch (MalformedURLException e) {
e.printStackTrace();
}
Just click alt+enter and then import try catch section... this helped me...

Attaching screenshots to TestNG Failed methods results

I am looking for a way to attach a screenshot to Results section of TestNG Report for the failed methods.
So far I was able to attache my screenshots to Reporter Output by implementing this:
Reporter.log("<br> <img src=.\\screenshots\\" + fileName + " /> <br>");
but still struggling with adding them to Test Results section of failed methods.
I was able to implement Listener and intercept onTestFailure actions which was originally suggested here:
How can I include a failure screenshot to the testNG report
Here is an example of that:
#Override
public void onTestFailure(ITestResult result) {
Reporter.setCurrentTestResult(result);
Reporter.log("<br> <img src=.\\screenshots\\Untitled.png /> <br>");
Reporter.setCurrentTestResult(null);
}
But Reporter.log function still pushes my information in the Reporter output log but not in the Results->Failed methods->Failed method log.
Update (03/14/14): I've attached screenshot to clarify my question. The problem is not in capturing screenshot and attaching it to Report. That part works fine. The problem is that screenshot is attached to Test Output part of the report but I want to see it in Results -> Failed Methods.
I have also implemented the same extending Testng TestListenerAdapter. By capturing the screenshot then attach it to the Testng Report with the image of size height=100 and width=100 with onTestFailure. Please see below if this helps solve your problem
File scrFile = ((TakesScreenshot) WebdriverManager.globalDriverInstance).getScreenshotAs(OutputType.FILE);
//Needs Commons IO library
try {
FileUtils.copyFile(scrFile, new File(file.getAbsolutePath()+ "/selenium-reports/html/" + result.getName() + ".jpg"));
Reporter.log("<a href='"+ file.getAbsolutePath()+"/selenium-reports/html/" + result.getName() + ".jpg'> <img src='"+ file.getAbsolutePath()+"/selenium-reports/html/"+ result.getName() + ".jpg' height='100' width='100'/> </a>");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Reporter.setCurrentTestResult(null);
In addition to above don't forget to add following lines to your testng suite xml
<listeners>
<listener class-name="com.tests.DotTestListener" />
</listeners>
OR
passing as listner parameter if you are executing it from command line
java -classpath testng.jar;%CLASSPATH% org.testng.TestNG -listener com.tests.DotTestListener test\testng.xml
Reference : http://testng.org/doc/documentation-main.html#logging-listeners
I've had same problem but it solved. By implementing SuitePanel you will be able to add screenshot as you want
https://github.com/cbeust/testng/blob/master/src/main/java/org/testng/reporters/jq/SuitePanel.java
I almost don't change the original code except
...
// Description?
String description = tr.getMethod().getDescription();
if (! Strings.isNullOrEmpty(description)) {
xsb.push("em");
xsb.addString("(" + description + ")");
xsb.pop("em");
}
// Add screen shot here
xsb.push(“img”,”src”,imagePath);
xsb.pop(“img”);
xsb.pop(D);
xsb.pop(D);
If you want to show the screen shot on the failed method then you will have to capture the exception and modify its message content and add img html to that and then it will appear. Let me know if you need example
I had same issue but its fixed now. I made a method to catcher screenshot in base class. this method return full path of screenshot.
public String getScreenshot (String screenshotName, WebDriver driver) throws IOException{
DateFormat dateformate = new SimpleDateFormat("dd-mm-yy-hh-mm-ss");
Date date = new Date();
String currentdate = dateformate.format(date);
String imageName =screenshotName+currentdate;
TakesScreenshot ts=(TakesScreenshot)driver;
File source=ts.getScreenshotAs(OutputType.FILE);
String location =System.getProperty("user.dir")+"\\testOutput\\screenshot\\"+imageName+".png";
File screenshotLocation =new File (location);
FileUtils.copyFile(source, screenshotLocation);
return location;
}
Add use this path to add screenshot in testng report as well as report log by updating testng TestNgListener-
public void onTestFailure(ITestResult arg0) {
Object currentClass = arg0.getInstance();
WebDriver driver = ((BrowserSetup) currentClass).getDriver();
String name = arg0.getName();
System.out.println(name);
try {
String screenshotPath =getScreenshot(name, driver);
System.out.println("Screenshot taken");
String path = "<img src=\"file://" + screenshotPath + "\" alt=\"\"/>";
System.out.println(screenshotPath+" and path - "+path);
Reporter.log("Capcher screenshot path is "+path);
} catch (Exception e) {
System.out.println("Exception while takescreenshot "+e.getMessage());
}
printTestResults(arg0);
}
I suggest you to use ReportNG instead of the primitive TestNG reports.
If the problem only with getting screenshots, you can try to get it like this:
private static byte[] GetCropImg(IWebDriver targetChrome, IWebElement targetElement)
{
var screenshot = ((ITakesScreenshot)targetChrome).GetScreenshot();
var location = targetElement.Location;
using (MemoryStream stream = new MemoryStream(screenshot.AsByteArray))
{
var rect = new Rectangle(location.X, location.Y, targetElement.Size.Width, targetElement.Size.Height);
using (Bitmap bmpImage = new Bitmap(stream))
{
using (Bitmap cropedImag = bmpImage.Clone(rect, bmpImage.PixelFormat))
{
using (MemoryStream ms = new MemoryStream())
{
cropedImag.Save(ms, ImageFormat.Jpeg);
byte[] byteImage = ms.ToArray();
return byteImage;
}
}
}
}
}
and then you can save file or save sting64
var imgString64 = Convert.ToBase64String(byteImage); //Get Base64
PS: on JAVA it should be almost the same)
you can get failed test cases screen shots with name of failed test class by using #After method.
Use below code segment

Categories