Invoke PDF, Server returned HTTP response code: 400 - http

English is not my native language; please excuse typing errors.
Hope I improved the question.
I start a Script over Selenium, automated testing, WebDriver.
I perform a Link on HTML-Page
This link creates a new Browser Tab
This BrowserTab display a PDF/A Standard Document
I want to parse the PDF an verify its content
After HttpURLConnection I got Hypertext Transfer Protocol (HTTP) response status code: 400
and parsing the InputStream can not be done.
Over localhost it can be done.
Also I can hit link "curent URL" without any problems.
Selenium v2.45.0
Tested on IE 9 and Firefox 39.0.
How can I examine the problem?
I read about HTTP response code: 400
But didn't find solution for my problem
Could it be a redirect-problem?
Thank you
Here is my code:
public class httperrorStack {
public static void main ( String[] args )
{
// Selnium WebDriver
WebDriver driver = null;
//driver = new FirefoxDriver();
// Test with Browser IE 9 same Problem withFirefox 39.0
System.setProperty("webdriver.ie.driver","C:\\dir\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
String baseUrl = "http://##.###.###.##:#####/wps/portal"; //ATU2
// launch direct to Base URL
driver.get(baseUrl);
// launch to Documentlink: opens PDF/A-Document in a new Browser Tab
driver.findElement(By.xpath("//a[#title='document_link']")).click();
//Get all the window handles in a set
Set <String> handles =driver.getWindowHandles();
Iterator<String> it = handles.iterator();
//iterate through windows
while (it.hasNext()){
String parent = it.next();
String newwin = it.next();
driver.switchTo().window(newwin);
URL url = null;
try {
// The CurrentURL of the documentlink
// url = "http://##.###.###.###:#####/wps/myportal/dirname/dirname/dir-name/!dir/p/b1/about50characters/In"
url = new URL(driver.getCurrentUrl());
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
// verify connection
HttpURLConnection connection = null;
HttpURLConnection httpConn = (HttpURLConnection)connection;
try {
httpConn = (HttpURLConnection)url.openConnection();
} catch (IOException e1) {
e1.printStackTrace();
}
InputStream is = null;
// Response Code = 400
try {
if (httpConn.getResponseCode() >= 400) {
is = httpConn.getErrorStream();
// httpConn.getResponseCode() = 400
//httpConn.getErrorStream() = "sun.net.www.protocol.http.HttpURLConnection$HttpInputStream#1d082e88"
} else {
is = httpConn.getInputStream();
}
} catch (IOException e1) {
e1.printStackTrace();
}
try{
connection = (HttpURLConnection)url.openConnection();
InputStream is2;
if (connection.getResponseCode() >= 400) {
is2 = connection.getErrorStream();
//connection.getErrorStream() = "sun.net.www.protocol.http.HttpURLConnection$HttpInputStream#60704c"
} else {
is2 = connection.getInputStream();
}
}
catch (Exception e){
e.printStackTrace();
}
BufferedInputStream fileToParse = null;
try {
fileToParse = new BufferedInputStream(
url.openStream());
} catch (IOException e) {
e.printStackTrace();
// output of StackTrace
/*java.io.IOException: Server returned HTTP response code: 400 for URL: http://##.###.###.##:#####/wps/redirect
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at mypackage.httperrorStack.main(httperrorStack.java:134)*/
}
// Close Window
driver.close();
driver.switchTo().window(parent);
driver.quit();
// exit the program explicitly
System.exit(0);
}
}
}

Related

Cannot open passkit file created in the server using dotnet-passbook v3.0.2

I have recently come across an issue that I cannot open my Pkpass which is created using dotnet-passbook version 3.2.0.
The Pkpass created locally can be opened fine and the issue is with the Pkpass created in the server.
I have even tried to upload the Pkpass from the server to the validator but the validator just returns “Failed to process the Pkpass file.”
Below is my code snapshot for building the Pkpass:
public static FileContentResult GetPass(Shopper account)
{
try {
if (account == null)
{
return null;
}
PassGenerator generator = new PassGenerator();
PassGeneratorRequest request = new PassGeneratorRequest();
// "webServiceURL" : "https://example.com/passes/",
// "authenticationToken" : "vxwxd7J8AlNNFPS8k0a0FfUFtq0ewzFdc",
// Product info
request.PassTypeIdentifier = "PassTypeIdentifier";
request.TeamIdentifier = "TeamIdentifier";
request.SerialNumber = "SerialNumber";
request.Description = "Description";
request.OrganizationName = "OrganizationName";
request.LogoText = "LogoText";
// Add the installed certificate and it's thumbprint
WebClient webClient = new WebClient();
try
{
X509KeyStorageFlags flags = X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable;
request.PassbookCertificate = new X509Certificate2(webClient.DownloadData(CertificatesBucket + "/Certificates.p12"), S3_AppleCertificatePassword, flags);
}
catch (Exception e)
{
throw new Exception("Error occurs when geting certificate: " + e.Message);
}
// Add Apple's WWDRCA certificates
try
{
request.AppleWWDRCACertificate = new X509Certificate2(webClient.DownloadData(CertificatesBucket + "/AppleWWDRCAG2.cer"));
}
catch (Exception e)
{
throw new Exception("Error occurs when geting AppleWWDRCCA: " + e.Message);
}
// override icon and icon retina
try
{
request.Images.Add(PassbookImage.Logo, webClient.DownloadData(AppleImageBucket + "/logo.png"));
request.Images.Add(PassbookImage.Icon, webClient.DownloadData(AppleImageBucket + "/icon.png"));
request.Images.Add(PassbookImage.Icon2X, webClient.DownloadData(AppleImageBucket + "/icon%402x.png"));
request.Images.Add(PassbookImage.Strip, webClient.DownloadData(AppleImageBucket + "/strip.png"));
request.Images.Add(PassbookImage.Strip2X, webClient.DownloadData(AppleImageBucket + "/strip%402x.png"));
}
catch (Exception e)
{
throw new Exception("Error occurs when geting images: " + e.Message);
}
// Add barcode
request.AddBarcode(BarcodeType.PKBarcodeFormatCode128, account.Id, "ISO-8859-1");
// Link the pass to an existing app using the app's Apple ID.
request.AssociatedStoreIdentifiers.Add(121212);
request.Style = PassStyle.StoreCard;
// Add fields
request.AddHeaderField(new StandardField("StandardField", "TEXT", account.Id));
request.AddSecondaryField(new StandardField("StandardField", "TEXT", account.Name));
request.AddSecondaryField(new StandardField("StandardField", "TEXT", "TEXT"));
request.TransitType = TransitType.PKTransitTypeAir;
byte[] generatedPass = generator.Generate(request);
//throw new Exception("apple generatedPass: " + JsonTransHelper.SerializeObject(generatedPass));
return new FileContentResult(generatedPass, "application/vnd.apple.pkpass");
}
catch (Exception ex)
{
throw new Exception("Error occurs when creating apple pass: " + ex.Message);
}
}
}
}
Any help greatly appreciated!
It is caused by AWS API Gateway. If you running this on a Lambda function try to invoke it directly.
Offset to Central Directory cannot be held in an Int64 .net core

