Wednesday, December 5, 2012

Php make zip file

$zip = new ZipArchive();
$zipFileDir = "c:/src/";
$zipFileName = "test.zip";
$zip->open($zipFileDir.$zipFileName, ZIPARCHIVE::CREATE);

/* FROM FOLDER c:/files/ */
$zipIncludedFilesDir = "c:/files/";
chdir($zipIncludedFilesDir);
$zip->addFile("a.jpg");
$zip->addFile("b.jpg");
$zip->close();
if(file_exists($zipFileDir.$zipFileName)) {
    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename='.$zipFileName);
    header('Content-Length: ' . filesize($zipFileDir.$zipFileName));
    readfile($zipFileDir.$zipFileName);
    unlink($zipFileDir.$zipFileName);
}
exit;

Java check if file exists on remote server using its url

import java.net.*;
import java.io.*;

public class URLUtils {

  public static void main(String s[]) {
    System.out.println(URLUtils.exists("http://www.test.com/exists.html"));
    System.out.println(URLUtils.exists("http://www.test.com/no_exists.html"));
    /*
      output :
        true
        false
    */    
  }

  public static boolean exists(String URLName){
    try {
      HttpURLConnection.setFollowRedirects(false);
      // note : you may also need
      //        HttpURLConnection.setInstanceFollowRedirects(false)
      HttpURLConnection con =
         (HttpURLConnection) new URL(URLName).openConnection();
      con.setRequestMethod("HEAD");
      return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    }
    catch (Exception e) {
       e.printStackTrace();
       return false;
    }
  }
}
 
 
The following is doing the same thing but this time we identify ourself to a proxy.
See also this HowTo.
 
import java.net.*;
import java.io.*;
import java.util.Properties;

public class URLUtils {

  public static void main(String s[]) {
    System.out.println(exists("http://www.your_server.com"));
    System.out.println(exists("http://www.yahoo.com"));
  }


