Codename One Capture API correct usage - codenameone

I tried to use the following code with the purpose to record some videos with real devices (Android and iPhone) and to see the resulting file sizes. But it doesn't work... it seems to record, but it doesn't play the resulting videos neither on Android nor iOS.
I wrote the following code merging some examples in the Codename One API. What's wrong?
Form hi = new Form("Capture", BorderLayout.center());
Container cnt = new Container(BoxLayout.y());
hi.setToolbar(new Toolbar());
Style s = UIManager.getInstance().getComponentStyle("Title");
FontImage icon = FontImage.createMaterial(FontImage.MATERIAL_VIDEOCAM, s);
FileSystemStorage fs = FileSystemStorage.getInstance();
String recordingsDir = fs.getAppHomePath() + "recordings/";
fs.mkdir(recordingsDir);
try {
for (String file : fs.listFiles(recordingsDir)) {
Button mb = new Button(file.substring(file.lastIndexOf("/") + 1) + " - " + (int) (fs.getLength(recordingsDir + file) / 1024.0 / 1024.0 * 100) / 100.0 + " MB");
mb.addActionListener((e) -> {
try {
Media video = MediaManager.createMedia(recordingsDir + file, true);
hi.removeAll();
hi.add(BorderLayout.CENTER, new MediaPlayer(video));
hi.revalidate();
} catch (IOException err) {
Log.e(err);
}
});
cnt.add(mb);
}
hi.add(BorderLayout.CENTER, cnt);
hi.getToolbar().addCommandToRightBar("", icon, (ev) -> {
try {
String file = Capture.captureVideo();
if (file != null) {
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MMM-dd-kk-mm");
String fileName = sd.format(new Date());
String filePath = recordingsDir + fileName;
Util.copy(fs.openInputStream(file), fs.openOutputStream(filePath));
Button mb = new Button(file.substring(file.lastIndexOf("/") + 1) + " - " + (int) (fs.getLength(filePath) / 1024.0 / 1024.0 * 100) / 100.0 + " MB");
mb.addActionListener((e) -> {
try {
Media video = MediaManager.createMedia(filePath, true);
hi.removeAll();
hi.add(BorderLayout.CENTER, new MediaPlayer(video));
hi.revalidate();
} catch (IOException err) {
Log.e(err);
}
});
cnt.add(mb);
cnt.getParent().revalidate();
}
} catch (IOException err) {
Log.e(err);
}
});
} catch (IOException err) {
Log.e(err);
}
hi.show();
This is what I see on iPhone X after tapping a Button to open a recorded video (that is very similar to what I see on Android 7):

I spent so much time looking at this it's embarrassing...
Change this:
Form hi = new Form("Capture", BorderLayout.center());
To this:
Form hi = new Form("Capture", new BorderLayout());
The former gives the component its preferred size. The latter scales it to take up available space. The preferred size is zero on most platforms since the video needs to load for preferred size to apply. When it loads one would need to reflow the layout.

Related

EncodedImage failing to work on actual phone