Playing video stream from mp4 file with moov atom at end using libvlcsharp

I want to play video replay from low-end surveillance camera. Replays are saved on the camera in .mp4 format, with moov atom at the end. It's possible to retrieve file via http request using digset authentication. Approximate size of each video file is 20 MB, but download speed is only 3 Mbps, so downloading whole file takes about 60 s. This is to long, so I want to start displaying video before whole file will be downloaded.
Web browsers handles this kind of problem by reading end of file at the begining. I want to achieve same goal using c# and libvlcsharp, so created HttpMediaInput class.
public class HttpMediaInput : MediaInput
{
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private HttpClientHandler _handler;
private HttpClient _httpClient;
private string _url;
Stream _stream = null;
public HttpMediaInput(string url, string username, string password)
{
_url = url;
_handler = new HttpClientHandler() { Credentials = new NetworkCredential(username, password) };
_httpClient = new HttpClient(_handler);
}
public override bool Open(out ulong size)
{
size = ulong.MaxValue;
try
{
_stream = _httpClient.GetStreamAsync(_url).Result;
base.CanSeek = _stream.CanSeek;
return true;
}
catch (Exception ex)
{
logger.Error(ex, $"Exception occurred during sending stream request to url: {_url}");
return false;
}
}
public unsafe override int Read(IntPtr buf, uint len)
{
try
{
byte[] buffer = new byte[len];
int bytesReaded = _stream.Read(buffer, 0, buffer.Length);
logger.Trace($"Bytes readed: {bytesReaded}");
Span<byte> byteSpan = new Span<byte>(buf.ToPointer(), buffer.Length);
buffer.CopyTo(byteSpan);
return bytesReaded;
}
catch (Exception ex)
{
logger.Error(ex, "Stream read exception");
return -1;
}
}
...
}
It works great for mp4 files that have all necessary metadata stored on the beginning, but no video is displayed in case of my camera.
Assuming that I will be able to download moov atom from mp4 using http range requests, how to provide this data to libvlc? Is it even possible?
I'm developing application using C#, WPF, dotnet framework.
VLC cannot play files from camera because http digest auth with md5 is considered to be deprecated (related issue in VLC repo).
However, I was able to resolve this problem following cube45 suggestions, I implemented range requests.
public override bool Open(out ulong size)
{
size = ulong.MaxValue;
try
{
HttpRequestMessage requestMessage = new HttpRequestMessage { RequestUri = new Uri(_url) };
requestMessage.Headers.Range = new System.Net.Http.Headers.RangeHeaderValue();
requestMessage.Method = HttpMethod.Head;
var response = _httpClient.SendAsync(requestMessage).Result;
size = (ulong)response.Content.Headers.ContentLength;
_fileSize = size;
logger.Trace($"Received content lenght | {size}");
base.CanSeek = true;
return true;
}
catch (Exception ex)
{
logger.Error(ex, $"Exception occurred during sending head request to url: {_url}");
return false;
}
}
public unsafe override int Read(IntPtr buf, uint len)
{
try
{
HttpRequestMessage requestMessage = new HttpRequestMessage { RequestUri = new Uri(_url) };
long startReadPosition = (long)_currentPosition;
long stopReadPosition = (long)_currentPosition + ((long)_numberOfBytesToReadInOneRequest - 1);
if ((ulong)stopReadPosition > _fileSize)
{
stopReadPosition = (long)_fileSize;
}
requestMessage.Headers.Range = new System.Net.Http.Headers.RangeHeaderValue(startReadPosition, stopReadPosition);
requestMessage.Method = HttpMethod.Get;
HttpResponseMessage response = _httpClient.SendAsync(requestMessage).Result;
byte[] readedBytes = response.Content.ReadAsByteArrayAsync().Result;
int readedBytesCount = readedBytes.Length;
_currentPosition += (ulong)readedBytesCount;
logger.Trace($"Bytes readed | {readedBytesCount} | startReadPosition {startReadPosition} | stopReadPosition | {stopReadPosition}");
Span<byte> byteSpan = new Span<byte>(buf.ToPointer(), (int)len);
readedBytes.CopyTo(byteSpan);
return readedBytesCount;
}
catch (Exception ex)
{
logger.Error(ex, "Media reading general exception");
return -1;
}
}
public override bool Seek(ulong offset)
{
try
{
logger.Trace($"Seeking media with offset | {offset}");
_currentPosition = offset;
return true;
}
catch (Exception ex)
{
logger.Error(ex, "MediaInput seekeing general error");
return false;
}
}
This solution seams to work, but there are two unresolved problems:
There is about 8s lag between libvlcsharp starts reading stream and video goes live (waiting time in web browser is about 2s).
Some part of video file at the end is not displayed, because the buffer is too short to hold whole file inside. Related thread

