Showing posts with label http. Show all posts
Showing posts with label http. Show all posts

Tuesday, September 18, 2018

Increase Concurrent http calls in any browser

Leave a Comment

I went through many posts for this on SO but not found any suitable solution

I got it from one of the answers for maximum concurrent connection to one domain limit

IE 6 and 7:      2 IE 8:            6 IE 9:            6 IE 10:           8 IE 11:           8 Firefox 2:       2 Firefox 3:       6 Firefox 4 to 46: 6 Opera 9.63:      4 Opera 10:        8 Opera 11 and 12: 6 Chrome 1 and 2:  6 Chrome 3:        4 Chrome 4 to 23:  6 Safari 3 and 4:  4 

How to call more than the maximum http calls set by browsers to one domain.

I went through this

One trick you can use to increase the number of concurrent conncetions is to host your images from a different sub domain. These will be treated as seperate requests, each domain is what will be limited to the concurrent maximum.

IE6, IE7 - Have a limit of two. IE8 is 6 if your a broadband, 2 if you are dial up.

but i don't have scenario like this. I am fetching specific data which is pointing to one web server. how will I overcome this.

I am having 14 http calls to same server at starting which is the reason it takes long to load the actual page. How to increase performance of my website through concurrent ajax/http calls

7 Answers

Answers 1

what you can do is dispatch that load to many subdomains. Instead of using only www, you use www1, www2, www3, www4 and round robin between those clientside.

You'll need to configure your web server so that www* subdomains ends up to the same place.

Answers 2

14 requests is not an issue. It becomes issue only if server response time is large. So most likely the root issue is the server side performance

These solutions are possible:

  • use HTTP cache (server should send corresponding headers)
  • use cache at the middle (e.g. CDN, Varnish)
  • optimize server side
    • content related:
      • combine several requests into one
      • remove duplicated information in requests
      • do not load information which client doesn't render
    • use cache at server side
    • etc... any other approach... there are plenty of them.

Answers 3

Just to extend on Charly Koza's answer as this has some limitations depending on user count etc.

First thing you should look at is into using CDNs, I will assume you have done this already.

The fact you are only hitting one server is not a problem, the browser will allow concurrent connections based on DNS host and not just IP.

If you have access to your DNS management and can dynamically spawn up a new subdomain, look to free services like CloudFlare's API.

Alternatively, create a wildcard domain, which will allow any subdomain to point to 1 server.

In this way, on your server side, you can identify if the user already has X amount of connections active, if so, the following scenario can be done:

  • Dynamically create a new Subdomain on the same IP, or if using the Wildcard, create a random subdomain newDomainRandom.domain.com
  • Then return the user a 301 redirect to the new domain, the users Internet Client will then register this as a new connection to another domain.

There is a lot of Pseudo work here, but this is more of a networking issue that a coding issue.

Compulsory warning on this method though :

There are no limits in using 301 redirects on a site. You can implement more than 100k of 301 redirects without getting any penalty. But: Too many 301 redirects put unnecessary load on the server and reduce speed.

Answers 4

How to call more than the maximum http calls set by browsers to one domain.

That is a HTTP/1.1 limit (6-8), If you are able to change the server (you tag this question as http), the best solution is using HTTP/2 (RFC 7540) instead of HTTP/1.1.

HTTP/2 multiplex many HTTP requests on a single connection, see this diagram. When HTTP/1.1 has a limit of 6-8 roughly, HTTP/2 does not have a standard limit but say that "It is recommended that this value (SETTINGS_MAX_CONCURRENT_STREAMS) be no smaller than 100" (RFC 7540). That number is better than 6-8.

Answers 5

I have a data driven application. ... I have google map, pivot, charts and grids

In comments you mentioned that data is coming from different providers, in case those are on different domains - try using dns-prefetch, i.e. like this:

   <link rel="dns-prefetch" href="http://www.your-data-domain-1.com/">    <link rel="dns-prefetch" href="http://www.your-data-domain-2.com/">    <link rel="dns-prefetch" href="http://www.3rd-party-service-1.com/">    <link rel="dns-prefetch" href="http://www.3rd-party-service-2.com/"> 

You need to list all domains which you are calling via AJAX and which are not the actual domain of your website itself.

It will force browser to send the DNS request as soon as it reads and parses that HTML data and not when your code requests the data from those domains for the first time. It might save you up to few hundreds of milliseconds when the browser will be actually doing an AJAX request for the data.

See also:

Answers 6

Just use Http2. Http1 has a limit on concurrent connections, depending on the browser about 6-10.

Answers 7

If your server is able to perform tasks concurrently, there is no added value in opening multiple connections to it, other than being able to update your UI earlier (before the completion of the slowest tasks). E.g. To enable users use the page before all the tasks have finished. This offers a good user experience.

However, there are other solutions to achieve this, than opening parellel http connections. In short you can merge all your endpoints under one endpoint that handles all tasks, and asynchronously place the result of each finished task to the response. The client can then process the result of each task at the time it finishes.

To achieve the above you need some short of protocol/api that operates on top of an http connection, or a connection that has been upgraded to websocket. Below there are some alternatives which provide the async response message feature:

Read More

Thursday, September 6, 2018

Can't post comment on reddit using Postman: USER_REQUIRED error

1 comment

I'm trying to post a comment using Postman. I'm sending the following information:

Headers:

Authorization: "Bearer access_token"  Content-Type: " application/x-www-form-urlencoded"  User-Agent: "some u/user" 

Body:

api_type: "json"  thing_id: "t3_9bmzy6"  text: "some comment" 

I'm sending this POST request to https://oauth.reddit.com/api/comment.

In return I get a USER_REQUIRED error:

​

{     "json": {         "errors": [             [                 "USER_REQUIRED",                 "Please log in to do that.",                 null             ]         ]     } } 

Why is that? I've passed an access_token and it was accepted as right (otherwise if I knowingly pass the wrong token I would get a 401 Unauthorized error).

What I have of the passwords:

My usual username:password pair

My script's app_id:app_secret pair

My access_token I was given in exchange for my app_id:app_secret pair.

I also tried to do this in Java, using HttpURLConnection class:

import org.apache.tomcat.util.codec.binary.Base64; import org.json.JSONArray; import org.json.JSONObject;  import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Scanner;  public class RedditParser {         public static void main(String[] args)  {             RedditParser redditParser = new RedditParser();             redditParser.postAComment("sds", "fdfdf");         }           public  void postAComment(String postID, String commentBody)  {                try  {                   String postLink = "https://oauth.reddit.com/api/comment";                     URL loginURL = new URL(postLink);                    HttpURLConnection connection = (HttpURLConnection) loginURL.openConnection();                   JSONObject requestJSON = new JSONObject();                   requestJSON.put("api_type", "json");                   requestJSON.put("thing_id", "t3_9bmzy6");                   requestJSON.put("text", "a test comment");                    connection.setDoOutput(true);                    connection.setRequestProperty("Authorization", "Bearer " +getAccessToken());  //getAccessToken returns correct(!) token; it's not the cause of the error                   connection.setRequestProperty("User-Agent", "script by /u/someuser");                   connection.setRequestProperty("Content-Type", "application/json");                    OutputStream os = connection.getOutputStream();                   os.write(requestJSON.toString().getBytes("UTF-8"));                   os.close();                    connection.connect();                    System.out.println("Done comment");                    InputStream input = connection.getInputStream();                   String inputString = new Scanner(input, "UTF-8").useDelimiter("\\Z").next();                   JSONObject jsonObject = new JSONObject(inputString);                   System.out.println(inputString);             }              catch (Exception e)  {                   System.out.println(e);             }         } } ​ 

But I still get the error output:

Done comment {"jquery": [[0, 1, "refresh", []], [0, 2, "attr", "find"], [2, 3, "call", [".error.USER_REQUIRED"]], [3, 4, "attr", "show"], [4, 5, "call", []], [5, 6, "attr", "text"], [6, 7, "call", ["Please log in to do that."]], [7, 8, "attr", "end"], [8, 9, "call", []]], "success": false} 

What else do I need to add to the request to get rid of the error?

1 Answers

Answers 1

From the information available I'd guess that you didn't provide user credentials in the access token request but that you requested an Application Only Token. This type of token can probably not be used to post comments on reddit for obvious reasons.

To perform actions for a certain user you will need to request an access token like this:

reddit@reddit-VirtualBox:~$ curl -X POST -d 'grant_type=password&username=reddit_bot&password=snoo' --user 'p-jcoLKBynTLew:gko_LXELoV07ZBNUXrvWZfzE3aI' https://www.reddit.com/api/v1/access_token {     "access_token": "J1qK1c18UUGJFAzz9xnH56584l4",      "expires_in": 3600,      "scope": "*",      "token_type": "bearer" } 

That is provide user credentials as form data and use the app credentials for Basic authentication.

Read More

Friday, August 24, 2018

Determine if a request was via a browser bookmark/favorite vs a link?

Leave a Comment

Say I am on a website viewing the homepage at https://whateverxyz.com/index. Then I either

  • (A) click a navigation link in the HTML of the page to https://whateverxyz.com/app1.html
  • (B) click on a browser bookmark to https://whateverxyz.com/app1.html

Can the server tell the difference between whether request was from A or B? Can client-side JavaScript running on app1.html tell the difference?

3 Answers

Answers 1

Citate from your question:

  • Can the server tell the difference between whether request was from A or B?
  • Can client-side JavaScript running on app1.html tell the difference?

In both cases this is not possible to detect the difference.

What say us official resources?

Citate from RFC 7231 - Hypertext Transfer Protocol (HTTP/1.1)

If the target URI was obtained from a source that does not have its own URI (e.g., input from the user keyboard, or an entry within the user's bookmarks/favorites), the user agent MUST either exclude the Referer field or send it with a value of "about:blank".

The Referer field has the potential to reveal information about the request context or browsing history of the user, which is a privacy concern if the referring resource's identifier reveals personal information (such as an account name) or a resource that is supposed to be confidential (such as behind a firewall or internal to a secured service). Most general-purpose user agents do not send the Referer header field when the referring resource is a local "file" or "data" URI. A user agent MUST NOT send a Referer header field in an unsecured HTTP request if the referring page was received with a secure protocol. See Section 9.4 for additional security considerations.

Read more about it:

Alternative solution

But something you could do on client side. In the page https://whateverxyz.com/index you could write one listener in JavaScript which detect all clicks on this page links. And on click event you could write the link URL and the time in a cookie, an IndexedDB or a localStorage. Then in the page https://whateverxyz.com/app1.html you have to read this information. In the case if this information is not undefined it is from link and in all other cases it is from bookmark (or may be it was tipped in adress bar, or whatever).

See related questions:

Answers 2

I am afraid, you can not find out! It is only accessible in browsers extensions.

Answers 3

You can set a query parameter after the page is loaded with JavaScript. (use history.pushState so its not reloading). Like:

history.pushState({}, "", "?bookmarked")

So when the navigation is from a bookmark, its with the ?bookmarked parameter, and when its a regular navigation you'll get it without any parameters.

Working example, Code for example

Read More

Tuesday, June 12, 2018

Make Postman test - Grails

Leave a Comment

I have the following test of a grails integration:

def http = new HTTPBuilder(loginUrl) http.request( POST, TEXT ) {     headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'     send URLENC, [j_username: username, j_password: password]      response.success = { resp, reader ->         loggedIn = ! reader.text.contains("j_username")     } } 

I'm trying to mount the test in Postman, but I'm not sure if I'm doing it correctly because of this send URLENC, [j_username: username, j_password: password]

I put the POST type route, and put something like:

{     j_username: username,     j_password: password } 

And the headers parameters:

'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4' 'Content-type' = 'Application/json' 

But it is always returning my login form in the body, does anyone know how to mount this test?

UPDATE

Actually in other projects I follow the reference and it works well. However I have developed the grails response part, did not leave an api/login route, and I believe that the login is done by the same web route /login/auth, but I can not validate the test by postman, but on the web logo perfectly.

UPDATE 2

I believe that in the project that receives my login request, to try to facilitate, they have made access to the api by the same web, and this request that is mounted in the integration, do not make a json type request, because of "send URLENC", Can someone please explain to me how to put this call in postman?

1 Answers

Answers 1

If you have the default Spring Security and Spring Security REST config, here how I do it :

Body of the Postman call

Header of the Postman call

Read More

Thursday, June 7, 2018

How to identify if a page request is for a preview

Leave a Comment

When I paste my website link at a social network (Facebook or Twitter for example), the social network access my site to show a preview to the user.

I want to separate this access from real access at my reports, but to do this, I need to identify this cases.

This kind of access send any kind of information that is default for everysite that I can identify that this access is not a real user, but a robot?

2 Answers

Answers 1

You should be able to identify those robots from their user-agent string. For example, Twitter uses the User-Agent of Twitterbot. And Facebook crawler identification is documented here.

Answers 2

You can use the User-Agent to do that.

if (strpos($_SERVER["HTTP_USER_AGENT"], "Twitterbot") !== false)    echo "TwitterBot"; else if (strpos($_SERVER["HTTP_USER_AGENT"], "facebookexternalhit") !== false)    echo "Facebook"; else    echo "regular user"; 

https://developers.facebook.com/docs/sharing/webmasters/crawler

Read More

Friday, June 1, 2018

wordpress err_connection_reset in Chrome from specific country

Leave a Comment

I volunteer supporting a news website in Russia, which was hand-crafted in PHP back in 2002-2004. Needless to say, I was super excited when editors hired some folks to build a new version, based on WordPress. The old site is running on mydomain.press. I put the new WordPress version, which is meant to replace the old one, on subdomain.mydomain.press.

And there's a mysterious problem with it.

When an editor is trying to access the site at subdomain.mydomain.press, her browser (Chrome in Russia) instantly reports err_connection_reset, in 9 cases out of 10. Not spinning trying to load the site - an instant error is reported. On my machine (Canada) the same website opens no problem. Well, a little slow (hence I mentioned she's not even seeing the delay - the error is instant), but it opens in 10 out of 10 trials. When her Chrome gets the content (in that 1/10 case), it also shows a slight delay. Only the error case is instantaneous. The old site at mydomain.press is opening 100% of the time.

Connecting remotely to her Windows machine (I'm using Mac OS X) via TeamViewer, I did observe the behaviour described when using Chrome. Interestingly enough, IE didn't show this problem - it loads consistently, except that once in ~10 reloads the page loads with a garbled styling. As if some css isn't loaded properly (but not in a way that would make it an invalid document, obviously).

I'm completely out of my depth. I tried disabling her Windows Defender to see if it's the culprit - nope. I've tried to reset her IP address (as suggested by the same page which offered the earlier way to try and fix the err_connection_reset) - no dice.

I'm not seeing either error from my own Chrome, nor the garbled css (though I didn't try with IExplorer from Canada).

I know they had some ISPs in Russia block them (silly political reason, AFAIK) in the past - but this doesn't look like blocking; she'd be 100% unable to view it otherwise. She's not under any firewall (nor is the website).

what else... nginx is the server used, the setup is "basic", I suppose (I'm not that proficient in configuring it to try anything fancy).

And to make things even more mysterious - the website at mydomain.press (the old version, php-hand-crafted) is opening just fine, 100% of trials.

Opening using the IP-address doesn't change the picture, so doesn't look like a DNS issue.

Any ideas?

1 Answers

Answers 1

There is an ongoing battle of Roskomnadzor against Telegram messenger in Russia, which affects subnets, DNS and DPI hardware around the country. Try to connect via proxy or VPN server outside Russia and see if the problem goes away.

Read More

Friday, May 11, 2018

how to get a Network Panel show up when debugging Electron/Node applications

Leave a Comment

I am building an electron application and I am using libraries (request/axios) for making requests. One thing I didn't expect is that making these requests on Node won't display a Network Panel when running in chrome debug mode. Is there a simple way to tell debug mode to turn on a network panel for tuning into https requests(I assume these libraries all use https)?


currently on my server side electron app i only see the following enter image description here

1 Answers

Answers 1

Solution 1 - create your own

you can wrap your axios functions and send an event to your renderer process

main electron process

const electron = require('electron');  const {   app,   BrowserWindow,   ipcMain } = electron;  const _axios = require('request-promise');  const axios = {   get: (url, params) => _axios.get(url, params).then(sendData),   post: (url, params) => _axios.post(url, params).then(sendData),   delete: (url, params) => _axios.delete(url, params).then(sendData),   put: (url, params) => _axios.put(url, params).then(sendData)   // ... };  function sendData() {   return (data) => {     mainWindow.webContents.send('network', data);     return data;   }; } 

renderer process (index.html):

<!DOCTYPE html> <html>  <head>   <meta charset="UTF-8">   <title>Hello World!</title>    <link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css"          rel="stylesheet">   <style>     .kb-debug-widget {       position: fixed;       bottom: 0;       height: 200px;       overflow-x: hidden;       overflow-y: auto;       background: grey;       left: 0;       right: 0;       font-size: 10px;     }   </style> </head>  <body>   <div class="kb-debug-widget">     <table class="table is-bordered is-striped is-narrow is-hoverable is-fullwidth"            id="network">       <tr>         <th>Name</th>         <th>Method</th>         <th>Status</th>         <th>Type</th>         <th>Body</th>       </tr>     </table>   </div>   <script>     require('./renderer.js');     var {       ipcRenderer,       remote     } = require('electron');      ipcRenderer.on('network', (event, response) => {       const networkElement = document.getElementById('network');        // print whatever you want here!       networkElement.innerHTML +=         `       <tr>         <td>${response.request.href}</td>         <td>${response.request.method}</td>         <td>${response.statusCode}</td>         <td>${response.headers['content-type']}</td>         <td>${response. data}</td>       </tr>       `;        // you can also print the network requests to the console with a decent UI by using console.table:       console.table({         name: response.request.href,         method: response.request.method,         status: response.statusCode,         type: response.headers['content-type'],         body: response. data,       });     });   </script> </body>  </html> 

This will create a widget on the bottom of your view.

it's even easier with request:

const _request = require('request-promise'); const _axios = require('request-promise');  // this should cover all sub-methods const request = (params, callback) => {   return _request(params, callback)   .on('response', (response) => {     mainWindow.webContents.send('network', response);     return response;   }); }; 

Since both axios & request return similar objects, you can use the same function on the renderer side.

code in action

enter image description here

Here's a GitHub repository with the code implemented

Solution 1: Alt - write network requests to renderer's console

I also added an option to print the requests to the dev tools console, with console.table. Here's how it looks: enter image description here You can leave only this method if you don't want a widget inside your HTML.

Solution 2 - Run electron with the --inspect flag

You can also just run electron with the inspect flag, which allows you to debug your server code and has its own network tab with the "server-side" HTTP requests.

In order to see it, run your electron application like so:

electron --inspect=<port> your/app 

if you want to immediatly break on the first line, run the same command but replace --inspect with --inspect-brk.

After running the command, open any web-browser and go to chrome://inspect and selecting to inspect the launched Electron app present there. enter image description here

hope this helped. if you have any questions, you can ask me in the comments

Read More

Monday, February 5, 2018

Can't send object via Object Output Stream from one http handler to another

Leave a Comment

So, in my app, I send the request from http server handler to another server. The thing is the second server is stuck on reading object. I was trying to figure out it myself but I can't see the problem. All streams are closed, maybe the response to the client is in the wrong place? I have no idea why is that..

This is my client:

public class ClientSimulator {      private Random random;     private static int clientCounter = 1;      public static void main(String[] args) throws Exception {         new ClientSimulator();         new ClientSimulator();         new ClientSimulator();     }      private ClientSimulator() {          this.random = new Random();         RuntimeMXBean rmb = ManagementFactory.getRuntimeMXBean();         long arrivalTime = rmb.getUptime();          System.out.println("thread no. " + clientCounter++ + " arrival time: " + arrivalTime);         try {             String myurl= "http://localhost:8080/sender";             String serverResponse = createClient(myurl);             System.out.println(serverResponse);         } catch (Exception e) {             e.printStackTrace();         }     }      private String createClient(String myurl) throws Exception {         URL url;         BufferedReader reader = null;         StringBuilder stringBuilder;          try {             //Standard HTTP connection             url = new URL(schedulerUrl);             HttpURLConnection connection = (HttpURLConnection) url.openConnection();             connection.setDoInput(true);             connection.setDoOutput(true);              int[] arr = {                     random.nextInt(10-1)+1,                     random.nextInt(10-1)+1,                     random.nextInt(10-1)+1,                     random.nextInt(10-1)+1,                     random.nextInt(10-1)+1,             };             Task t = new Task(arr);              ObjectOutputStream oos = new ObjectOutputStream(connection.getOutputStream());             oos.writeObject(t);             oos.close();              // read the output from the server             reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));             stringBuilder = new StringBuilder();             //print the response             String line = reader.readLine();             stringBuilder.append(line);              return stringBuilder.toString();         } catch (Exception e) {             e.printStackTrace();             throw e;         } finally {             if (reader != null) {                 try {                     reader.close();                 } catch (IOException ioe) {                     ioe.printStackTrace();                 }             }         }     }      private boolean getRandBool(){         return this.random.nextBoolean();     } } 

This is how I send the request from the main server to another server:

@Override     public void handle(HttpExchange httpExchange) throws IOException {          String template = "\nClient no. %s connected!";          //Getting task         Task t;         ObjectInputStream ois = new ObjectInputStream(httpExchange.getRequestBody());         try {             System.out.print("Recieved object:");             t = (Task) ois.readObject();             t.setDeadline(deadline);             t.setHard(isHard);             System.out.print(" not sorted array: ");             int[] arr = (int[]) t.getData();             for (int anArr : arr) {                 System.out.print(anArr + " ");             }             ois.close();             String response = "response for client no. " + clientCounter;            httpExchange.sendResponseHeaders(200, response.length());            OutputStream os = httpExchange.getResponseBody();            os.write(response.getBytes());            os.close();            clientCounter++;              HttpURLConnection test = (HttpURLConnection) new URL(fogServ1URL).openConnection();             test.setDoOutput(true);             System.out.println("test__1");             ObjectOutputStream stream = new ObjectOutputStream(test.getOutputStream());             stream.flush();             System.out.println("test__2");             stream.writeObject(t);             System.out.println("test__3");             stream.close();             System.out.println("test__4");             test.getResponseCode();             System.out.println("test__5"); //this doesn't print         } catch (ClassNotFoundException e) {             e.printStackTrace();         }     } } 

This is handler from the second server:

class RootHandler implements HttpHandler{ private static int clientCounter = 1;  @Override public void handle(HttpExchange exchange) throws IOException {        System.out.println("\nRoot handler; \n\tclient no. " + clientCounter++);      Task t;     ObjectInputStream ois = new ObjectInputStream(exchange.getRequestBody());     try {         System.out.println("Recieved object:"); //only this is on the console         t = (Task) ois.readObject();         ois.close();         System.out.println("Array not sorted:");         int[] arr = (int[]) t.getData();         for (int anArr : arr) {             System.out.print(anArr + " ");         }         TaskSolver.solve(t);         System.out.println("\nArray sorted!");         for (int anArr : (int[])t.getData()) {             System.out.print(anArr + " ");         }     } catch (ClassNotFoundException e) {         e.printStackTrace();     }      String response = "Server up!";     exchange.sendResponseHeaders(200, response.getBytes().length);     OutputStream os = exchange.getResponseBody();     os.write(response.getBytes());     os.close(); } } 

I don't get it because I send the Task from client to the main server in the same way and its working. I just can't read the output in the next servers. What am I doing wrong?

Btw. If someone is curious why I'm sending the same object to another server: I plan to create more servers, the main server will be sending requests to them depending on type/containing headers.

2 Answers

Answers 1

In Second server while reading the object there is some IOException occurred, since IOException in handle method of RootHandler class is passed to invoking method instead of handling it. So error like Internal Server Error response status is sent to client ( first server ).

Since there is exception in second server the test.getResponseCode() throws IOException since it is not handled in first server handle method

System.out.println("test__5");

is not invoked.

If you want to know what is happening catch IOException in handle method of the both server and print Stack trace.

Answers 2

Try following below sequence in your first server -

  1. Receive object by reading the InputStream
  2. Connect with the second server.
  3. Send object by writing on OutputStream of second server.
  4. Get the response from second server
  5. Send response to client by writing on OutputStream of first server.

The reason behind current behavior is related to closing of Exchange. As per the documentation -

Exchanges are terminated when both the request InputStream and response OutputStream are closed.

Currently, in your first server code, you are writing the response on OutputStream and then closing it. After that, your first server start communicating with second server.

When first server sent request to second server and wait for the response, at the time, underlying HttpExchange gets closed, thus connection and associated thread are released. Till this time, second server hasn't read the request.

In this situation, some IOException must occur in second server for indicating the error or second server will keep waiting for reading the InputStream and eventually get timeout.

Closing of Exchange and releasing of associated thread is not immediate step after closing OutputStream, but it can terminate anytime and subsequent code lines are not guaranteed to be executed. In your case, connection terminated while waiting for the response from second server but it can terminate before that also.

Read More

Sunday, December 31, 2017

Retrieve data from a table of aspx page using Excel VBA

Leave a Comment

I am trying to retrieve table data from aspx page using excel vba.I know how to get table data from a URL but below is the main problem.

Problem

There is an aspx page (say www.abc.aspx). I am currently on this page.Let this page be page1.

Now I click a page2 link on the current page. What is worth noticing is that after clicking this link, the old URL (www.abc.aspx) doesn't change but the content changes.( Content is of page2 )

If you view page1 source code it has

<form method="post" action="page1 url" id="Form1"> 

Whatever is the action on page1 (page2 click) , it posts back the same page1 url.

So how can I get page2 table data in excel VBA since I don't know its URL?

Code

This is what I had used to fetch table data.

I used internet explorer object.Then navigated to the link and saved the document in htmldoc.

ie.navigate "url"  Do While ie.READYSTATE <> READYSTATE_COMPLETE Application.StatusBar = "Fetching data..." DoEvents Loop  Set htmldoc = ie.document  'Column headers Set eleColth = htmldoc.getElementsByTagName("th") j = 0 'start with the first value in the th collection         For Each eleCol In eleColth 'for each element in the td collection             ThisWorkbook.Sheets(1).Range("A1").Offset(i, j).Value = eleCol.innerText 'paste the inner text of the td element, and offset at the same time             j = j + 1 'move to next element in td collection         Next eleCol 'rinse and repeat   'Content Set eleColtr = htmldoc.getElementsByTagName("tr")  'This section populates Excel     i = 0 'start with first value in tr collection     For Each eleRow In eleColtr 'for each element in the tr collection         Set eleColtd = htmldoc.getElementsByTagName("tr")(i).getElementsByTagName("td") 'get all the td elements in that specific tr         j = 0 'start with the first value in the td collection         For Each eleCol In eleColtd 'for each element in the td collection             ThisWorkbook.Sheets(1).Range("D3").Offset(i, j).Value = eleCol.innerText 'paste the inner text of the td element, and offset at the same time             j = j + 1 'move to next element in td collection         Next eleCol 'rinse and repeat         i = i + 1 'move to next element in td collection     Next eleRow 'rinse and repeat  ie.Quit Set ie = Nothing 

EDIT:

Example

If we click on questions in Stack Overflow (https://stackoverflow.com/questions) and now click on page2 of questions (new link is https://stackoverflow.com/questions?page=2&sort=newest)

In my case, if we click on page2, the new link is not updated.It is the same old link.

EDIT: I have found a similar question here

How do I get url that is hidden by javascript on external website?

Thanks.

2 Answers

Answers 1

Ok, I sympathise, there is a school of thought (including Tim Berners-Lee) that says every separate page should have its own URI and that these don't change.

But webmasters can and do mess you around. They can redirect you HTTP request and can obfuscate the navigation as in your case. They can rewrite HTTP requests.

You have two options

Option 1 - Let Internet Explorer resolve the new content for you

So, if the content is visible on the screen then it must be in the Document Object Model (DOM). In IE, or indeed in Chrome, one can right-click and get the context menu and then choose Inspect to see where in the DOM that element resides.

I think your code demonstrates enough expertise to drill in. However, sometimes some websites like to disable the Inspect menu option to avoid programers poking around. (EDIT: As in your case now that I have read the comments)

Option 2 - Use an HTTP sniffing Tool like Fiddler to detect the HTTP redirect/rewrite

As I said above, HTTP requests can be rewritten and redirected by the web-server but the HTTP protocol does give notifications of redirects. There are tools to detect this. A popular tool is Fiddler, today I have discovered that there is a specific IE Fiddler add-on.

To be honest though the developer tools that ship with the browsers themselves, particularly Chrome (Ctrl+Shift+I, then Network tab), show network traffic to a level of detail increasingly on a par with any sniffing tool.

Sorry you got down-voted, this seems like a perfectly reasonable question.

Answers 2

A bird's eye view on the problem:

You have a requirement that you seem to not be able to let go: Use Excel VBA. I emphasize this point since often times answers provide solutions satisfying alternative premises from what is posted in the OP.

A possible solution:

So you have to Interface Excel VBA with another tool having the capability for revealing the contents of html redirects or obfuscated URLs.

Google Chrome Developer Tools reveals all contents, and you can interface very nicely Google Chrome with Excel VBA, using the Selenium VBA Wrapper. Download here.

It is quite versatile, e.g., you can see how to scrape web data.

As for getting obfuscated contents, there are a few items that may help

how to get innerHTML of whole page in selenium driver? (not VBA but useful)

Selenium + VBA to Control Chrome

(Note: the author of the wrapper is usually eager to answer in SO, and precise in his answers).

I guess YMMV, there are always people trying to obfuscate their data, with various techniques, and often for good reasons...

If you have a real example for your http://www.abc.aspx, it may help.

Read More

Thursday, November 30, 2017

Caching reverse proxy for dynamic content

Leave a Comment

I was thinking about asking on Software Recommendations, but then I've found out that it may be a too strange request and it needs some clarification first.

My points are:

  • Each response contains an etag
    • which is a hash of the content
    • and which is globally unique (with sufficient probability)
  • The content is (mostly) dynamic and may change anytime (expires and max-age headers are useless here).
  • The content is partly user-dependent, as given by the permissions (which itself change sometimes).

Basically, the proxy should contain a cache mapping the etag to the response content. The etag gets obtained from the server and in the most common case, the server does not deal with the response content at all.

It should go like follows: The proxy always sends a request to the server and then either

  • 1 the server returns only the etag and the proxy makes a lookup based on it and
    • 1.1 on cache hit,
      • it reads the response data from cache
      • and sends a response to the client
    • 1.2 on cache miss,
      • it asks the server again and then
      • the server returns the response with content and etag,
      • the proxy stores it in its cache
      • and sends a response to the client
  • 2 or the server returns the response with content and etag,
    • the proxy stores the data in its cache
    • and sends a response to the client

For simplicity, I left out the handling of the if-none-match header, which is rather obvious.

My reason for this is that the most common case 1.1 can be implemented very efficiently in the server (using its cache mapping requests to etags; the content isn't cached in the server), so that most requests can be handled without the server dealing with the response content. This should be better than first getting the content from a side cache and then serving it.

In case 1.2, there are two requests to the server, which sounds bad, but is no worse than the server asking a side cache and getting a miss.

Q1: I wonder, how to map the first request to HTTP. In case 1, it's like a HEAD request. In case 2, it's like GET. The decision between the two is up to the server: If it can serve the etag without computing the content, then it's case 1, otherwise, it's case 2.

Q2: Is there a reverse proxy doing something like this? I've read about nginx, HAProxy and Varnish and it doesn't seem to be the case. This leads me to Q3: Is this a bad idea? Why?

Q4: If not, then which existing proxy is easiest to adapt?

An Example

A GET request like /catalog/123/item/456 from user U1 was served with some content C1 and etag: 777777. The proxy stored C1 under the key 777777.

Now the same request comes from user U2. The proxy forwards it, the server returns just etag: 777777 and the proxy is lucky, finds C1 in its cache (case 1.1) and sends it to U2. In this example, neither the clients not the proxy knew the expected result.

The interesting part is how could the server know the etag without computing the answer. For example, it can have a rule stating that requests of this form return the same result for all users, assuming that the given user is allowed to see it. So when the request from U1 came, it computed C1 and stored the etag under the key /catalog/123/item/456. When the same request came from U2, it just verified that U2 is permitted to see the result.

1 Answers

Answers 1

Q1: It is a GET request. The server can answer with an "304 not modified" without body.

Q2: openresty (nginx with some additional modules) can do it, but you will need to implement some logic yourself (see more detailed description below).

Q3: This sounds like a reasonable idea given the information in your question. Just some food for thought:

  • You could also split the page in user-specific and generic parts which can be cached independently.

  • You shouldn't expect the cache to keep the calculated responses forever. So, if the server returns a 304 not modified with etag: 777777 (as per your example), but the cache doesn't know about it, you should have an option to force re-building the answer, e.g. with another request with a custom header X-Force-Recalculate: true.

  • Not exactly part of your question, but: Make sure to set a proper Vary header to prevent caching issues.

  • If this is only about permissions, you could maybe also work with permission infos in a signed cookie. The cache could derive the permission from the cookie without asking the server, and the cookie is tamper proof due to the signature.

Q4: I would use openresty for this, specifically the lua-resty-redis module. Put the cached content into a redis key-value-store with the etag as key. You'd need to code the lookup logic in Lua, but it shouldn't be more than a couple of lines.

Read More

Thursday, November 9, 2017

How to send image from image Uri through HTTP request? (React Native and Django Backend)

Leave a Comment

I’m using Expo’s image picker and I’m getting this output:

Object {   "cancelled": false,   "height": 468,   "uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540jbaek7023%252Fstylee/ImagePicker/9a12f0a3-9260-416c-98a6-51911c91ddf4.jpg",   "width": 468, } 

I could render my image, but I just realized that the URL is the phone’s local URI.

I’m using Redux-Thunk and Axios to send HTTP POST request:

export const sendPost = ( imageUri, title, content ) => async dispatch => {   let response = await axios.post(`${ROOT_URL}/rest-auth/registration/`, {     image, <<<<- I can't put image uri here :( it's LOCAL path     title,     content   })    if(response.data) {     dispatch({ type: POST_CREATE_SUCCESS, payload: response.data.token })   } else {     dispatch({ type: POST_CREATE_FAIL })   } } 

UPDATE I changed a request call

let headers = { 'Authorization': `JWT ${token}`};   if(hType==1) {     headers = { 'Authorization': `JWT ${token}`};   } else if (hType==2) {     headers = { 'Authorization': `Bearer ${token}`};   }  let imageData = new FormData(); imageData.append('file', { uri: image }); let response = await axios.post(`${ROOT_URL}/clothes/create/`, {     image: imageData,     text, bigType, onlyMe ...   }, {headers}); 

!! sorry for the complication but image variable name; image is uri for the image. I didn't want to change the name of original variable name

and on server, it's printing

'image': {'_parts': [['file', {'uri': 'file:///data/user/0/host.exp.exponent     /cache/ExperienceData/%2540jbaek7023%252Fstylee/     ImagePicker/78f7526a-1dfa-4fc9-b4d7-2362964ab10d.jpg'}]]} 

I found that gzip compression is a way to send image data. Does it help?

3 Answers

Answers 1

It has to be a local URI, there's no issues with that, how else are you going to point to the image.

Now to upload the image you should first wrap it inside of FormData:

// add this just above the axios request let img = new FormData(); img.append('file', { uri: imageUri }); 

Then inside of your axios request body add:

image: img, 

Answers 2

Another option is to convert your image to base64 and send the string. Downsize is that usually the base64 strings has a bigger size than the image itself.

Something like this:

function readImage(url, callback) {        var request = new     XMLHttpRequest();   request.onload = function() {        var file = new FileReader();        file.onloadend = function() {           callback(file.result);        }        file.readAsDataURL(request.response);   };           request.open('GET', url);           request.responseType = 'blob';                      request.send();  } 

Answers 3

you cant use react-native-fetch-blob .....

import RNFetchBlob from " react-native-fetch-blob"    PostRequest(PATH){        RNFetchBlob.fetch('POST', "[URL]", {                "x-session-id": "SESSION_ID", //or Custom headers              'Content-Type': 'multipart/form-data',            }, [                    { name: 'image', filename: 'vid.jpeg', data: RNFetchBlob.wrap(PATH) },                  // custom content type                ]).then((res) => {                  console.log(res)                })              .catch((err) => {                  console.log(err)                  // error handling ..              })          }    }

for reference react-native-fetch-blob

Read More

Monday, October 16, 2017

Unable to trigger web request implemented in Giraffe

Leave a Comment

I'm struggling to trigger a web service that's written in Giraffe.

Here's the code:

let webApp : HttpContext -> HttpHandlerResult =       choose [         GET >=>             choose [ routef "/platforms/" fetchPlatforms ] 

fetchPlatforms is implemented as follows:

let private fetchPlatforms () (context : HttpContext) =     async { let response = getPlatforms()             return! json response context     } 

The issue that I'm running into is that when I run the server code and then attempt to test the web service, I get the following message:

enter image description here

Here's the entire solution.

Update:

I am only observing this issue in VS Code.

Hence, I can observe a successful web request and response using Visual Studio 2017 (3) version 15.4

Here's the video that demonstrates the difference between VS2017 and VS Code

2 Answers

Answers 1

I downloaded your source code and tried to reproduce the issue, but first I was getting an error during startup because I don't have your db configured locally, therefore I made the following change:

type TestObj =     {         Prop1 : string         Prop2 : int     }  let private fetchPlatforms  =     let obj1 = { Prop1 = "test"; Prop2 = 100 }     json obj1     //  let response = getPlatforms()     //  json response 

... and when I start the app now and make a Postman call to the /platforms endpoint then it seems to work fine for me...

postman

Have you resolved your issue perhaps?

Answers 2

routef should match pattern: https://github.com/dustinmoris/Giraffe#routef

otherwise try route:

let webApp : HttpContext -> HttpHandlerResult =   choose [     GET >=>         choose [ route "/platforms" >=> fetchPlatforms ] 

EDIT:

And looking at your code, the fetchPlatforms function is not a proper handler. HttpHandler :

A HttpHandler is a simple function which takes two curried arguments, a HttpFunc and a HttpContext, and returns a HttpContext (wrapped in an option and Task workflow) when finished.

Instead of:

let private fetchPlatforms  =      let response = getPlatforms()      json response 

Try something like that:

let fetchPlatforms   =     fun (next : HttpFunc) (ctx : HttpContext) ->         let response = getPlatforms()         json response next ctx 

You can do that async as well (it depends on getPlatforms):

let fetchPlatforms   =     fun (next : HttpFunc) (ctx : HttpContext) ->         task {             let! response = getPlatforms()             return! json response next ctx         } 
Read More

Wednesday, September 27, 2017

Java: How to make API call with data?

Leave a Comment

I want to make API call similar to below curl command:

curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer  1djCb/mXV+KtryMxr6i1bXw"  -d '{"operands":[]}'  https://ads.line.me/api/v1.0/authority_delegations/get 

What I am trying

public void send_deligation_request(String details[]) throws Exception{     System.out.println(Arrays.toString(details));      URL line_api_url = new URL("https://ads.line.me/api/v1.0/authority_delegations/get");     String payload = "{operands:[]}";        HttpURLConnection linec = (HttpURLConnection)line_api_url.openConnection();     linec.setDoInput(true);     linec.setDoOutput(true);     linec.setRequestMethod("POST");     linec.setRequestProperty("Content-Type", "application/json");     linec.setRequestProperty("Authorization", "Bearer "+access_token);      OutputStreamWriter writer = new OutputStreamWriter(linec.getOutputStream(), "UTF-8");     writer.write(payload);       BufferedReader in = new BufferedReader(                             new InputStreamReader(                                     linec.getInputStream()));     String inputLine;      while ((inputLine = in.readLine()) != null)          System.out.println(inputLine);     in.close(); } 

But I am getting below error:

[naofumi.haida@torchlight.co.jp, 5514] 
java.io.IOException: Server returned HTTP response code: 400 for URL: https://ads.line.me/api/v1.0/authority_delegations/get   at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1840)   at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)   at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)   at AuthorityDelegation.send_deligation_request(AuthorityDelegation.java:66)   at AuthorityDelegation.read_csv(AuthorityDelegation.java:36)   at AuthorityDelegation.main(AuthorityDelegation.java:20) 

Could somebody please help me?

5 Answers

Answers 1

HTTP code 400 means a BAD REQUEST.

I can't access the endpoint you have shared but here is free online REST API which I am using for demonstrating ..

curl -X POST \   https://jsonplaceholder.typicode.com/posts \   -H 'cache-control: no-cache' \   -H 'postman-token: 907bbf75-73f5-703f-c8b6-3e1cd674ebf7' \   -d '{         "userId": 100,         "id": 100,         "title": "main title",         "body": "main body"     }' 
  • -H = headers
  • -d = data

Sample Run:

[/c]$ curl -X POST \ >   https://jsonplaceholder.typicode.com/posts \ >   -H 'cache-control: no-cache' \ >   -H 'postman-token: 907bbf75-73f5-703f-c8b6-3e1cd674ebf7' \ >   -d '{ >         "userId": 100, >         "id": 100, >         "title": "main title", >         "body": "main body" >     }'    % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current                                  Dload  Upload   Total   Spent    Left  Speed 100   258  100   150  100   108    147    106  0:00:01  0:00:01 --:--:--   192{   "{\n        \"userId\": 100,\n        \"id\": 100,\n        \"title\": \"main title\",\n        \"body\": \"main body\"\n    }": "",   "id": 101 } 

Java Code for the same is as follows:

OkHttpClient client = new OkHttpClient();  MediaType mediaType = MediaType.parse("application/octet-stream"); RequestBody body = RequestBody.create(mediaType, "{\n        \"userId\": 100,\n        \"id\": 100,\n        \"title\": \"main title\",\n        \"body\": \"main body\"\n    }"); Request request = new Request.Builder()   .url("https://jsonplaceholder.typicode.com/posts")   .post(body)   .addHeader("cache-control", "no-cache")   .addHeader("postman-token", "e11ce033-931a-0419-4903-ab860261a91a")   .build();  Response response = client.newCall(request).execute(); 

Another example of calling REST POST call with data ..

User user = new User(); user.setFirstName("john"); user.setLastName("Maclane");  ResteasyClient client = new ResteasyClientBuilder().build(); ResteasyWebTarget target = client.target("URL"); Response response = target.request().post(Entity.entity(user, <MEDIATYPE>)); //Read output in string format System.out.println(response.getStatus()); response.close();  

Here is the what your code looks like when I update it with my endpoints and payload.

import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.Arrays;  public class TestClass {      public static final String POST_URL = "https://jsonplaceholder.typicode.com/posts";      public static final String POST_DATA = "{\"userId\": 100,\"id\": 100,\"title\": \"main title\",\"body\": \"main body\"}";      public static void main(String[] args) throws Exception {         String[] details = {};         System.out.println(Arrays.toString(details));          URL line_api_url = new URL(POST_URL);         String payload = POST_DATA;          HttpURLConnection linec = (HttpURLConnection) line_api_url                 .openConnection();         linec.setDoInput(true);         linec.setDoOutput(true);         linec.setRequestMethod("POST");         linec.setRequestProperty("Content-Type", "application/json");         linec.setRequestProperty("Authorization", "Bearer "                 + "1djCb/mXV+KtryMxr6i1bXw");          OutputStreamWriter writer = new OutputStreamWriter(                 linec.getOutputStream(), "UTF-8");         writer.write(payload);          BufferedReader in = new BufferedReader(new InputStreamReader(                 linec.getInputStream()));         String inputLine;          while ((inputLine = in.readLine()) != null)             System.out.println(inputLine);         in.close();     } } 

In nutshell, check the API documentation and ensure the request payload is of correct format as 400 means BAD REQUEST.

Answers 2

It’s a 400 error, which means Bad Request. Please check this link below.

How to find out specifics of 400 Http error in Java?

Answers 3

OutputStreamWriter will buffer the output. After this line in your code:

writer.write(payload); 

add this line

writer.flush(); 

I would expect that to fix your problem.

Answers 4

Though this may not help you with precisely an existing HTTP call using the traditional HttpURLConnection. Yet an interesting way to achieve this in recent times is to use HTTP/2 Client and try out the latest introduced incubator module jdk.incubator.http form Java 9.

An easy way(quick-start) of mocking a POST call using the same is as follows :

  1. Create a within your project and define module-info.java as:

    module http.trial {      requires jdk.incubator.httpclient; } 
  2. Within the module create a package and a class named HttpPost with following content:

    import jdk.incubator.http.HttpRequest; import jdk.incubator.http.HttpClient; import jdk.incubator.http.HttpResponse; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException;  public class HttpPost {    public static void main(String[] args) {      // Request builder     URI uri = null;     try {         uri = new URI("https://ads.line.me/api/v1.0/authority_delegations/get");     } catch (URISyntaxException e) {         e.printStackTrace();     }     HttpRequest.BodyProcessor bodyProcessor = HttpRequest.BodyProcessor.fromString("{\"operands\":[]}");     HttpRequest request = HttpRequest.newBuilder().uri(uri)                     .header("Content-Type", "application/json")                     .header("Authorization", "Bearer 1djCb/mXV+KtryMxr6i1bXw")                     .POST(bodyProcessor)                     .build();      // Client     HttpClient httpClient = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.ALWAYS).build();     System.out.println(httpClient.version());      // Response builder     HttpResponse response = null;     try {         response = httpClient.send(request, HttpResponse.BodyHandler.asString());     } catch (IOException | InterruptedException e) {         e.printStackTrace();     }      System.out.println("StatusCode = " + response.statusCode());     System.out.println("Response = " + response.body().toString());   } } 

Answers 5

Thanks everyone for your help. I used below code to make it work.

public JSONObject send_post() {     HttpClient httpClient = HttpClientBuilder.create().build();     JSONObject jsonObject = null;      try {          HttpPost request = new HttpPost(this.URL + this.object_type + this.request_type);         StringEntity params = null;         if (this.request_type.equals("/get")) {             params = new StringEntity("{\"accountId\":\"5514\"}");         } else if (this.request_type.equals("/set")) {             // params = new             // StringEntity("{\"accountId\":\"5514\",\"operands\":[{\"id\":40151,\"name\":\"ddddd\"}]}");             String output = String.format("{\"accountId\":\"5514\",\"operands\":[{\"id\":%s,\"name\":\"%s\"}]}",                     this.params[0], this.params[1]);             if (this.params[1].equals("OptimizationOff")) {                 output = String.format(                         "{\"accountId\":\"5514\",\"operands\":[{\"id\":%s,\"bidOptimizationType\":\"%s\"}]}",                         this.params[0], "NONE");             } else if (this.params[1].equals("OptimizationOn")) {                 output = String.format(                         "{\"accountId\":\"5514\",\"operands\":[{\"id\":%s,\"bidOptimizationType\":\"%s\",\"bidOptimizationGoal\":\"%s\"}]}",                         this.params[0], this.params[2], this.params[3]);             }             if (object_type.equals("/ads")) {                 output = String.format("{\"accountId\":\"5514\",\"operands\":[{\"id\":%s,\"bidAmount\":\"%s\"}]}",                         this.params[0], this.params[1]);             }             params = new StringEntity(output);         }         request.addHeader("content-type", "application/json");         request.addHeader("Authorization", "Bearer " + this.Access_Token);         request.setEntity(params);          HttpResponse response = httpClient.execute(request);          BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));         StringBuffer result = new StringBuffer();         String line = "";         while ((line = rd.readLine()) != null) {             result.append(line);         }          System.out.println("API Resonse :"+result.toString());         jsonObject = new JSONObject(result.toString());      } catch (Exception ex) {          ex.printStackTrace();      } finally {      }     return jsonObject;  } 
Read More

Wednesday, May 24, 2017

best way to save nginx request as a file?

Leave a Comment

i am looking for a solution to save data sent via http (e.g. as a POST) as quickly as possible (with lowest overhead) via nginx (v1.2.9). i tried the following nginx configuration, but am not seeing any files written in the directory:

server {   listen 9199;   location /saveme {     client_body_in_file_only on;     client_body_temp_path /tmp/bodies;   } } 

what am i doing wrong? and/or is there a better way to accomplish this? (the data that is written should ideally be one file per request, and it does not matter if it is fairly "raw" in nature. post-processing of the files will be done via a separate process via a queue.)

2 Answers

Answers 1

This question has already been answered here:

Basically, you need to combine log_format and fastcgi_pass. You can then use the access_log directive for example, to specify where the saved variable should be dumped to.

location = /saveme {   log_format postdata $request_body;   access_log  /var/log/nginx/postdata.log  postdata;   fastcgi_pass php_cgi; } 

It could also work with your method but I think you're missing client_body_buffer_size and `client_max_body_size

Answers 2

Do you mean save cache for HTTP post while someone access and request file and store on hdd rather than memory? I may suggest use proxy_cache_path and proxy_cache. The proxy_cache_path directive sets the path and configuration of the cache, and the proxy_cache directive activates it.

proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m max_size=10g                  inactive=60m use_temp_path=off; server { ...     location / {         proxy_cache my_cache;         proxy_pass http://my_upstream;     } } 
  • The local disk directory for the cache is called /path/to/cache
  • levels sets up a two‑level directory hierarchy under /path/to/cache/
  • keys_zone sets up a shared memory zone for storing the cache keys and metadata such as usage timers
  • max_size sets the upper limit of the size of the cache
  • inactive specifies how long an item can remain in the cache without being accessed

    the proxy_cache directive activates caching of all content that matches the URL of the parent location block (in the example, /). You can also include the proxy_cache directive in a server block; it applies to all location blocks for the server that don’t have their own proxy_cache directive.

Read More

Sunday, May 14, 2017

Writing to a session variable with SessionStateBehavior.ReadOnly

Leave a Comment

In my ASP.NET MVC 5 application, I'm performing a GET request on a method inside a controller that needs to read a value stored in session. To avoid session state locking issue, I've set SessionStateBehavior to ReadOnly on the class level.

 [SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]     public class TestController: Controller     {          var test = Session["KEY"]; ... 

However, very occasionally, I need to overwrite the Session variable to something else inside that same method. ASP.NET MVC does not allow me to do this with SessionStateBehavior set to ReadOnly. I can't set it to Required because then I run into the issue of session state locking issue again, preventing concurrent AJAX requests.

What's a good solution for this?

Edit: We're using SQL server for session state management.

5 Answers

Answers 1

If you target .NET Framework 4.6.2 and you're on SQL Server, you could leverage the new async SessionState module to access the session storage providers asynchronously.

Download and install the SessionStateModule and the SqlSessionState NuGet packages.

Consider also that SQLServer mode stores session state in the SQL Server database.

Note (from the comments)

While the session in ASP.NET Core is non-locking, only next release of SqlSessionStateProviderAsync should introduce this feature, according to this msdn blog.

Alternative provider

Another, different option would be to use StackExchange.Redis: e.g. for a web app in Azure App Service, follow these configuration steps. More generally, in a Redis server or servers, RedisSessionProvider never locks the Session

Answers 2

create a customControllerFactory which inherit with DefaultControllerFactory, and override the GetControllerSessionBehavior(). then use ControllerBuilder.Current.SetControllerFactory() to register the factory at Application_Start

see http://www.c-sharpcorner.com/UploadFile/ff2f08/session-state-behavior-per-action-in-Asp-Net-mvc/

Answers 3

Because you're using a SQL Server session backend, I think you can achieve what you want by manually interacting with the session database and bending it to your will.

Familiarize yourself with the workings of a session provider, in particular the SqlSessionStateStore class. Under the hood, all it's doing is (de)serializing your data and calling the stored procedures in the session state database (specifically, check out SetAndReleaseItemExclusive).

If you can figure out how to construct a SessionStateStoreData object, or more specifically the ISessionStateItemCollection needed to construct it, from the session collection you have access to via the HttpContext plus whatever changes you want to make, you can then use reflection to call the internal static SessionStateUtility.SerializeStoreData method. After that, it should be trivial to call the correct stored procedure (based on the updated session's size).

Answers 4

You can dynamically set the session state behavior for every request. Based on some condition you can switch to SessionStateBehavior.Required and in any other case just use the default behavior.

You will need a custom MvcRouteHandler:

public class MyMvcRouteHandler : MvcRouteHandler {     protected override SessionStateBehavior GetSessionStateBehavior(RequestContext requestContext)     {         if (someCondition)         {             return SessionStateBehavior.Required;         }         // fallback to default behavior         return base.GetSessionStateBehavior(requestContext);     } } 

In the requestContext you will find HttpContext and based on that you can decide what to do.

You will need to set this new RouteHandler for every necessary route. You can do this in the RouteConfig file, put this after route registrations:

// ... routes.MapRoute(     name: "Default",     url: "{controller}/{action}/{id}",     defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); // ...  // set MyMvcRouteHandler for every route foreach (var route in routes.OfType<Route>()) {     route.RouteHandler = new MyMvcRouteHandler(); } 

Answers 5

The issue is a logic issue and two opposite business requirements which are: the readOnly and the need to modify that given some conditions. So, what i would do is to go back to your logic and cover the conditions. I would use the SessionStateBehavior() to sort of toggle. For example, add a simple if statement as follows (sudo code)

    If a condition is met that requires non readOnly then      SetSessionStateBehavior(     SessionStateBehavior required  ) 

// here do what you need to do then set it back

Read More

Tuesday, April 18, 2017

Is there an alternative of RewriteRule / .htaccess for a Python http.server.HTTPServer?

Leave a Comment

Can my server module (with http.server.HTTPServer) use something like the RewriteRule for redirect all traffic into a single cgi script? I'd like to be able to do what's shown here in this other question, but for my python server.

Can it be done using something like .htaccess, or is there another way?

Also, can this be done even for a simple localhost development server?
I am serving files for development via, for example, http://localhost:8000/html/index.html, and I would like to hide the /html subfolder from the URL even in development.
How can that be achieved?

1 Answers

Answers 1

You can use a custom script to initialize your server and define your Routes in it, such as suggested in this article.

Python 2:

server.py

import os import posixpath import urllib import BaseHTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler  # modify this to add additional routes ROUTES = (  <- this is the "good stuff", make aliases for your paths     # [url_prefix ,  directory_path]     ['/media', '/var/www/media'],     ['',       '/var/www/site']  # empty string for the 'default' match )   class RequestHandler(SimpleHTTPRequestHandler):      def translate_path(self, path):         """translate path given routes"""          # set default root to cwd         root = os.getcwd()          # look up routes and set root directory accordingly         for pattern, rootdir in ROUTES:             if path.startswith(pattern):                 # found match!                 path = path[len(pattern):]  # consume path up to pattern len                 root = rootdir                 break          # normalize path and prepend root directory         path = path.split('?',1)[0]         path = path.split('#',1)[0]         path = posixpath.normpath(urllib.unquote(path))         words = path.split('/')         words = filter(None, words)          path = root         for word in words:             drive, word = os.path.splitdrive(word)             head, word = os.path.split(word)             if word in (os.curdir, os.pardir):                 continue             path = os.path.join(path, word)          return path  if __name__ == '__main__':     BaseHTTPServer.test(RequestHandler, BaseHTTPServer.HTTPServer) 

Then run your script:

python server.py 

Python 3:

In Python 3 the BaseHTTPServer and the SimpleHTTPServer modules have been merged into the http.server module. So you will have to modify the above script as follows:

Change the

import BaseHTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler 

to

import http.server 

(if you do this then the calls should be modified to http.server.SimpleHTTPRequest etc.)

or

from http.server import BaseHTTPServer, SimpleHTTPServer, SimpleHTTPRequestHandler 

(with this option calls remain the same as the original script)

then run the server script: python server.py


IN YOUR CASE:

You should modify the ROUTES variable to suite your needs.
For example, you want to hide the /html folder from your url:

ROUTES = (     ['', '/exact/path/to/folder/html'],     ['/another_url_path', '/exact/path/to/another/folder'],     ... ) 

Now if you hit: http://localhost:8000/index.html you will be in your home page.


Note: This script by default will serve the contained files in the folder that is in when executed to the domain url (ex. I have server.py on the Documents folder, then when I run it, http://localhost:8000 url will server my Documents folder).
You can change this behavior by the Routes (see the 'default' match comment on the code) or by placing the script in your projects root folder and start it from there.

Good luck :)

Read More

Friday, April 14, 2017

Monitoring HTTP requests and WebSockets in Netbeans

Leave a Comment

I am writing a HTTP and WebSocket client in Java to connect to any http server.

I wrote something similar in js before and was able to use the network tab of the developer tools in firefox and chrome to see what HTTP requests were sent and what Websocket messages were exchanged.

My question is: is there any tool or plugin for Netbeans to see these same requests and messages?

2 Answers

Answers 1

Netbeans comes with an HTTP Monitor which you can access via Window -> HTTP Monitor.

Netbeans HTTP Monitoring

Answers 2

If your intent is to observe / log / inspect outgoing and incoming connections from your tool, then you would need to intercept the traffic somehow.

Wireshark can help with that. If the transport is over SSL then Wireshark may not be much help.

You could use a reverse proxy like charles, intercept the traffic and inspect it there. https://www.charlesproxy.com/documentation/proxying/reverse-proxy/

Also, here is a similar question : Log all network interactions of Java application

Hope it helps. Also, not entirely sure why you would need a netbeans plugin? When your application is running, it will do so in its own JVM, so unless you are planning on packaging the plugin with your tool, I don't see how you can use it.

Read More

Sunday, March 26, 2017

Live video streaming from recording files over HTTP based on PHP

Leave a Comment

I want to organize live streaming from recording files over HTTP based on PHP.

INTRODUCTION: On the streaming server I writing video to local file(local_file.mpg) and when received a request from client then start streaming to it from
$start_byte = filesize("local_file.mpg")-10MB; The local_file.mpg is still writing and PHP script continue reading it and flushing.

PROBLEM: I streaming it via HTTP Range with the following headers:

header('HTTP/1.1 206 Partial Content'); header("Content-Type: video/mpeg"); header('Content-Length: '.($seek_end - $seek_start)); header('Content-Range: bytes '.$seek_start.'-'.$seek_end.'/'.$size); 

And flushing as follows:

while(!feof($fp)){     $buf_size = 1024*8;     $pos = ftell($fp);     if ($pos >= $item["to_byte"]){             fclose($fp);             break;     }      if ($pos + $buf_size > $item["to_byte"]){         $buf_size = $item["to_byte"] - $pos;     }      if ($buf_size > 0){         echo fread($fp, $buf_size);     }      flush();     ob_flush(); } 

I open it via VLC or FFplay, but it played until the time moment when the stream was requested. This is to be expected, because we determine the size of the file and provide it to requested side. But if we artificially increase a file size, for example
$size = filesize("local_file.mpg")+999999999999; it also not help, because video players requesting new data too early when it is not recorded. And also stopped play at the time moment when the stream was requested.

1. Please advice how to correct organize live streaming from recording files over HTTP based on PHP.
2. Is it possible to do it with HTTP RANGE mechanism or I should use another way?


UPDATE: Based on this question I tried the next code:

<?php  $file = "online.mpg";  function flush_buffers(){     ob_end_flush();     ob_flush();     flush();     ob_start(); }  header('Content-Type: video/mpeg'); $stream = fopen( $file, "rb" ); fseek($stream, (filesize($file)-10000000), SEEK_SET);  while(1){     $response = fread($stream, 8192);      echo $response;     flush_buffers(); }  fclose( $stream ); exit(); ?> 

And it works well via ffplay, but via VLC it played no more then 1 minute and stoped then.
Please advice how to make it work on VLC also?

1 Answers

Answers 1

Do you have a time limit for php execution ? if yes , change it to unlimited with :

set_time_limit(0); 
Read More

Monday, March 20, 2017

Express.js http call inside route doesn't update variable

Leave a Comment

I'm building a REST api on top of express.js. I am having trouble updating variables inside my routes.

Example:

I'm calling app.get("/wp/page/create/:id", function(req, res)

Inside this route I start by calling a http request using request-promise library. The response of this call I use in a nested http call.

I use a global variable for the headers for the nested call, and it's to the header a i need to make changes by using the etag variable.

Code:

global.postHeaders = headers; postHeaders['X-HTTP-Method'] = "MERGE"; postHeaders['Content-Type'] = 'application/json;odata=verbose'; postHeaders['X-RequestDigest'] = spContext;  request.get({ url: "xxx", headers: headers, json: true }).then(function(response) {     var etag = response.d.__metadata.etag     postHeaders['If-Match'] = etag;      request.post({        url: "xxx",        type: "POST",        body: data,        headers: postHeaders,        json: true        }).then(function(data) {           res.send(data).end()           console.log("All done!");       }) }) 

When i start the server up and enter the route everything works fine. When i when try to hit it again the etag variables is still the same, even though it should be updated.

If I restart the server it works the again on the first attempt but fails on the second/third.

Any idea what I am doing wrong?

2 Answers

Answers 1

I have resolved the issues. The simple solution was to clear the headers containing the variable.

global.postHeaders = headers; postHeaders['X-HTTP-Method'] = "MERGE"; postHeaders['Content-Type'] = 'application/json;odata=verbose'; postHeaders['X-RequestDigest'] = spContext;  request.get({  url: "xxx",  headers: headers,  json: true  }).then(function(response) { var etag = response.d.__metadata.etag postHeaders['If-Match'] = etag;     request.post({      url: "xxx",      type: "POST",      body: data,      headers: postHeaders,      json: true      }).then(function(data) {       postHeaders['If-Match'] = "";       res.send(data).end()       console.log("All done!");   }) }) 

Answers 2

postHeaders is a global variable. is headers in global.postHeaders = headers; also a global varaible ? Whatever you are trying to do here is grossly wrong. postHeaders variable will be shared across multiple request. so you will hit a scenario where postHeaders['If-Match'] value might be empty string or the etag .

Try this instead of the first line var postHeaders = Object.assign({}, headers);

Not sure what you are trying, but at-least this statement will subside the huge error in the code. This will create a new header object for each request.

Read More

Thursday, March 16, 2017

update my graph in UI after service returns with JSON

Leave a Comment

I have a service that returns an object successfully from my API. By the time this is returned however I have already rendered my custom graph component with their default values.

I can pull the value of 'title' for example from the object, see \\'works!' comment

How can I update my graph component's 'chart1Title'?

import { Component } from '@angular/core'; import { HttpWebServiceService1 } from './http-web-service-service'; import { Chart } from './bar-chart-demo/chartModel'; @Component({   selector: 'app-root',   templateUrl: './app.component.html',   styleUrls: ['./app.component.css'],   providers: [HttpWebServiceService1] }) export class AppComponent {     charts: Chart[];     thisChartObject: Array<Object>;     thisChartsTitle: string;     constructor(HttpWebServiceService1: HttpWebServiceService1){     HttpWebServiceService1.getHTTP()       .subscribe(         charts =>          {           console.log(charts); //works           console.log(charts['charts'][0]['title']); //works this.chart1Title = charts['charts'][0]['title']; //does not work         },         error => console.error('Error: ' + error),         () => console.log(charts[0])       );    }    //Draw chart with some default values   chart1Data:any[] = [     {data: [3, 1, 1], type: 'bar'}   ];   chart1Label:string[] = [Label1', 'Label2', 'Label3'];   chart1Type='bar';   chart1Title = 'my graph title'; } 

My HTML

<!-- Header --> <div class="flex-container-header"      fxLayout="row"      fxLayoutAlign="space-between center">   <div class="flex-item">      <img src="../../assets/img/my_logo.png" >   </div>   <div class="flex-item" fxFlex=10>     <img src="../../assets/img/my_logo1.png" ng-href="www.site.ie" >   </div> </div>   <!--Headline Chart--> <div *ngIf="!isLoading">   <div class="flex-container"       fxLayout="row"       fxLayout.md="column"      fxLayout.sm="column"      fxLayout.xs="column"      fxLayoutAlign="center">   <div class="flex-item" fxFlex=60 fxFlex.md=100 fxFlex.sm=100 fxFlex.xs=100> <app-bar-chart-demo [chartLabel]="chart1Label" [chartData]="chart1Data" [chartType]="chart1Type" [(chartTitle)]="chart1Title"></app-bar-chart-demo>  </div> </div> </div>     <p></p> </div> 

2 Answers

Answers 1

I have same issue in my work, for me, I use a flag: isLoading

    export class AppComponent {         charts: Chart[];         thisChartObject: Array<Object>;         thisChartsTitle: string;          isLoading: boolean;         constructor(HttpWebServiceService1: HttpWebServiceService1){         this.isLoading = true;         HttpWebServiceService1.getHTTP()           .subscribe(             charts =>              {               console.log(charts); //works               console.log(charts['charts'][0]['title']); //works               this.updateData(charts);             },             error => console.error('Error: ' + error)           );        }        public updateData(charts: any) {         this.chart1Title = charts['charts'][0]['title'];         this.isLoading = false;       }     } 

in your *.component.html:

    <div *ngIf="!isLoading">       <your-chart></your-chart>     </div> 

Hope it helps.

Answers 2

You need the object before rendering the page so I suggest using a resolve :

Thoughtram blog Resolve example

Resolve documentation

If this doesn't fix the issue you are having , I would suggest implementing a lifecycle hook.

Read More