I am facing a problem while using encodedImage. When a user logins into the app, the first form after successful login has an image. And the image is causing me issues upon retrieving it.
When the user captures an image in the app, I convert it to a base64 string which I send to the server. The code for that is:
ImageIO img = ImageIO.getImageIO();
ByteArrayOutputStream out = new ByteArrayOutputStream();
img.save(et, out, ImageIO.FORMAT_JPEG, 1);
byte[] ba = out.toByteArray();
String userImage64 = Base64.encodeNoNewline(ba);
et is the captured image. So I store the string userImage64 in the server.
When I retrieve the base64, I decode it and convert it to an EncodedImage. The code is:
String url = new JSONObject(result.getResponseData()).getString("photo");
byte[] b = Base64.decode(url.getBytes());
Image icon = EncodedImage.create(b);
When I am on the simulator, everything flows smoothly. The images display and everything works very well.
My issue is, when I put the app on an android device, it doesn't work. It shows me a toast of successful login and just stops there. So i did some debugging and realized that issue is with the three lines of converting from base64 to image. When I comment out the three lines, everything works very well. Where could I be going wrong?
EDIT
Below is the code I use to capture a photo:
String i = Capture.capturePhoto();
if (i != null) {
try {
final Image newImage = Image.createImage(i);
Image roundedMask = Image.createImage(rich.minScreensize() / 4, rich.minScreensize() / 4, 0xff000000);
Graphics gra = roundedMask.getGraphics();
gra.setColor(0xffffff);
gra.fillArc(0, 0, rich.minScreensize() / 4, rich.minScreensize() / 4, 0, 360);
Object masked = roundedMask.createMask();
cropImage(newImage, rich.minScreensize() / 4, rich.minScreensize() / 4, et -> {
if (editing) {
try {
ImageIO img = ImageIO.getImageIO();
ByteArrayOutputStream out = new ByteArrayOutputStream();
img.save(et, out, ImageIO.FORMAT_JPEG, 1);
byte[] ba = out.toByteArray();
userImage64 = Base64.encodeNoNewline(ba);
et = et.applyMask(masked);
logoimage.setIcon(et);
///removed unnecessary code
logoimage.getComponentForm().revalidate();
} catch (IOException ex) {
}
} else {
et = et.applyMask(masked);
logoimage.setIcon(et);
}
});
} catch (IOException ex) {
Log.p("Error loading captured image from camera", Log.ERROR);
}
}
Inside there is code I use to crop the photo and that is code is:
private void cropImage(Image img, int destWidth, int destHeight, OnComplete<Image> s) {
Form previous = getCurrentForm();
Form cropForm = new Form("", new LayeredLayout());
Label toobarLabel = new Label("New Holder", "Toolbar-HeaderLabel");
cropForm.setTitleComponent(toobarLabel);
Toolbar mainToolbar = new Toolbar();
mainToolbar.setUIID("ToolBar");
cropForm.setToolbar(mainToolbar);
Label moveAndZoom = new Label("Move and zoom the photo to crop it");
moveAndZoom.getUnselectedStyle().setFgColor(0xffffff);
moveAndZoom.getUnselectedStyle().setAlignment(CENTER);
moveAndZoom.setCellRenderer(true);
cropForm.setGlassPane((Graphics g, Rectangle rect) -> {
g.setColor(0x0000ff);
g.setAlpha(150);
Container cropCp = cropForm.getContentPane();
int posY = cropForm.getContentPane().getAbsoluteY();
GeneralPath p = new GeneralPath();
p.setRect(new Rectangle(0, posY, cropCp.getWidth(), cropCp.getHeight()), null);
if (isPortrait()) {
p.arc(0, posY + cropCp.getHeight() / 2 - cropCp.getWidth() / 2,
cropCp.getWidth() - 1, cropCp.getWidth() - 1, 0, Math.PI * 2);
} else {
p.arc(cropCp.getWidth() / 2 - cropCp.getHeight() / 2, posY,
cropCp.getHeight() - 1, cropCp.getHeight() - 1, 0, Math.PI * 2);
}
g.fillShape(p);
g.setAlpha(255);
g.setColor(0xffffff);
moveAndZoom.setX(0);
moveAndZoom.setY(posY);
moveAndZoom.setWidth(cropCp.getWidth());
moveAndZoom.setHeight(moveAndZoom.getPreferredH());
moveAndZoom.paint(g);
});
final ImageViewer viewer = new ImageViewer();
viewer.setImage(img);
cropForm.add(viewer);
cropForm.getToolbar().addMaterialCommandToRightBar("", FontImage.MATERIAL_CROP, e -> {
previous.showBack();
s.completed(viewer.getCroppedImage(0).
fill(destWidth, destHeight));
});
cropForm.getToolbar().addMaterialCommandToLeftBar("", FontImage.MATERIAL_CANCEL, e -> previous.showBack());
cropForm.show();
}

Excel corrupted generated with Apache POI returned fronm API REST spring boot