Spring MVC Multipart file upload random FileNotFoundException

I built a web application using spring MVC, everything is working fine except the file upload in which I got random FileNotFoundExceptions. I found some solutions online like using a different tmp folder but I keep getting random error.
My code is:
#RequestMapping(value="/upload", method=RequestMethod.POST)
public #ResponseBody String handleFileUpload(#RequestParam("file") final MultipartFile multipartFile,
#RequestHeader("email") final String email, #RequestHeader("password") String password){
if (authenticateUser(email, password)) {
if (!multipartFile.isEmpty()) {
System.out.println("Start processing");
Thread thread = new Thread(){
public void run(){
ProcessCSV obj = new ProcessCSV();
try {
File file = multipartToFile(multipartFile);
if(file !=null) {
obj.extractEvents(file, email, cluster, session);
}
else {
System.out.println("null File");
}
} catch (IOException e) {
System.out.println("File conversion error");
e.printStackTrace();
}
}
};
thread.start();
return "true";
} else {
return "false";
}
}
else {
return "false";
}
}
and:
public File multipartToFile(MultipartFile multipartFile) throws IOException {
File uploadFile = null;
if(multipartFile != null && multipartFile.getSize() > 0) {
uploadFile = new File("/tmp/" + multipartFile.getOriginalFilename());
FileOutputStream fos = null;
try {
uploadFile.createNewFile();
fos = new FileOutputStream(uploadFile);
IOUtils.copy(multipartFile.getInputStream(), fos);
} catch (FileNotFoundException e) {
System.out.println("File conversion error");
e.printStackTrace();
} catch (IOException e) {
System.out.println("File conversion error");
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
System.out.println("File conversion error");
e.printStackTrace();
}
}
}
}
else {
System.out.println("null MultipartFile");
}
return uploadFile;
}
and the configuration file:
multipart.maxFileSize: 100MB
multipart.maxRequestSize: 100MB
multipart.location = ${user.home}
server.port = 8090
I used different versions of the multipartToFile function, one was using multipartfile.transferTo() but I was getting the same random error. Any advice?
Thank you
EDIT stack trace:
java.io.IOException: java.io.FileNotFoundException: /Users/aaa/upload_07720775_4b37_4b86_b370_40280388f3a4_00000003.tmp (No such file or directory)
at org.apache.catalina.core.ApplicationPart.write(ApplicationPart.java:121)
at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile.transferTo(StandardMultipartHttpServletRequest.java:260)
at main.RESTController.multipartToFile(RESTController.java:358)
at main.RESTController$1.run(RESTController.java:241)
Caused by: java.io.FileNotFoundException: /Users/aaa/upload_07720775_4b37_4b86_b370_40280388f3a4_00000003.tmp (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at org.apache.tomcat.util.http.fileupload.disk.DiskFileItem.write(DiskFileItem.java:392)
at org.apache.catalina.core.ApplicationPart.write(ApplicationPart.java:119)
... 3 more
I had just had a night of terror with this error. I found out that MultiPartFile is only recognisable to and by the #Controller class. So if you pass it to another bean which is not a controller, Spring will not be able to help you. It somewhat makes sense that the #Controller is tightly bound to the front screen (communication from the browser to the system - Controllers are the entry point from the browser). So any conversation must happen there in the Controller.
In my case, I did something like the following:
#Controller
public class FileUploadingController{
#PostMapping("/uploadHistoricData")
public String saveUploadedDataFromBrowser(#RequestParam("file") MultipartFile file) {
try {
String pathToFile = "/home/username/destination/"
new File(pathToFile).mkdir();
File newFile = new File(pathToFile + "/uploadedFile.csv");
file.transferTo(newFile); //transfer the uploaded file data to a java.io.File which can be passed between layers
dataService.processUploadedFile( newFile);
} catch (IOException e) {
//handle your exception here please
}
return "redirect:/index?successfulDataUpload";
}
}`
I had the same problem, it looks like MultipartFile is using different current dir internally, so all not absolute paths are not working.
I had to convert my path to an absolute path and then it worked.
It is working inside #RestController and in other beans too.
Path path = Paths.get(filename).toAbsolutePath();
fileToImport.transferTo(path.toFile());
fileToImport is MultipartFile.

text/event-stream render in grails from scratch(without plugin)

To use push method , we use the famous JS object EventSource :
This is the client part which is easy to develop it :
var eventSource = new EventSource("controller/action");
eventSource.onmessage = function(event) {
document.getElementById('foo').innerHTML = event.data;
};
However , i get difficulty to configure push method in server part(Grails) .
When , i peek in JEE app developped by Servlets , i can see that the server part is as following :
http://viralpatel.net/blogs/html5-server-sent-events-java-servlets-example/
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//content type must be set to text/event-stream
response.setContentType("text/event-stream");
//encoding must be set to UTF-8
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
for(int i=0; i<10; i++) {
writer.write("data: "+ System.currentTimeMillis() +"\n\n");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
writer.close();
}
}
To convert this servlet to action controller :
def push(){
render(contentType:'text/event-stream',characterEncoding:'UTF-8'){
[dt:"data: "+ System.currentTimeMillis() +"\n\n"]
}
}
and in client part :
var eventSource = new EventSource(baseURL+"external/push");
eventSource.onmessage=function(e){
console.log(e.data.dt);
}
Unfortunately, i don't get any result at console .
I'm not sure if the render method will handle 'text/event-stream' correctly, but you have direct access to the response object in the action:
def push() {
//content type must be set to text/event-stream
response.setContentType("text/event-stream");
//encoding must be set to UTF-8
response.setCharacterEncoding("UTF-8");
for(int i=0; i<10; i++) {
response.outputStream.write("data: "+ System.currentTimeMillis() +"\n\n");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
response.outputStream.flush()
}
def push = {
response.setContentType("text/event-stream");
for(def i=0;i<10;i++) {
render("data $i: ${System.currentTimeMillis()}\n");
sleep(1000)
}
}

Check Httpconnection is open or not in blackberry

Before making HttpConnection from blackberry application i want to check if it is open or not?. Because without checking that when i tried to make a connection i got class net.rim.device.api.io.ConnectionClosedException.
EDIT: Posted the code from the OP's answer.
Below is my code for the http connection.
public String makePostRequest(String[] paramName, String[] paramValue) {
StringBuffer postData = new StringBuffer();
HttpConnection connection = null;
InputStream inputStream = null;
OutputStream out = null;
try {
connection = (HttpConnection) Connector.open(this.url);
connection.setRequestMethod(HttpConnection.POST);
for (int i = 0; i < paramName.length; i++) {
postData.append(paramName[i]);
postData.append("=");
postData.append(paramValue[i]);
postData.append("&");
}
String encodedData = postData.toString();
connection.setRequestProperty("Content-Language", "en-US");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", (new Integer(
encodedData.length())).toString());
connection.setRequestProperty("Cookie", Constants.COOKIE_TOKEN);
byte[] postDataByte = postData.toString().getBytes("UTF-8");
out = connection.openOutputStream();
out.write(postDataByte);
DebugScreen.Log("Output stream..."+out);
DebugScreen.Log("Output stream..."+connection.getResponseCode());
// get the response from the input stream..
inputStream = connection.openInputStream();
DebugScreen.Log("Input stream..."+inputStream);
byte[] data = IOUtilities.streamToBytes(inputStream);
response = new String(data);
} catch ( Exception e) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
WaitingScreen.removePopUP();
Status.show(Constants.CONNETION_ERROR);
}
});
DebugScreen.Log("Exception inside the make connection..makePostRequest."
+ e.getMessage());
DebugScreen.Log("Exception inside the make connection..makePostRequest."
+ e.getClass());
}finally {
try {
if(inputStream != null){
inputStream.close();
inputStream = null;
}
if(out != null){
out.close();
out = null;
}
if(connection != null){
connection.close();
connection = null;
}
} catch ( Exception ex) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
WaitingScreen.removePopUP();
}
});
DebugScreen.Log("Exception from the connection2 class.."
+ ex.getMessage());
DebugScreen.Log("Exception from the connection2 class.."
+ ex.getClass());
}
}
return response;
}
Before making httpconnection from blackberry application i want to check if it is open or not.
That doesn't make sense. You want to make sure it is open before you open it. You can't. You have to try to open it, and handle the exception if it fails. That's what the exception is for.
The best way to test whether any resource is available is to try to use it. You can't predict that. You have to try it.
Because without checking that when i tried to make a connection i got class net.rim.device.api.io.ConnectionClosedException.
So it wasn't available. So now you know. That's the correct behaviour. You're already doing the right thing. There is no question here to answer.

Resources