  public static boolean exists(String URLName){
    try {
      Properties systemSettings = System.getProperties();
      systemSettings.put("proxySet", "true");
      systemSettings.put("http.proxyHost","proxy.mycompany.local") ;
      systemSettings.put("http.proxyPort", "80") ;

      URL u = new URL(URLName);
      HttpURLConnection con = (HttpURLConnection) u.openConnection();
      //
      // it's not the greatest idea to use a sun.misc.* class
      // Sun strongly advises not to use them since they can 
      // change or go away in a future release so beware.
      //
      sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
      String encodedUserPwd =
         encoder.encode("domain\\username:password".getBytes());
      con.setRequestProperty
         ("Proxy-Authorization", "Basic " + encodedUserPwd);
      con.setRequestMethod("HEAD");
      System.out.println
         (con.getResponseCode() + " : " + con.getResponseMessage());
      return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    }
    catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
}  

http://www.rgagnon.com/javadetails/java-0059.html

Run Multiple Java Thread

bool isFinished = false;
final ProgressDialogue dialogue = new ProgressDialogue("Loading...");
final Thread progressThread = new Thread() {
    public void run() {
        dialogue.setVisible(true);
    }
};
final Thread progressEvent = new Thread() {
    public synchronized void run() {
        /* DO SOME WORK */
        isFinished = true;
    }
};
 final Runnable doFinished = new Runnable() {
     public void run() { saveBackupFile(); }
};
final Thread progressMonitor = new Thread() {
    public void run() {
        while (true) {
            try {
                /* SLEEP SOME TIME 1000 ms */
                Thread.sleep(1000);
            } catch (Exception ex) {

            }
            /* WAIT FOR WORK FINISHED */
            if (isFinished) {
                /* FINISH ALL */
                Thread.currentThread().interrupt();
                break;
            }
        }
         /* CALL DO FINISH METHOD WHEN THIS PROCESS REACH TO END */
         SwingUtilities.invokeLater(doFinished);
    }
};
progressThread.start();
progressEvent.start();
progressMonitor.start();

Tuesday, December 4, 2012

Execute shell commands in PHP

/**
Method to execute a command in the terminal
Uses :

1. system
2. passthru
3. exec
4. shell_exec

 */
function terminal($command)
{
    //system
    if (function_exists('system')) {
        ob_start();
        system($command, $return_var);
        $output = ob_get_contents();
        ob_end_clean();
    } //passthru
    else if (function_exists('passthru')) {
        ob_start();
        passthru($command, $return_var);
        $output = ob_get_contents();
        ob_end_clean();
    } //exec
    else if (function_exists('exec')) {
        exec($command, $output, $return_var);
        $output = implode("\n", $output);
    } //shell_exec
    else if (function_exists('shell_exec')) {
        $output = shell_exec($command);
    } else {
        $output = 'Command execution not possible on this system';
        $return_var = 1;
    }

    return array('output' => $output, 'status' => $return_var);
}

Use as this way:
$o = terminal('ls');
print_r($o);

http://www.binarytides.com/execute-shell-commands-php/

How to know that a string starts/ends with a specific string in jQuery

One option is to use regular expressions:
if (str.match("^Hello")) {
   // ...
}

if (str.match("World$")) {
   // ...
}

How to download and save a file from url using Java

Give a try to Java NIO:

try {
    URL url = new URL("http://portal.com/img/logo-header.gif");
    ReadableByteChannel rbc = Channels.newChannel(url.openStream());
    FileOutputStream fileOutputStream = new FileOutputStream("C:\\src\\a.gif");
    fileOutputStream.getChannel().transferFrom(rbc, 0, 1 << 24);
} catch (Exception ex) {
    ex.printStackTrace();
}

Using transferFrom() is potentially much more efficient than a simple loop that reads from the source channel and writes to this channel. Many operating systems can transfer bytes directly from the source channel into the filesystem cache without actually copying them.
http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html 

Sunday, December 2, 2012

jQuery Tabs Tutorial

See total result in jsFiddle

Html for tab

<ul class='tabs'>
    <li><a href='#tab1'>Tab 1</a></li>
    <li><a href='#tab2'>Tab 2</a></li>
    <li><a href='#tab3'>Tab 3</a></li>
</ul>
<div style='clear: both;'>&nbsp;</div>
<div class='tab_div' id='tab1'>
    <p>Hi, this is the first tab.</p>
</div>
<div class='tab_div' id='tab2'>
    <p>This is the 2nd tab.</p>
</div>
<div class='tab_div' id='tab3'>
    <p>And this is the 3rd tab.</p>
</div>

jQuery code to make tab


$('ul.tabs').each(function(){
    // For each set of tabs, we want to keep track of
    // which tab is active and it's associated content
    var $active, $content, $links = $(this).find('a');

    // If the location.hash matches one of the links, use that as the active tab.
    // If no match is found, use the first link as the initial active tab.
    $active = $($links.filter('[href="'+location.hash+'"]')[0] || $links[0]);
    $active.addClass('active');
    $content = $($active.attr('href'));

    // Hide the remaining content
    $links.not($active).each(function () {
        $($(this).attr('href')).hide();
    });

    // Bind the click event handler
    $(this).on('click', 'a', function(e){
        // Make the old tab inactive.
        $active.closest("ul").find(".active").removeClass('active');
        $content.hide();

        // Update the variables with the new link and content
        $active = $(this);
        $content = $($(this).attr('href'));

        // Make the tab active.
        $active.addClass('active');
        $active.closest("li").addClass("active");
        $content.show();

        // Prevent the anchor's default click action
        e.preventDefault();
    });
});

Css


ul {
    display: inline;
}
ul.tabs li {
    float: left;
    margin: 10px 15px 10px 0;
    list-style-type: none;
    border: 1px solid gray;
}
ul.tabs li a {
    text-decoration: none;
    padding: 5px;
}
ul.tabs li a.active {
    font-weight: bold;
    color: blue;
}
div.tab_div {
    background-color: gray;
    padding: 20px;
}

Output is as following