EDIT :
If I hit directly the endpoint from the browser, the file is dowloaded correctly.
So I guess the problem is in the front and the way to create and save the file with the data received.
I have a java/spring boot application where I want to build an API endpoint that creates and returns a downloadable excel file. Here is my controller endpoint:
#GetMapping(path = "/informe/{informeDTO}")
public ResponseEntity<InputStreamResource> generarInforme(#PathVariable(value = "informeDTO") String informeDTOString) throws JsonParseException, JsonMappingException, IOException {
final InformeDTO informeDTO =
new ObjectMapper().readValue(informeDTOString, InformeDTO.class);
List<InformeDTO> listDatosinformeDTO = utilsService.getDatosInformeDTO(informeDTO);
for (InformeDTO informeDTO2 : listDatosinformeDTO) {
logger.debug(informeDTO2);
}
ByteArrayInputStream in = createReport(listDatosinformeDTO);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment; filename=IOPreport.xlsx");
return ResponseEntity.ok().headers(headers)
.contentType(
MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
.body(new InputStreamResource(in));
}
This is the angular controller :
function generarInformeIOP(){
InformesService.generarInformeIOP($scope.informeView.sociedad, $scope.informeView.area, $scope.informeView.epigrafe,
$scope.informeView.cuenta, $scope.informeView.status, $scope.informeView.organizationalUnit,
$scope.informeView.societyGL, $scope.informeView.calculationType, $scope.informeView.provincia, $scope.informeView.financialSegment,
$scope.informeView.loadDateFrom, $scope.informeView.loadDateTo, $scope.informeView.incomeDateFrom, $scope.informeView.incomeDateTo)
.then(
function(response)
{
var blob = new Blob([response.data], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
saveAs(blob, "IOPreport.xlsx");
$scope.informeFunctionality.errorMessage = '';
},
function(errResponse)
{
console.log("ERROR: " + errResponse.data);
$scope.informeFunctionality.errorMessage = "Ha ocurrido un error inesperado: " + errResponse.data.error +
": " + errResponse.data.message;
}
)
}
And the service :
....
$http.get(urls.SERVICE_API + "informe/"+ angular.toJson(informeDTO)).then(
function(response) {
console.log("GenerarInformeIOP - success");
deferred.resolve(response);
}, function(errResponse) {
console.log("GenerarInformeIOP - error");
deferred.reject(errResponse);
});
...
The generation is successfull, the file is downloaded but I think it is corrupted because Excel can't open it.
Are there anything wrong?
EDIT (adding createReport) :
private ByteArrayInputStream createReport(List<InformeDTO> datosInforme) {
ByteArrayInputStream result =null;
try (Workbook workbook = new XSSFWorkbook(); ByteArrayOutputStream out = new ByteArrayOutputStream();) {
Set<String> columns = new LinkedHashSet<String>();
// Coumnas fijas
columns.add("Cuenta");
columns.add("Epigrafe");
columns.add("Descripcion");
columns.add("Total_Importe");
// Columnas dinamicas
/*
* Tedremos que recorrer todas las filas puesto que no sabremos si una traera
* menos periodos que otra de esta manera obtendremos todos los periodos
*/
for (InformeDTO informeDTO : datosInforme) {
for (Map.Entry<String, Double> entry : informeDTO.getTotalByPeriodoContable().entrySet()) {
columns.add(entry.getKey());
}
}
/*
* CreationHelper helps us create instances for various things like DataFormat,
* Hyperlink, RichTextString etc in a format (HSSF, XSSF) independent way
*/
// CreationHelper createHelper = workbook.getCreationHelper();
// Create a Sheet
Sheet sheet = workbook.createSheet("IOPReport");
// Create a Font for styling header cells
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setFontHeightInPoints((short) 14);
headerFont.setColor(IndexedColors.RED.getIndex());
// Create a CellStyle with the font
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
// Create a Row
Row headerRow = sheet.createRow(0);
// Creating cells
int i = 0;
for (String value : columns) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(value);
cell.setCellStyle(headerCellStyle);
i++;
}
// Create Other rows and cells with employees data
int rowNum = 1;
int cellDynamicNum = 0;
for (InformeDTO informeDTO : datosInforme) {
Row row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(informeDTO.getCuenta());
row.createCell(1).setCellValue(informeDTO.getEpigrafe());
row.createCell(2).setCellValue(informeDTO.getDescripcion_epigrafe());
row.createCell(3).setCellValue("No Data");
cellDynamicNum = 4;
for (Map.Entry<String, Double> entry : informeDTO.getTotalByPeriodoContable().entrySet()) {
row.createCell(cellDynamicNum).setCellValue(entry.getValue());
cellDynamicNum++;
}
}
// Resize all columns to fit the content size
for (i = 0; i < columns.size(); i++) {
sheet.autoSizeColumn(i);
}
// Write the output to a file
workbook.write(out);
result = new ByteArrayInputStream(out.toByteArray());
out.close();
workbook.close();
} catch (Exception e) {
logger.debug("Excepcion en la creacion del report " + e);
}
return result;
}
Regards
When building the output here:
result = new ByteArrayInputStream(out.toByteArray());
The workbook is not saved into out until it is closed. So you need to change the order to:
workbook.close()
result = new ByteArrayInputStream(out.toByteArray());
Closing a ByteArrayOutputStream is not necessary but it's fine if you leave it.
I'm not sure why ResponseEntity<InputStreamResource> is used. I've another working solution which use byte-array ResponseEntity<byte[]>. Some of the code snippet are attached below:
After creating the workbook, write it to outputstream:
private final MediaType mediaType = MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
...
...
// at the end
ByteArrayOutputStream stream = new ByteArrayOutputStream();
workbook.write(stream);
return getDownload(stream.toByteArray(), filename, mediaType);
....
Download method:
public static ResponseEntity<byte[]> getDownload(byte[] content, String filename, MediaType mediaType) {
HttpHeaders headers = new HttpHeaders();
headers.setContentLength(content.length);
headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);
headers.set(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION);
headers.setContentType(mediaType);
return new ResponseEntity<>(content, headers, HttpStatus.OK);
}
Let me know if this works.
I resolved it adding the reponse type in the front call:
var config = { responseType: 'blob' };
$http.get(urls.SERVICE_API + "informe/"+ angular.toJson(informeDTO), config).then(
....
)

