Wednesday, September 3, 2014

How To: Send HTTP POST Request in Java using Apache HttpClient

This example code shows how you can send data (or parameters) to a URL using POST. This is the complete program source code.

The Apache HttpClient library simplifies handling HTTP requests. To use this library download the binaries with dependencies from http://hc.apache.org/ and add them to your project classpath.

HttpClient class is used to retrieve and send data. An instance of this class can be created with new DefaultHttpClient(). DefaultHttpClient is the standard HttpClient.

The HttpClient uses a HttpUriRequest to send and receive data. HttpPost is an important subclass of HttpUriRequest. The response of the HttpClient can be get as an InputStream.

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class PostDataExample {

    public static String postData(String postURL, String urlParameters) {
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(postURL);

            StringEntity strEntity = new StringEntity(urlParameters);
            httppost.setEntity(strEntity);
            httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
 
            // Execute HTTP Post Request
            HttpResponse response = client.execute(httppost);
         
            // Read response
            InputStream in = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null){
                result.append(line);
            }
            in.close();
         
            return result.toString();
         
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) {
        String params = "id=1432&name=Testing&locale=";
        System.out.println(postData("http://www.example.com/test.php", params));
    }

}


Feel free to comment if you have any questions about the code above.

Tuesday, September 2, 2014

How To: Download contents of a URL in Java using HTTPClient

This Java function can be used to download a webpage into a StringBuilder instance using the HTTPClient class. You have to import the necessary libraries.

public static String getURLContents(String url) {
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);
    StringBuffer str = new StringBuffer();
 
    try {
        HttpResponse response = client.execute(request);
        InputStream in = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader( new InputStreamReader(in) );
        String line = "";
        while ((line = reader.readLine()) != null){
            str.append(line);
        }
        in.close();
    } catch (Exception e) {return "";}
 
    return str.toString();
}


If you have any questions, feel free to comment below.

Monday, September 1, 2014

How To: Show Posts From Only Specific Categories on Your WordPress Homepage

Sometimes you'll need to show posts from only one category on your homepage. It's easy enough to do it. Following are the steps you need to follow:

Find Your Category ID

First you will have to find the ID of the category you want to show. When you're in the admin, hover over the edit link (or the title) for any of your categories and look at the address in your status-bar (that's the bar along the bottom of your browser window if you don't know about it), you should see the category ID at the end of the URL.

You can also use a plugin called Reveal IDs for this purpose.

Insert Code

Once you have your category ID, open your functions.php file and insert the following function code: (Appearances > Editor > Theme Functions – functions.php)

function my_home( $query ) {
  if ( $query->is_home() && $query->is_main_query() ) {
     $query->set( 'cat', '5');
  }
}
add_action( 'pre_get_posts', 'my_home' );


In this example above, the category ID I have used is 5.

If you would like to include more than one category, then just add another ID by inserting a comma and the ID number. For example, this will display posts from category 5 and 6:

$query->set( 'cat', '5, 6' );

You can also use get_cat_id() function for retrieving the category, like this:

$cat_id = get_cat_id('category name');
$query->set( 'cat', $cat_id );


And that's all. You should now see posts only from this category on your homepage.

Happy coding!

Sunday, August 31, 2014

How To: Missing String Related Functions in C++ - Replace, Split, Trim etc.

String manipulation functions are really important and we often find ourselves needing them while coding in C++. High-level languages like C# and Java etc. provide such functions through methods of a string class. However, they are not inherently present in C++.

Here are some of the more frequently used string related functions. They are pretty self-explanatory. All of them are independent functions. Hope you find them useful.

Note: Don't forget to include the appropriate headers: <string> <vector> <sstream>

using namespace std;

string strToLowerCase(string str) {

    const int length = str.length();
    for(int i=0; i < length; ++i) {
        str[i] = tolower(str[i]);
    }
    return str;
}

string strToUpperCase(string str) {

    const int length = str.length();
    for(int i=0; i < length; ++i) {
        str[i] = toupper(str[i]);
    }
    return str;
}

void strReplace(string &str, const string what, const string to) {

    if (str.empty() || what.empty()) return;

    size_t pos;
    while ( (pos = str.find(what)) != string::npos ) {
        str.replace(pos, what.length(), to);
    }
}

