Selenium- How to read a PDF file with current user context - java

I am using selenium for SharePoint UI testing, and I have test scenario where I would need to read and verify the PDF content. but when I use the following code I get. Error ":java.io.IOException: Server returned HTTP response code: 401 for URL http://******.com/pdf"
So I would need help on reading the PDF file with current User context.
String GetURL = driver.getCurrentUrl();
URL TestURL = new URL(GetURL);
BufferedInputStream TestFile = new BufferedInputStream(TestURL.openStream());
PDFParser TestPDF = new PDFParser((RandomAccessRead) TestFile);
TestPDF.parse();
String TestText = new PDFTextStripper().getText(TestPDF.getPDDocument());
Assert.assertTrue(TestText.contains("Open the setting.xml, you can see it is like this"));

Related

How to send Request file path in JSON request in Jmeter Test

All i am new to Jmeter and i am trying to create a rest api request that i can use to do some load test. I was able to authenticate and proceed to the next step of sending the post request.
Our Request is basically something like this
{"id" : 112, "someversion" : "2.0", "policyData" : "C:/TEMP/PGF/someinput.json" }
i was able to capture on the server what a sample request looks like. It seems that we are zipping and doing some base64 encoding before we send the request......
My main Question is how can i zip and encode this before posting so it can be similar to that format.
I have tried the following in jsr223 preprocessor:
import org.apache.commons.io.IOUtils;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.codec.binary.Base64;
String bodyString = sampler.getArguments().getArgument(0).getValue();
byte [] requestBody = bodyString.getBytes();
ByteArrayOutputStream out = new ByteArrayOutputStream(requestBody.length);
GZIPOutputStream gzip = new GZIPOutputStream(out);
so in here i need to zip this. it seems it zipping and my request is as this:
I am thinking i just need to encode the policy data only and not the entire request ......
I need to do something like this in java and encrypt that file possibly before I send it in the request.
using (var cryptStream = new CryptoStream(streamWriter.BaseStream, new
ToBase64Transform(), CryptoStreamMode.Write, leaveOpen: true))
using (var gzipStream = new GZipStream(cryptStream,
CompressionMode.Compress))
using (var inputFile = new FileStream(requestData.policyData,
FileMode.Open, FileAccess.Read))
{
inputFile.CopyTo(gzipStream);
}
I think you need to:
Extract the path to file from the request body using JsonSlurper
GZip this file content
Encode the bytes array to Base64
Example code:
String bodyString = sampler.getArguments().getArgument(0).getValue();
File policyData = new File(new groovy.json.JsonSlurper().parseText(bodyString).policyData)
def fileStream = new ByteArrayOutputStream()
def gzipStream = new java.util.zip.GZIPOutputStream(fileStream)
gzipStream.write(policyData.bytes)
gzipStream.close()
def gzipped = fileStream.toByteArray()
fileStream.close()
log.info(gzipped.encodeBase64().toString())
More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It
Thank you for your help... This is how i had initially solve my issue
String bodyString = sampler.getArguments().getArgument(0).getValue();
ByteArrayOutputStream rstBao = new ByteArrayOutputStream();
String JsonRequest = FileUtils.readFileToString(new
File("C:/TEMP/PGF/pgf_svc_input.json"));
GZIPOutputStream zos = new GZIPOutputStream(rstBao);
zos.write(JsonRequest.getBytes());
IOUtils.closeQuietly(zos);
byte[] bytes = rstBao.toByteArray();
//Here is where i am able to encode the bytes to base 64
Base64.encodeBase64String(bytes);
vars.put("postDataEncoded64",Base64.encodeBase64String(bytes));
log.info("khemlall this is the content"+ Base64.encodeBase64String(bytes));
log.info(vars.get("postDataEncoded64"));
rstBao.close()
In the body of my request i added the variable:
{
"id":"22351",
"pmmVersion":"2.0",
"policyData" : "${postDataEncoded64}"
}

check for validity of URL in java. so as not to crash on 404 error