Displaying Blank page in which PDF link is included

Android OS version 7.1.1, following code display blank screen first time after download the App. Have to kill the App and open it again to work normally. Please advise.
Code:
Container cc = new Container(BoxLayout.y());
cc.setScrollableY(true);
TextArea ta = new TextArea(Util.readToString(is));
ta.setEditable(false);
ta.setUIID("Label");
Button b = new Button("Terms of Service");
b.addActionListener(e3 -> {
try {
FileSystemStorage fs = FileSystemStorage.getInstance();
final String homePath = fs.getAppHomePath();
String fileName = homePath + "Terms of Service.pdf";
Util.copy(Display.getInstance().getResourceAsStream(getClass(), "/Terms of Service.pdf"), fs.openOutputStream(fileName));
Display.getInstance().execute(fileName);
} catch (IOException ex) {
}
});
cc.add(ta);
CheckBox rememberMe1 = new CheckBox();
rememberMe1.setSelected(false);
rememberMe1.setHeight(Display.getInstance().convertToPixels(10.0f));
rememberMe1.setAutoSizeMode(true);
b.setAutoSizeMode(true);
setSameHeight(rememberMe1, l11, b);
cc.add(FlowLayout.encloseIn(rememberMe1, b));

Get the Ip Info from Client to Web Api

fist at all sorry for my bad English.
I'm trying to get the IP in the login option to save them as a "Session" in the database and register who and where is using the app.
I try this, but it obvious that it isn't going to work.
var ip = new System.Net.WebClient().DownloadString("http://ipinfo.io/json");
It Gets the IP Client. So it logical that I need to do this get in the Client side. But the problem is that the Client can change this values before its send to the Web API
$http.get("http://ipinfo.io/json").then(function (response) {
return response.data;
}).catch(function (response) {
console.log(response.data);
});
The users can change this value to send me a false data in the login and I don't have how to validate if this information is valid or real. So, the question is ¿How can I do this without let the user manipulate this data?
Create a method in web API, and we can save all the information needed directly to database.
public static string UserIp()
{
string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
try
{
string url1 = "http://geoip.nekudo.com/api/" + ip.ToString(); // passing IP address will return location information.
WebClient client = new WebClient(); // Intialize the webclient
string jsonstring = client.DownloadString(url1);
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring); // De-serialize the JSON string
string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\App_Data\\Logs\\" + "Ip.txt";
using (System.IO.StreamWriter writer = new StreamWriter(filePath, true))
{
// you can save the information to database instead of writing to a file
writer.WriteLine("UserIp:" + ip);
writer.WriteLine("Date:" + DateTime.Now);
writer.WriteLine("JsonString:" + jsonstring);
writer.WriteLine("Country name:" + dynObj.country.code);
}
return dynObj;
}
catch (Exception ex)
{
string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\App_Data\\Logs\\" + "I.txt";
string url1 = "http://geoip.nekudo.com/api/" + ip.ToString();
WebClient client = new WebClient(); // Intialize the webclient
string jsonstring = client.DownloadString(url1);
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
// string a = dynObj.country.code;
using (System.IO.StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" +
ex.StackTrace +
"" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
writer.WriteLine("UserIp:" + ip);
writer.WriteLine("Dynamic obj:" + dynObj);
}
return null;
}
}