vector<string> strSplit(string s, char delim) {
    vector<string> elems;
    stringstream ss(s);
    string item;
    while(getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}

string strTrim(string str) {

    size_t pos1 = str.find_first_not_of(" \t");
    size_t pos2 = str.find_last_not_of(" \t");

    str = str.substr(pos1 == string::npos ? 0 : pos1,
        pos2 == string::npos ? 0 : pos2 - pos1 + 1);

    return str;
}

bool strStartsWith(string str, string start) {

    if (start.length() > str.length()) return false;
    if ( str.substr(0, start.length()) == start ) return true;
    else return false;
}

bool strEndsWith(string str, string end) {

    if (end.length() > str.length()) return false;
    if ( str.substr(str.length() - end.length()) == end ) return true;
    else return false;
}

int strCountWords(string str) {

    int count = 0;
    for (int i=0; i < str.length(); i++) {
        if (isspace(str.at(i))) count++;
    }
    return (count+1);
}


Thursday, August 28, 2014

PHP 7: What To Expect? Features and Expected Release Date

We are not completely sure about the exact feature set of version 7 of PHP. There are some features that we can talk about since they are being implemented in PHP 7. The rest we can only speculate based on reasonable guesses.

1. PHPNG to Become Basis for PHP 7

PHPNG is an improved PHP codebase which increases the performance gains anywhere between 20% and 110% in real world applications such as Wordpress, Drupal or SugarCRM. It also significantly reduces memory consumption.

The goal now is to officially accept the new codebase as the basis for the next major version of PHP. Once that happens, we will generally stop referring to phpng as phpng, and will start referring to it only as PHP 7. This upgrade will bring a huge performance improvement to PHP.

2. JIT Engine

According to Dmitry Stogov of Zend, the motivation of starting the development of PHPNG was to research the implementation of a JIT engine for the Zend Engine based PHP. Such an engine can dynamically compile Zend opcodes into native machine code with the result that the code will run faster the next time it is run.

It is certainly likely that a JIT engine will be brought to PHP 7, as according to Zeev Suraski it can "push performance through the roof for an already ultra fast implementation".

3. AST: Abstract Syntax Tree

Recently, Nikita Popov proposed the introduction of an Abstract Syntax Tree (AST) as an intermediary structure in PHP compilation process.

As described in his proposals, the two primary advantages of using AST are:
  1. More maintainable parser and compiler and better code quality
  2. No more syntactical decisions due to technical restrictions

Nikita already provided a patch to implement AST support on top of the PHPNG branch.

4. Asynchronous Programming

Facebook Hack provides a very elegant support for asynchronous programming. PHP core developers are also moving fast towards making asynchronous programming available in PHP sooner rather than later.

Recently, Julien Pauli, one of the developers of the latest PHP releases, has been commenting about refactoring PHP I/O multiplexing layer.

This feature would allow future versions of PHP to easily implement support to the execution of parallel tasks within the same request, which will result in pushing performance improvement potential of PHP to the next level.  Of course, we won’t get performance improvements automatically just by enabling the support for asynchronous programming. New PHP code needs to be written to take advantage of its potential.

However, despite the initial effort of Jean Pauli, it is not necessary that asynchronous programming built-in support will be enabled in PHP 7.

5. Standalone Multi-threading Web Server

This feature might not make in PHP 7 version, but it is something that would make PHP more scalable. This feature is already present in HHVM which can be run as a standalone multi-threading Web server. This allows Facebook to reduce the numbers of server machines needed to handle the high traffic load.

Multi-threaded Web servers like ngynx, lighttpd or even Apache in worker mode can be be used to run PHP, however that is not the same as having PHP run on its own multi-threading Web server.

A multi-threading Web server can handle many simultaneous requests using a single memory pool. It would also allow PHP use a single pool of database connections, thus minimizing the number of simultaneous database connections opened during access peaks.

When will PHP 7 be released?

It is too early to predict the release date of PHP 7. Some people say that it will take around 1 to 3 years. A reasonable guess is to expect a final PHP 7 release some time in 2016, although it is possible that we see an early alpha version before that.

So in conclusion, you will have to wait for at least one year until you can start learning about it.

What do YOU think about PHP 7? What would you like to see happening to the PHP language in future? Let me know through your comments.

Tags: PHP 7 release date, PHP 7 features, PHP 7 improvements

C++ - Take Screenshot of the Windows Desktop using GDI+

Here is the complete C++ source code for taking screenshot in Windows:

#include <iostream>
#include <string>
#include <windows.h>
#include <gdiplus.h>

#pragma comment(lib, "gdiplus.lib")

using namespace std;
using namespace Gdiplus;

int GetEncoderClsid(WCHAR *format, CLSID *pClsid)
{
    unsigned int num = 0,  size = 0;
    GetImageEncodersSize(&num, &size);
    if(size == 0) return -1;
    ImageCodecInfo *pImageCodecInfo = (ImageCodecInfo *)(malloc(size));
    if(pImageCodecInfo == NULL) return -1;
    GetImageEncoders(num, size, pImageCodecInfo);
 
    for (unsigned int j = 0; j < num; ++j) {
        if(wcscmp(pImageCodecInfo[j].MimeType, format) == 0) {
            *pClsid = pImageCodecInfo[j].Clsid;
            free(pImageCodecInfo);
            return j;
        }  
    }
    free(pImageCodecInfo);
    return -1;
}

int SaveScreenshot(string filename, ULONG uQuality) // by Napalm
{
    ULONG_PTR gdiplusToken;
    GdiplusStartupInput gdiplusStartupInput;
    GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
    HWND hMyWnd = GetDesktopWindow();
    RECT r;
    int w, h;
    HDC dc, hdcCapture;
    int nBPP, nCapture, iRes;
    LPBYTE lpCapture;
    CLSID imageCLSID;
    Bitmap *pScreenShot;
 
    // get the area of my application's window    
    GetWindowRect(hMyWnd, &r);
    dc = GetWindowDC(hMyWnd);   // GetDC(hMyWnd) ;
    w = r.right - r.left;
    h = r.bottom - r.top;
    nBPP = GetDeviceCaps(dc, BITSPIXEL);
    hdcCapture = CreateCompatibleDC(dc);

    // create the buffer for the screenshot
    BITMAPINFO bmiCapture = { sizeof(BITMAPINFOHEADER), w, -h, 1, nBPP, BI_RGB, 0, 0, 0, 0, 0, };

    // create a container and take the screenshot
    HBITMAP hbmCapture = CreateDIBSection(dc, &bmiCapture, DIB_PAL_COLORS, (LPVOID *)&lpCapture, NULL, 0);

    // failed to take it
    if (!hbmCapture) {
        DeleteDC(hdcCapture);
        DeleteDC(dc);
        GdiplusShutdown(gdiplusToken);
        printf("failed to take the screenshot. err: %d\n", GetLastError());
        return 0;
    }

    // copy the screenshot buffer
    nCapture = SaveDC(hdcCapture);
    SelectObject(hdcCapture, hbmCapture);
    BitBlt(hdcCapture, 0, 0, w, h, dc, 0, 0, SRCCOPY);
    RestoreDC(hdcCapture, nCapture);
    DeleteDC(hdcCapture);
    DeleteDC(dc);

    // save the buffer to a file  
    pScreenShot = new Bitmap(hbmCapture, (HPALETTE)NULL);
    EncoderParameters encoderParams;
    encoderParams.Count = 1;
    encoderParams.Parameter[0].NumberOfValues = 1;
    encoderParams.Parameter[0].Guid  = EncoderQuality;
    encoderParams.Parameter[0].Type  = EncoderParameterValueTypeLong;
    encoderParams.Parameter[0].Value = &uQuality;
    GetEncoderClsid(L"image/jpeg", &imageCLSID);

    wchar_t *lpszFilename = new wchar_t[filename.length() + 1];
    mbstowcs( lpszFilename, filename.c_str(), filename.length() + 1);
 
    iRes = (pScreenShot->Save(lpszFilename, &imageCLSID, &encoderParams) == Ok);
    delete pScreenShot;
    DeleteObject(hbmCapture);
    GdiplusShutdown(gdiplusToken);
    return iRes;
}

// Example program code:

int main() {
    string path = "screenshot.jpg";
    ULONG quality = 100;
    SaveScreenshot(path, quality);
 
    return 0;
}


If you have any problem running this code, please comment below. I will be glad to help you out.

Tags: screenshot in C++, screenshot using gdiplus, gdiplus library

C++ - Get File Size in KB/MB/GB Format using stat()

This code uses stat() function of the built-in sys/stat.h header file, to get the size of a file.

The size is then passed to convertSize function which converts the file size to a suitable unit and returns the result as a string value.

You might want to know that stat(), however, isn't part of the C++ standard, so it may or may not be available in your compiler.

These utility functions are really useful and might come in handy for you in solving other problems as well.

#include <iostream>
#include <string>
#include <sstream>
#include <windows.h>
#include <sys/stat.h> /* for stat() function */

using namespace std;

// Utility functions:


string convertToString(double num) {
    ostringstream convert;
    convert << num;
    return convert.str();
}

double roundOff(double n) {
    double d = n * 100.0;
    int i = d + 0.5;
    d = (float)i / 100.0;
    return d;
}

string convertSize(size_t size) {              
    static const char *SIZES[] = { "B", "KB", "MB", "GB" };
    int div = 0;
    size_t rem = 0;

    while (size >= 1024 && div < (sizeof SIZES / sizeof *SIZES)) {
        rem = (size % 1024);
        div++;
        size /= 1024;
    }

    double size_d = (float)size + (float)rem / 1024.0;
    string result = convertToString(roundOff(size_d)) + " " + SIZES[div];
    return result;
}

int file_size(const char *path) {
    struct stat results;

    if (stat(path, &results) == 0) {
        return results.st_size;
    } else {
        return -1;
    }
}

// This is the function that you will call:
string getFileSize(string path) {
    size_t size = file_size((const char *)path.c_str());
    return convertSize(size);
}


// Example program:
int main() {
    cout << getFileSize("D:\\httrack_x64-3.48.13.exe") << endl;
    return 0;
}


This code has been test with Visual Studio 2008 and Dev-C++. If you have any problems running this code, please comment below. I will be glad to help you out.

Tags: C++, convert size, file size in c++, round off, size in string, length of file in c++