Essentially, like a bulletproof tank, i want my program to absord 404 errors and keep on rolling, crushing the interwebs and leaving corpses dead and bludied in its wake, or, w/e.
I keep getting this error:
Exception in thread "main" org.jsoup.HttpStatusException: HTTP error fetching URL. Status=404, URL=https://en.wikipedia.org/wiki/Hudson+Township+%28disambiguation%29
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:537)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:493)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:205)
at org.jsoup.helper.HttpConnection.get(HttpConnection.java:194)
at Q.Wikipedia_Disambig_Fetcher.all_possibilities(Wikipedia_Disambig_Fetcher.java:29)
at Q.Wikidata_Q_Reader.getQ(Wikidata_Q_Reader.java:54)
at Q.Wikipedia_Disambig_Fetcher.all_possibilities(Wikipedia_Disambig_Fetcher.java:38)
at Q.Wikidata_Q_Reader.getQ(Wikidata_Q_Reader.java:54)
at Q.Runner.main(Runner.java:35)
But I can't understand why because I am checking to see if I have a valid URL before I navigate to it. What about my checking procedure is incorrect?
I tried to examine the other stack overflow questions on this subject but they're not very authoritative, plus I implemented the many of the solutions from this one and this one, so far nothing has worked.
I'm using the apache commons URL validator, this is the code I've been using most recently:
//get it's normal wiki disambig page
String URL_check = "https://en.wikipedia.org/wiki/" + associated_alias;
UrlValidator urlValidator = new UrlValidator();
if ( urlValidator.isValid( URL_check ) )
{
Document docx = Jsoup.connect( URL_check ).get();
//this can handle the less structured ones.
and
//check the validity of the URL
String URL_czech = "https://www.wikidata.org/wiki/Special:ItemByTitle?site=en&page=" + associated_alias + "&submit=Search";
UrlValidator urlValidator = new UrlValidator();
if ( urlValidator.isValid( URL_czech ) )
{
URL wikidata_page = new URL( URL_czech );
URLConnection wiki_connection = wikidata_page.openConnection();
BufferedReader wiki_data_pagecontent = new BufferedReader(
new InputStreamReader(
wiki_connection.getInputStream()));
The URLConnection throws an error when the status code of the webpage your downloading returns anything other than 2xx (such as 200 or 201 ect...). Instead of passing Jsoup a URL or String to parse your document consider passing it an input stream of data which contains the webpage.
Using the HttpURLConnection class we can try to download the webpage using getInputStream() and place that in a try/catch block and if it fails attempt to download it via getErrorStream().
Consider this bit of code which will download your wiki page even if it returns 404
String URL_czech = "https://en.wikipedia.org/wiki/Hudson+Township+%28disambiguation%29";
URL wikidata_page = new URL(URL_czech);
HttpURLConnection wiki_connection = (HttpURLConnection)wikidata_page.openConnection();
InputStream wikiInputStream = null;
try {
// try to connect and use the input stream
wiki_connection.connect();
wikiInputStream = wiki_connection.getInputStream();
} catch(IOException e) {
// failed, try using the error stream
wikiInputStream = wiki_connection.getErrorStream();
}
// parse the input stream using Jsoup
Jsoup.parse(wikiInputStream, null, wikidata_page.getProtocol()+"://"+wikidata_page.getHost()+"/");
The Status=404 error means there's no page at that location. Just because a URL is valid doesn't mean there's anything there. A validator can't tell you that. The only way you can determine that is by fetching it, and seeing if you get an error, as you're doing.

Trouble to save PDF file from a java web service using C#

I'm retrieving a PDF file from a web server java, returning a byte array.
Need save the PDF on the local machine using C #, but the file is saved completely in blank, I think it is because of the byte array format is different.
Here is my code:
StreamReader responseReader = new StreamReader(webStream);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/pdf";
WebResponse webResponse = request.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
responseReader.Close();
byte[] docByte = Encoding.ASCII.GetBytes(response);
File.WriteAllBytes(#"C:\file.pdf", docByte);
Any suggestions on how to save the PDF file normally?
Thank you for listening
// ...
Stream webStream = webResponse.GetResponseStream();
using (var stream = File.Create(#"C:\file.pdf"))
{
webStream.CopyTo(stream);
}
Why don't you do it simply with WebClient like this?
using System.Net;
using (WebClient webClient = new WebClient())
{
webClient.DownloadFile(URL, #"C:\file.pdf");
}

sending video file to browser over websocket

I want to send a video file from a server written in java to a web browser client.
The socket connection works fine and I have no trouble sending text.
The library I'm using to make a socket server is this https://github.com/TooTallNate/Java-WebSocket
This is the code for sending the file
public void sendFile(WebSocket conn,String path)
{
try
{
File file = new File(path);
byte[] data = new byte[(int)file.length()];
DataInputStream stream = new DataInputStream(new FileInputStream(file));
stream.readFully(data);
stream.close();
conn.send(data);
..snip catch statements..
Here is my javascript code for catching the file
function connect()
{
conn = new WebSocket('ws://localhost:8887');
conn.onopen = function(){alert("Connection Open");};
conn.onmessage = function(evt){if(evt.data instanceof Blob){readFile(evt);}else{alert(evt.data);}};
conn.onclose = function(){alert('connection closed');};
}
function readFile(file_data)
{
var video = document.getElementById('area');
video.src = window.URL.createObjectURL(file_data.data);
}
..skip to html element for playing the file..
<video id='area' controls="controls"></video>
I want to be able to receive the file in the browser and play it.
The error I get while trying to send a webm video file to fireox is:
HTTP "Content-Type" of "application/octet-stream" is not supported. Load of media resource blob:794345a5-4b6d-4585-b92b-3acb51612a6c failed.
Is it possible to receive a video file from a websocket and play it?
Am I implementing something wrong?
Video element requires right content-type, ws Blob comes with generic one, and it seems (to me) there is no way to set it serverside or clientside.
Fortunately, Blob has slice(start, end, contentType) method:
var rightBlob = originalBlob.slice(0, originalBlob.size, 'video/webm')

Fail to upload a image file into Google Doc via java api

below is my code
DocsService client = new DocsService("testappv1");
client.setUserCredentials(username, password);
client.setProtocolVersion(DocsService.Versions.V2);
File file = new File("C:/test.jpg");
DocumentEntry newDocument = new DocumentEntry();
newDocument.setTitle(new PlainTextConstruct("test"));
String mimeType = DocumentListEntry.MediaType.fromFileName(file.getName()).getMimeType();
newDocument.setMediaSource(new MediaFileSource(file, mimeType));
newDocument = client.insert(destFolderUrl, newDocument);
the document was created successful, but it did not contain anything.
try the following
client.insert(new URL("https://docs.google.com/feeds/documents/private/full/?convert=false"), newDocument);
i think the ?convert=false bit is important, not sure how you do that without the url
client.insert(new URL(destFolderUrl+ "?convert=false"), newDocument);
would hopefully work in your case

Categories