BrowserMob Proxy is not opening 2nd page in chrome (Internet connection goes off after landing to 2nd page)

I'm running Windows 10 virtual machine on ubuntu, and on VM I have following versions :-
Eclipse neon, Selenium Webdriver 3.0.1, Mozilla Firefox 51.0.1, Google Chrome 55, geckoDriver v0.11.1, Chromedriver v2.27, BrowserMob Proxy jar 2.1.4, jackson-all-1.7.3.jar, harlib-1.1.2.jar
I wanted to read browser traffics in selenium and for that i opted for BrowserMob proxy. I have 2 page of communication on the browser like Authenticates url, Lands on the 1st page clicks a dropdown menu (link) and lands on the 2nd page
When the second page opens the page does not load but the calls are going behind. What i noticed is in the VM when the second page loads internet connectivity goes off at that page only (internet sign stops blinking).
When i Reboot both the VM & the host machine and then execute the code. It loads the page at first attempt after fresh reboot of the system then again, if i execute the same code same problem persists.
But the traffic data is getting logged in the file. The same code if i try to execute in geckodriver(Firefox) then the page is getting loaded but traffic is not getting captured.capturing only specific urls from the log data
I have stuck in both the ways. Please find below the code :-
class 1 :-
public class BrowserMobExample{
public static String sFileName = System.getProperty("user.dir") + "\\CaptureNetworkTraffic\\BrowserMob.har";
WebDriver driver = null;
BrowserMobProxy proxy = null;
#BeforeTest
public void setUp() throws Exception {
// start the proxy
proxy = new BrowserMobProxyServer();
proxy.start(0);
//get the Selenium proxy object - org.openqa.selenium.Proxy;
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
// configure it as a desired capability
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);
//set chromedriver system property
System.setProperty("webdriver.chrome.driver", "path to chromedriver");
driver = new ChromeDriver(capabilities);
/*System.setProperty("webdriver.gecko.driver", "path to geckodriver");
driver = new FirefoxDriver(capabilities);*/
// enable more detailed HAR capture, if desired (see CaptureType for the complete list)
proxy.enableHarCaptureTypes(CaptureType.REQUEST_HEADERS, CaptureType.RESPONSE_HEADERS);
proxy.newHar("label_for_har");
driver.manage().window().maximize();
driver.get("http://username:pswd#url.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Robot rb = new Robot();
rb.keyPress(KeyEvent.VK_ENTER);
//do something on page
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
WebElement citySelect = driver.findElement(By.xpath("dropdown_xpath"));
Select dropdown= new Select(select_a_dropdown_menuitem);
dropdown.selectByVisibleText("Text_displayed");
//driver.navigate().refresh();
}
#Test
public void testCaseOne() throws AWTException {
/*driver.manage().window().maximize();
driver.get("http://username:pswd#url.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Robot rb = new Robot();
rb.keyPress(KeyEvent.VK_ENTER);
//do something on page
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
WebElement citySelect = driver.findElement(By.xpath("dropdown_xpath"));
Select dropdown= new Select(select_a_dropdown_menuitem);
dropdown.selectByVisibleText("Text_displayed");
//driver.navigate().refresh();*/
}
#AfterTest
public void tearDown() {
// get the HAR data
Har har = proxy.getHar();
// Write HAR Data in a File
File harFile = new File(sFileName);
try {
har.writeTo(harFile);
ReadHAR reading = new ReadHAR();
reading.main(null);
} catch (IOException ex) {
System.out.println (ex.toString());
System.out.println("Could not find file " + sFileName);
}
/*if (driver != null) {
proxy.stop();
//driver.quit();
}*/
}
}
class 2 :-
public class ReadHAR {
public static void main(String[] args) {
String filename = new String();
filename = BrowserMobExample.sFileName;
// System.out.println("This is the file location " + filename);
File f = new File(filename);
HarFileReader r = new HarFileReader();
HarFileWriter w = new HarFileWriter();
try
{
System.out.println("Reading " + filename);
HarLog log = r.readHarFile(f);
// Access all elements as objects
HarBrowser browser = log.getBrowser();
HarEntries entries = log.getEntries();
// Used for loops
List<HarPage> pages = log.getPages().getPages();
List<HarEntry> hentry = entries.getEntries();
String string1 = "p_still_media";
String string2 = "m_still_media";
String string3 = "T-Map";
/* for (HarPage page : pages)
{
System.out.println("page start time: "
+ ISO8601DateFormatter.format(page.getStartedDateTime()));
System.out.println("page id: " + page.getId());
System.out.println("page title: " + page.getTitle());
}*/
File varTmpDir = new File(System.getProperty("user.dir") + "\\CaptureNetworkTraffic\\results.txt");
boolean exists = varTmpDir.exists();
System.out.println(" result.txt : " +exists);
System.out.println(" file path:"+ varTmpDir);
if(exists){
varTmpDir.delete();
}
File result = new File(System.getProperty("user.dir") + "\\CaptureNetworkTraffic\\results.txt");
// result.createNewFile();
result.setWritable(true);
//FileWriter fw = new FileWriter(result, false);
// PrintWriter out = new PrintWriter(fw);
//Output "response" code of entries.
for (HarEntry entry : hentry)
{
// System.out.println("IP is : " + entry.getServerIPAddress());
if(entry.getRequest().getUrl().contains(string2)/* & entry.getResponse().getStatus() !=200*/){
System.out.println(" Url is : " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus()); //Output url of request
// Files.newBufferedWriter(result, StandardOpenOption.APPEND);
// out.write(" Url is : " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus());
// BufferedWriter bw = new BufferedWriter(fw);
System.out.println("IP is :- "+entry.getServerIPAddress());
FileWriter fw = new FileWriter(result, true);
BufferedWriter out = new BufferedWriter(fw);
out.write(" Url is : " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus());
out.newLine();
out.close();
fw.close();
}
else if(entry.getRequest().getUrl().contains(string3) /*& entry.getResponse().getStatus() !=200*/){
// System.out.println("request code: " + entry.getRequest().getMethod()); //Output request type
System.out.println(" Url is: " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus()); //Output url of request
// out.write(" Url is : " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus());
FileWriter fw = new FileWriter(result, true);
BufferedWriter out = new BufferedWriter(fw);
out.write(" Url is : " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus());
out.newLine();
out.close();
fw.close();
}
else if(entry.getRequest().getUrl().contains(string1) /*& entry.getResponse().getStatus() !=200*/){
// System.out.println("request code: " + entry.getRequest().getMethod()); //Output request type
System.out.println(" Url is: " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus()); //Output url of request
//out.write(" Url is : " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus());
// out.close();
//System.out.println(" response code: " + entry.getResponse().getStatus()); // Output the
FileWriter fw = new FileWriter(result, true);
BufferedWriter out = new BufferedWriter(fw);
out.write(" Url is : " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus());
out.newLine();
out.close();
fw.close();
}
}
/*
// Once you are done manipulating the objects, write back to a file
System.out.println("Writing " + "fileName" + ".test");
File f2 = new File("fileName" + ".test");
w.writeHarFile(log, f2);
*/
}
catch (JsonParseException e)
{
e.printStackTrace();
//fail("Parsing error during test");
}
catch (IOException e)
{
e.printStackTrace();
//fail("IO exception during test");
}
}
}
With ChromeDriver logs are getting generated but the page is not loading. With firefox page is loading but logs are not captured (I think for geckodriver browsermob proxy is not compatible or this feature isn't available yet)
Am i missing anything or what is the issue ? Stuck on this since more than a week. Tried the above on ubuntu to but facing the same issue.
Any help on this issue is much appreciated.

Resources