Monday 26 December 2011

Retrieve list of Lotus Notes forms

Retrieve list of Lotus Notes forms
This task retrieve list of Lotus Notes forms including name and xml data.
Retrieve list of Lotus Notes forms using java, DxlExporter and jsoup
  1. Create getFormList as following
  2. Call getFormList method as following
Call method
try {
    String idfile = "";
    String password = "";
    String server = "";
    String filepath = "";
    NotesThread.sinitThread();
    Session s = NotesFactory.createSessionWithFullAccess();
    s.createRegistration().switchToID(idfile, password);
    Database d = s.getDatabase(server, filepath);
    Map<String, String> forms = getFormList(d);
    for (String key : forms.keySet()) {
        logger.info("Form: " + key);
        logger.info(forms.get(key));
    }
} catch (Exception e) {
    logger.error("", e);
}
    
getFormList method
public Map<String, String> getFormList(Database db) {
    Map<String, String> tag = new HashMap<String, String>();
    try {
        NoteCollection nc = db.createNoteCollection(false);
        nc.setSelectForms(true);
        nc.buildCollection();
        String noteId = nc.getFirstNoteID();
        int fileNo = 0;
        while (noteId != null) {
            try {
                lotus.domino.Document doc = db.getDocumentByID(noteId);
                DxlExporter dxl = db.getParent().createDxlExporter();
                dxl.setConvertNotesBitmapsToGIF(true);
                String xml = dxl.exportDxl(doc);
                dxl.recycle();
                doc.recycle();

                xml = xml.substring(xml.indexOf("<form "));
                org.jsoup.nodes.Document jdoc = Jsoup.parse(xml);
                Element element = jdoc.select("form").first();
                tag.put(element.attr("name"), xml);
            } catch (Exception e) {
                logger.error("", e);
            }
       
            fileNo++;
            if (fileNo == nc.getCount()) {
                noteId = null;
            } else {
                noteId = nc.getNextNoteID(noteId);
            }
        }
        nc.recycle();
    } catch (Exception e) {
        logger.error("", e);
    }
    return tag;
}
    

  Protected by Copyscape Online Copyright Protection

Initialize logger by java

Initialize logger by java
This task use java to initialize logger.
Initialize logger
  1. Create /cfg/log-conf.xml as following
  2. Create initLog method as following
  3. At beginning of program, call initLog method
/cfg/log-conf.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration>
    <appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
        <param name="File"   value="log/bruchia.log" />
        <param name="Append" value="true" />
        <param name="MaxFileSize" value="1024KB" />
        <param name="MaxBackupIndex" value="10240" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" 
                   value="%d %-5p [%t] %C{2} %M (%F:%L) - %m%n"/>
        </layout>     
    </appender>
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                   value="%d %-5p [%t] %C{2} %M (%F:%L) - %m%n"/>
        </layout>     
    </appender>
    
    <category name="org.apache.log4j.xml">
        <priority value="warn" />
        <appender-ref ref="fileAppender" />
        <appender-ref ref="STDOUT" />
    </category>
    
    <logger name="org.apache" >
            <level value ="warn" />
    </logger>
    
    <root>
        <priority value ="info" />
        <appender-ref ref="fileAppender" />
        <appender-ref ref="STDOUT" />
    </root>
</log4j:configuration>
    
initLog method
private static void initLog() {
    try {
        String configDir = new File(System.getProperty("user.dir"), "cfg").getAbsolutePath();
        String logConfigFile = new File(configDir, "log-conf.xml").getAbsolutePath();
        String logDir = new File(System.getProperty("user.dir"), "log").getAbsolutePath();
        String stdoutLogFile = new File(logDir, "stdout.log").getAbsolutePath();
   
        DOMConfigurator.configure(logConfigFile);
        System.setErr(new PrintStream(new BufferedOutputStream(new FileOutputStream(stdoutLogFile)), true));
        System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(stdoutLogFile)), true));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
    

  Protected by Copyscape Online Copyright Protection

Format code with line number

Format code with line number.
This task use javascript to format code in <pre> tag with line number.
Format code with line number using jQuery
  1. Put code in <pre class='code'></pre> tags.
  2. Add following code at the end of page.
<style>
.code-viewer { border: solid 1px silver; font-family: monospace; font-size: 12px; padding: 5px; background-color: white; margin-bottom: 10px; }
.code-viewer-inner { width: 100%; border-top: solid 1px #E3E3E3; }
.code-viewer .line .number { width: 40px; background-color: teal; color: white; border-bottom: solid 1px #E3E3E3; padding: 0px 5px 0px 5px; }
.code-viewer .line .data { border-bottom: solid 1px #E3E3E3; white-space: pre-wrap; padding-left: 5px; }
.code-viewer .action { padding: 0px 0px 5px 0px; }
.code-viewer .action a { text-decoration: none; color: teal; font-family: Arial, sans-serif; font-size: 12px; font-weight: bold; margin: 0px 5px 0px 5px; }
.code-viewer .action a:hover { text-decoration: underline; }
.code-viewer .raw-code { display: none; }
</style>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
var cv_ids = new Array();
function cv_getId() {
  var id = 'E' + Math.floor(Math.random() * 100000); 
  while (cv_ids.indexOf(id) >= 0) {
    id = 'E' + Math.floor(Math.random() * 100000); 
  }
  cv_ids.push(id);
  return id;
}
function cv_process(esrc) {
  esrc = $(esrc);
  var src = esrc.html();
  esrc.hide();
  var id = cv_getId();
  var id2 = cv_getId();
  var id3 = cv_getId();
  esrc.after("<div id='" + id + "' class='code-viewer'><div id='" + id2 + "' class='action'></div><table cellspacing='0' cellpadding='0' class='code-viewer-inner'></table><div id='" + id3 + "' class='raw-code'></div></div>");
  var etag = $('#' + id + ' .code-viewer-inner');
  var eaction = $('#' + id2);
  eaction.append("<a href='javascript:return false;' onclick=\"var e1 = $('#" + id + " .code-viewer-inner'); var e2 = $('#" + id3 + "'); e1.show(); e2.hide();\">formatted</a>");
  eaction.append("<a href='javascript:return false;' onclick=\"var e1 = $('#" + id + " .code-viewer-inner'); var e2 = $('#" + id3 + "'); e2.show(); e1.hide();\">raw</a>");
  var eraw = $('#' + id3);
  var lines = src.split('\n');
  var src2 = '';
  for (var i = 0; i < lines.length - 1; i++) {
    var line = lines[i];
    line = line.replace(/\</g, '<');
    line = line.replace(/\>/g, '>');
    id = cv_getId();
    etag.append("<tr id='" + id + "' class='line'></tr>");
    var eline = $('#' + id);
    id = cv_getId();
    id2 = cv_getId();
    eline.append("<td id='" + id + "' class='number'></td><td id='" + id2 + "' class='data'></td>");
    var enumber = $('#' + id);
    enumber.text(i + 1);
    var edata = $('#' + id2);
    edata.html(line);
    edata.css('white-space', 'pre-wrap');
    edata.css('font-family', 'monospace');
    src2 += line + '\n';
  }
  eraw.append("<pre>" + src2 + "</pre>");
}
var items = $('pre.code');
for (var i = 0; i < items.length; i++) {
  cv_process(items[i]);
}
</script>
    

  Protected by Copyscape Online Copyright Protection

Retrieve unique id by javascript

Retrieve unique id by javascript
This task use javascript to generate id which is unique in page.
Retrieve unique id using Math.random
var uniqid_list = new Array();
function uniqid() {
    var id = 'E' + Math.floor(Math.random() * 100000);
    while (uniqid_list.indexOf(id) >= 0) {
        id = 'E' + Math.floor(Math.random() * 100000);
    }
    uniqid_list.push(id);
    return id;
}
    

  Protected by Copyscape Online Copyright Protection

Sunday 25 December 2011

Verify table structure

Verify table structure
This task use java to check table structure and create new table if table structure is not valid.
Verify table structure
  1. Create checkTable as following
  2. Call checkTable as following
Call method
try {
    String dbfile = "C:\\Temp\\test.db";
    Class.forName("org.sqlite.JDBC");
    Connection conn = DriverManager.getConnection("jdbc:sqlite:" + dbfile);
    boolean valid = checkTable(conn, "element", new String[] { "id", "db_id", "eleType", "eleName", "eleFormula", "eleFlags", "eleParentObject", "eleModifiedBy", "eleModified", "score" });
    if (!valid) {
        Statement stat = conn.createStatement();
        stat.executeUpdate("drop table if exists element;");
        stat.executeUpdate("create table element (id char(36) not null primary key, db_id char(36) not null, eleType varchar(255) default null, eleName varchar(255) default null, eleFormula text default null, eleFlags varchar(8000) default null, eleParentObject varchar(255) default null, eleModifiedBy varchar(255) default null, eleModified varchar(50) default null, score int default 0);");
        stat.close();
    }
} catch (Exception e) {
    logger.error("", e);
}
    
checkTable method
private boolean checkTable(Connection conn, String table, String[] fields) {
    try {
        PreparedStatement prep = conn.prepareStatement("select * from " + table + " where (1=0);");
        ResultSet rs = prep.executeQuery();
        ResultSetMetaData md = rs.getMetaData();
        List<String> cols = new ArrayList<String>();
        for (int i = 1; i <= md.getColumnCount(); i++) {
            cols.add(md.getColumnName(i).toLowerCase());
        }
        rs.close();
        prep.close();

        if (fields.length > cols.size()) return false;
        for (int i = 0; i < fields.length; i++) {
            if (cols.indexOf(fields[i].toLowerCase()) < 0) {
                return false;
            }
        }
        return true;
    } catch (Exception e) {
        logger.error("", e);
        return false;
    }
}
    

  Protected by Copyscape Online Copyright Protection

Friday 23 December 2011

Redirect blog post to another web page

Redirect blog post to another web page
This task use javascript to redirect blog post to another web page.
Redirect blog post to another web page
<script>
var srcUrl = 'URL of blog post';
var tagUrl = 'URL of new web page';
var curUrl = window.location + '';
if (srcUrl != '' && tagUrl != '' && srcUrl.toLowerCase() == curUrl.toLowerCase()) {
  window.location.replace(tagUrl);
}
</script>
    

  Protected by Copyscape Online Copyright Protection

Retrieve list of documents in Lotus Notes database

Retrieve list of documents in Lotus Notes database
This task use java to retrieve list of documents in Lotus Notes database.
Filter documents with aliases
  1. Create getDocuments method as following
  2. Call getDocuments method as following
Call method
try {
    String idfile = "path to your id file";
    String password = "your password";
    // <server>!!<filepath> | <filepath>
    String filename = "path to database file";
    String form = "your form";
    String filter = "your document filter";
    NotesThread.sinitThread();
    Session s = NotesFactory.createSessionWithFullAccess();
    s.createRegistration().switchToID(idfile, password);
    Database d = openDatabase(s, filename);
    DocumentCollection dc = getDocuments(d, form, filter);
    logger.info(dc.getCount());
    d.recycle();
    s.recycle();
} catch (Exception e) {
    logger.info("", e);
}
    
getDocuments method
public DocumentCollection getDocuments(Database database, String form, String filter) throws Exception {
    if (filter.trim().length() == 0) {
        return database.search(grabFormCond(database, form));
    } else {
        return database.search(grabFormCond(database, form) + " & (" + filter + ")");
    }  
}  
  
private String grabFormCond(Database database, String form) throws Exception {
    String target = "((Form='" + form + "')";
    try {
        Vector aliases = database.getForm(form).getAliases();
        for (int i = 0; i < aliases.size(); i++) {
            target += "|(Form='" + aliases.get(i) + "')";
        }
    } catch (Exception e) {
        logger.error("", e);
    }
    return target + ")";
}
    

  Protected by Copyscape Online Copyright Protection

Thursday 22 December 2011

Open Lotus Notes database

Open Lotus Notes database
This task use java to open Lotus Notes database.
Open Lotus Notes database using DbDirectory
  1. Create openDatabase method as following
  2. Call openDatabase method as following
Call method
try {
    String idfile = "path to your id file";
    String password = "your password";
    // <server>!!<filepath> | <filepath>
    String filename = "path to database file";
    NotesThread.sinitThread();
    Session s = NotesFactory.createSessionWithFullAccess();
    s.createRegistration().switchToID(idfile, password);
    Database d = openDatabase(s, filename);
    logger.info(d.getTitle() + " | " + d.getFilePath());
    d.recycle();
    s.recycle();
} catch (Exception e) {
    logger.info("", e);
}
    
openDatabase method
private Database openDatabase(Session session, String filename) throws Exception {
    int pos = filename.indexOf("!!");
    Database tag = null;
    if (pos < 0) {
        DbDirectory dir = session.getDbDirectory("");
        tag = dir.openDatabase(filename);
    } else {  
        String server = filename.substring(0, pos);
        String path = filename.substring(pos + 2, filename.length());
        DbDirectory dir = session.getDbDirectory(server);
        tag = dir.openDatabase(path);
    }
    return tag;
}
    

  Protected by Copyscape Online Copyright Protection

Retrieve list of databases on Lotus Notes server

Retrieve list of databases on Lotus Notes server
This task use java to retrieve list of databases on Lotus Notes server.
Retrieve list of databases using DbDirectory
  1. Create listDatabase method as following
  2. Call listDatabase method as following
Call method
try {
    String idfile = "path to your id file";
    String password = "your password";
    String server = "your server, empty if local";
    NotesThread.sinitThread();
    Session s = NotesFactory.createSessionWithFullAccess();
    s.createRegistration().switchToID(idfile, password);
    List<Database> dblist = listDatabase(s, server);
    for (int i = 0; i < dblist.size(); i++) {
        Database db = dblist.get(i);
        logger.info(db.getTitle() + " | " + db.getFilePath());
        db.recycle();
    }
    s.recycle();
} catch (Exception e) {
    logger.info("", e);
}
    
listDatabase method
private List<Database> listDatabase(Session session, String server) throws Exception {
    List<Database> tag = new ArrayList<Database>();
    DbDirectory dir = session.getDbDirectory(server);
    Database db = dir.getFirstDatabase(DbDirectory.DATABASE);
    while (db != null) {
        tag.add(db);
        db = dir.getNextDatabase();
    }
    db = dir.getFirstDatabase(DbDirectory.TEMPLATE);
    while (db != null) {
        tag.add(db);
        db = dir.getNextDatabase();
    }
    return tag;
}
    

  Protected by Copyscape Online Copyright Protection

Retrieve name of current user of Lotus Notes by java

Retrieve name of current user of Lotus Notes by java
This task use java to retrieve name of current user of Lotus Notes.
Extract name of current user of Lotus Notes
  1. Create getUsername method as following
  2. Call getUsername method as following
Call method
try {
    String idfile = "path to your id file";
    String password = "your password";
    NotesThread.sinitThread();
    Session s = NotesFactory.createSessionWithFullAccess();
    s.createRegistration().switchToID(idfile, password);
    String username = getUsername(s);
    logger.info(username);
} catch (Exception e) {
    logger.info("", e);
}
    
getUsername method
private String getUsername(Session session) throws Exception {
    String noteUser = session.getUserName();
    String[] fields = noteUser.split("/");
    for (int i = 0; i < fields.length; i++) {
        int pos = fields[i].indexOf("=");
        if (i == 0) {
            noteUser = fields[i].substring(pos + 1);
        } else {
            noteUser += "/" + fields[i].substring(pos + 1);
        }
    }
    return noteUser;
}
    

  Protected by Copyscape Online Copyright Protection

Retrieve version of Lotus Notes by java

Retrieve version of Lotus Notes by java
This task use java to retrieve version of Lotus Notes.
Extract version of Lotus Notes
  1. Create getNotesVersion method as following
  2. Call getNotesVersion method as following
Call method
try {
    String idfile = "path to your id file";
    String password = "your password";
    NotesThread.sinitThread();
    Session s = NotesFactory.createSessionWithFullAccess();
    s.createRegistration().switchToID(idfile, password);
    String version = getNotesVersion(s);
    logger.info(version);
} catch (Exception e) {
    logger.info("", e);
}
    
getNotesVersion method
private String getNotesVersion(Session session) throws Exception {
    String version = session.getNotesVersion();
    int pos = version.indexOf("|");
    if (pos >= 0) {
        version = version.substring(0, pos);
    }
    pos = version.indexOf("Release ");
    if (pos >= 0) {
        version = version.substring(pos + 8);
    }
    return version;
}
    

  Protected by Copyscape Online Copyright Protection

Encrypt and decrypt string by java

Encrypt and decrypt string by java
This task use java to encrypt and decrypt string.
Encrypt and decrypt string using AES
  1. Create Crypto.java as following
  2. Call encrypt and decrypt methods as following
Call methods
try {
    String key = UUID.randomUUID().toString().replaceAll("-", "");
    String src = "Hello world!";
    String tag1 = Crypto.encrypt(src, key);
    String tag2 = Crypto.decrypt(tag1, key);
    logger.info(src);
    logger.info(tag1);
    logger.info(tag2);
} catch (Exception e) {
    logger.error("", e);
}
    
Crypto.java
public class Crypto {

    public static String encrypt(String value, String key) throws GeneralSecurityException {
        SecretKeySpec sks = new SecretKeySpec(hexStringToByteArray(key), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters());
        byte[] encrypted = cipher.doFinal(value.getBytes());
        return byteArrayToHexString(encrypted);
    }

    public static String decrypt(String message, String key) throws GeneralSecurityException {
        SecretKeySpec sks = new SecretKeySpec(hexStringToByteArray(key), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, sks);
        byte[] decrypted = cipher.doFinal(hexStringToByteArray(message));
        return new String(decrypted);
    }   
    
    private static String byteArrayToHexString(byte[] b){
        StringBuffer sb = new StringBuffer(b.length * 2);
        for (int i = 0; i < b.length; i++){
            int v = b[i] & 0xff;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString().toUpperCase();
    }
   
    private static byte[] hexStringToByteArray(String s) {
        byte[] b = new byte[s.length() / 2];
        for (int i = 0; i < b.length; i++){
            int index = i * 2;
            int v = Integer.parseInt(s.substring(index, index + 2), 16);
            b[i] = (byte)v;
        }
        return b;
    }
     
}
    

  Protected by Copyscape Online Copyright Protection

Save hash table to string

Save hash table to string
This task use java to save hash table to string.
Save hash table to string using ByteArrayOutputStream
public String writeHash(Properties properties) {
    String tag = "";
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        properties.store(baos, "");
        tag = baos.toString();
        baos.close();
    } catch (Exception e) {
        logger.error("", e);
    }
    return tag;
}
    

  Protected by Copyscape Online Copyright Protection

Load hash table from string

Load hash table from string
This task use java to load hash table from string.
Load hash table from string using ByteArrayInputStream
public void readHash(Properties properties, String src) {
    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(src.getBytes()); 
        properties.load(bais);
        bais.close();
    } catch (Exception e) {
        logger.error("", e);
    }
}
    

  Protected by Copyscape Online Copyright Protection

Load hash table from file

Load hash table from file
This task use java to load hash table from file.
Load hash table from file using FileInputStream
public void loadHash(Properties properties, String filename) {
    try {
        FileInputStream fis = new FileInputStream(filename); 
        properties.load(fis);
        fis.close();
    } catch (Exception e) {
        logger.error("", e);
    }
}
    

  Protected by Copyscape Online Copyright Protection

Save hash table to file

Save hash table to file
This task use java to save hash table to file.
Save hash table to file using FileOutputStream
public void saveHash(Properties properties, String filename) {
    try {
        FileOutputStream fos = new FileOutputStream(filename); 
        properties.store(fos, "");
        fos.close();
    } catch (Exception e) {
        logger.error("", e);
    }
}
    

  Protected by Copyscape Online Copyright Protection

Encrypt and decrypt string

Encrypt and decrypt string
This task use php to encrypt and decrypt string.
Encrypt and decrypt string using RIJNDAEL_256
  1. Create crypto.php as following
  2. Call encrypt and decrypt method as following
call methods
$key = uniqid();
$src = "Hello world!";

require_once('crypto.php');
$cp = new crypto();
$tag1 = $cp->encrypt($src, $key);
$tag2 = $cp->decrypt($tag1, $key);
print($src . "<br />" . $tag1 . "<br />" . $tag2);
    
crypto.php
<?php

class crypto {

    public function encrypt($text, $key) { 
        $src = uniqid() . $text;
        $tag = trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $src, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)))); 
        return $tag;
    } 

    public function decrypt($text, $key) { 
        $src = $text;
        $tag = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, base64_decode($src), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))); 
        $tag = substr($tag, 13);
        return $tag;
    } 

}

?>
    
PHP

  Protected by Copyscape Online Copyright Protection

Access mysql database

Access mysql database
This task use php to execute query on mysql database. If error occurs, error message is sent to specified email.
Access mysql database using utility class
  1. Create database.php as following
  2. Call query or execute method as following
call methods
$CONFIG['db']['server'] = 'localhost';
$CONFIG['db']['database'] = 'database';
$CONFIG['db']['username'] = 'username';
$CONFIG['db']['password'] = 'password';
$CONFIG['db']['prefix'] = 'prefix_';

$CONFIG['mail']['report'] = 'webmaster@host.com';
$CONFIG['mail']['sender'] = 'webmaster@host.com';

require_once('database.php');

$db = new database();
$id = 'abcdef';
$data = $db->query(sprintf("select * from %s where id = %s", $db->table('task'), $db->quote($id) ));
print_r($data);
$db->execute(sprintf("delete from %s where id = %s", $db->table('task'), $db->quote($id) ));
$db->clean();
    
database.php
<?php

class database {

    private $cfg;
    private $link;

    public function __construct() {
        global $CONFIG;
        $this->cfg = $CONFIG['db'];
        $this->link = mysql_connect($this->cfg['server'], $this->cfg['username'], $this->cfg['password']);
        if (!$this->link) {
            $this->sendError(mysql_error());
        }
        if ($this->link) {
            if (!mysql_select_db($this->cfg['database'], $this->link)) {
                $this->sendError(mysql_error());
                $this->clean();
            }
        }
    }

    public function clean() {
        mysql_close($this->link);
        $this->link = null;
    }

    public function quote($src) {
        return "'" . mysql_real_escape_string($src) . "'";
    }

    public function table($src) {
        return $this->cfg['prefix'] . $src;
    }

    public function query($sql) {
        $data = array();
        if (!$this->link) return $data;
        $result = mysql_query($sql, $this->link);
        if ($result) {
            while ($row = mysql_fetch_assoc($result)) {
                $data[] = $row;
            }
        } else {
            $this->sendError(mysql_error());
        }
        return $data;
    }

    public function execute($sql) {
        if (!$this->link) return false;
        $result = mysql_query($sql, $this->link);
        if (!$result) {
            $msg = mysql_error();
            $this->sendError($msg);
            return $msg;
        } else {
            return true;
        }
    }

    public function sendError($message) {
        global $CONFIG;
        $from = $CONFIG['mail']['sender'];
        $to = $CONFIG['mail']['report'];
        $header = "From: $from\r\nReply-To: $from\r\n";
        $subject = "Database error!";
        mail($to, $subject, $message, $header);
    }

}

?>
    
PHP

  Protected by Copyscape Online Copyright Protection

Task tagged by [PHP]

  1. Use one host for multiple domain
  2. Access mysql database
  3. Encrypt and decrypt string

Use one host for multiple domain

Use one host for multiple domain
This task use php to run multiple domain on one host
Run multiple domain by parking domain
  1. Park domain
  2. Create .htaccess as following
  3. Create index.php file as following
.htaccess
RewriteEngine On
RewriteRule ^([a-z/A-Z/0-9/\-/\//+/\&/\=]*)$ /index.php?$1
    
index.php
<?php

$host = $_SERVER['HTTP_HOST'];

if ($host == 'host1.com') {
    require_once("host1.com/index.php");
} else if ($host == 'host2.com') {
    require_once("host2.com/index.php");
} else {
    header("Location: http://host3.com");
}

?>
    
PHP

  Protected by Copyscape Online Copyright Protection

Retrieve list of libraries on SharePoint site

Retrieve list of libraries on SharePoint site
This task use Java WSDL for SharePoint to retrieve list of libraries on SharePoint site.
Retrieve list of libraries on SharePoint site using Lists webservice
private List<String> getLibraries(String site, String username, String password) {
    List<String> tag = new ArrayList<String>();
    try {
        ListsSoapStub stub = SharePointWSDL.newLists(new URL(site + "/_vti_bin/Lists.asmx"), new ListsLocator());
        stub.setUsername(username);
        stub.setPassword(password);
        com.microsoft.schemas.sharepoint.soap.GetListCollectionResponseGetListCollectionResult lcr = stub.getListCollection();
        if (lcr.get_any().length > 0) {
            NodeList children = lcr.get_any()[0].getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                Node node = children.item(i);
                String baseType = node.getAttributes().getNamedItem("BaseType").getNodeValue();
                if (!"1".equals(baseType)) continue;
                String template = node.getAttributes().getNamedItem("ServerTemplate").getNodeValue();
                String title = node.getAttributes().getNamedItem("Title").getNodeValue();
                if ("|101|115|109|".indexOf("|" + template + "|") < 0) continue;
                tag.add(title);
            }
        }
    } catch (Exception e) {
        logger.error("", e);
    }
    return tag;
}
    

  Protected by Copyscape Online Copyright Protection

Task tagged by [SharePoint]

  1. Upload file to SharePoint site
  2. Retrieve list of libraries on SharePoint site

Upload file to SharePoint site

Upload file to SharePoint site
This task use Java WSDL for SharePoint to upload file to SharePoint site.
Upload file to SharePoint site using Copy webservice
Call uploadFile. site argument contains domain name instead of IP.
private String uploadFile(String site, String username, String password, String library, String filename) {
    String tag = "";
    try {
        CopySoapStub stub = SharePointWSDL.newCopy(new URL(site + "/_vti_bin/Copy.asmx"), new CopyLocator());
        stub.setUsername(username);
        stub.setPassword(password);

        String name = (new File(filename)).getName();
        String tagPath = site + "/" + library + "/" + name; 
        FieldInformation[] fis = new FieldInformation[1];
        UnsignedIntHolder uih = new UnsignedIntHolder(new UnsignedInt());
        CopyResultCollectionHolder crch = new CopyResultCollectionHolder(new CopyResult[] { new CopyResult() });

        fis[0] = new FieldInformation();
        fis[0].setInternalName("Title");
        fis[0].setDisplayName(name);
        fis[0].setType(FieldType.Text);
        fis[0].setValue(name);
       
        stub.copyIntoItems(tagPath, new String[] { tagPath }, fis, readFile(filename), uih, crch);
        boolean success = true;
        for (int i = 0; i < crch.value.length; i++) {
            if (CopyErrorCode._Success.equals(crch.value[i].getErrorCode().getValue())) continue;
            logger.error(crch.value[i].getErrorCode().getValue() + " : " + crch.value[i].getErrorMessage());
            logger.info(crch.value[i].getDestinationUrl());
            success = false;
        }
        if (success) {
            tag = tagPath;
        }
    } catch (Exception e) {
        logger.error("", e);
    }
    return tag;
}
    
private byte[] readFile(String filename) {
    File file = new File(filename);
    byte[] tag = new byte[0];
    try {
        tag = new byte[(int)file.length()];
        InputStream is = new FileInputStream(file);     
        int offset = 0;
        int numRead = 0;
        while (offset < tag.length && (numRead = is.read(tag, offset, tag.length - offset)) >= 0) {
            offset += numRead;
        }     
    } catch (Exception e) {
        logger.error("", e);
    }
    return tag;
}
    

 

All tasks

  1. Check Lotus Notes connection by java
  2. Check Salesforce connection by java
  3. Execute command line process from java with timeout
  4. Execute thread from java with timeout
  5. Retrieve CPU brand by C and Win32 API
  6. Call JSONP with jQuery
  7. Upload file to SharePoint site
  8. Retrieve list of libraries on SharePoint site
  9. Use one host for multiple domain
  10. Access mysql database
  11. Encrypt and decrypt string
  12. Save hash table to file
  13. Load hash table from file
  14. Load hash table from string
  15. Save hash table to string
  16. Encrypt and decrypt string by java
  17. Retrieve version of Lotus Notes by java
  18. Retrieve name of current user of Lotus Notes by java
  19. Retrieve list of databases on Lotus Notes server
  20. Open Lotus Notes database
  21. Retrieve list of documents in Lotus Notes database
  22. Redirect blog post to another web page
  23. Verify table structure
  24. Retrieve unique id by javascript
  25. Format code with line number
  26. Initialize logger by java
  27. Retrieve list of Lotus Notes forms
  28. Install and run Jetty 8.0.4
  29. Configure log4j for Jetty 8.0.4
  30. Parse simple math expression
  31. Extract summary of web page
  32. Grab jobs from vWorker
  33. Grab jobs from Freelancer
  34. Retrieve Salesforce server instance
  35. Add post and comment to Chatter
  36. Grab jobs from oDesk
  37. Grab jobs from Stack Overflow Careers
  38. Extract Lotus Notes database icon
  39. Run javascript in sandbox
  40. Create javascript sandbox with jsoup support
  41. Grab vBulletin pages in logged-in mode
  42. Add JSON support to javascript sandbox
  43. Grab google search results
  44. Grab categories from Amazon aStores
  45. Grab products from Amazon aStores
  46. Grab categories from BestBuy
  47. Grab products from BestBuy
  48. Grab categories from Walmart
  49. Grab products from Walmart
  50. Grab categories from Newegg
  51. Grab products from Newegg
  52. Add Lucene support to javascript sandbox
  53. Add MySQL support to javascript sandbox
  54. Grab categories from HP Shopping
  55. Grab products from HP Shopping
  56. Grab video from YouTube
  57. Grab video from DailyMotion
  58. Grab book/journal from ScienceDirect
  59. Grab article from ScienceDirect
  60. Grab search results from Google
  61. Grab search results from Bing
  62. Grab search results from Yahoo

Task tagged by [JSONP]

  1. Call JSONP with jQuery

Task tagged by [jQuery]

  1. Call JSONP with jQuery

Task tagged by [JavaScript]

  1. Call JSONP with jQuery
  2. Redirect blog post to another web page
  3. Retrieve unique id by javascript
  4. Format code with line number
  5. Run javascript in sandbox
  6. Create javascript sandbox with jsoup support
  7. Grab vBulletin pages in logged-in mode
  8. Add JSON support to javascript sandbox
  9. Grab google search results
  10. Grab categories from Amazon aStores
  11. Grab products from Amazon aStores
  12. Grab categories from BestBuy
  13. Grab products from BestBuy
  14. Grab categories from Walmart
  15. Grab products from Walmart
  16. Grab categories from Newegg
  17. Grab products from Newegg
  18. Add Lucene support to javascript sandbox
  19. Add MySQL support to javascript sandbox
  20. Grab categories from HP Shopping
  21. Grab products from HP Shopping
  22. Grab video from YouTube
  23. Grab video from DailyMotion
  24. Grab book/journal from ScienceDirect
  25. Grab article from ScienceDirect
  26. Grab search results from Google
  27. Grab search results from Bing
  28. Grab search results from Yahoo

Call JSONP with jQuery

Call JSONP with jQuery
This task use jQuery to JSONP page.
Call JSONP using append method
Fill code in response method. Call request method with following arguments:
callbackVar: name of GET variable containing JSONP callback, eg. api.php?jsonp=response
bufferID: id of empty div tag which is used for temporarily adding script tag
args: arguments is passed to callback function
    

function jsonp() {

    this.request = function(url, args, callbackVar, bufferID) {
        var super = this;
        var callback = 'jsonp_response_' + Math.floor(Math.random() * 100000);
        window[callback] = function(data) {
            super.response(args, data);
            delete window[callback];
        }
        var params = { callbackVar : callback };
        var buffer = $('#' + bufferID);
        buffer.append("<script src='" + url + '&' + jQuery.param(params) + "'></script>");
    }

    this.response = function(args, data) {
        // Tasks go here
    }

}
    

  Protected by Copyscape Online Copyright Protection

All tags

Java C/C++ Lotus Notes Salesforce
JavaScript jQuery JSONP SharePoint
PHP Jetty log4j jsoup
Chatter SWT Lucene MySQL

Wednesday 21 December 2011

Task tagged by [Lotus Notes]

  1. Check Lotus Notes connection by java
  2. Retrieve version of Lotus Notes by java
  3. Retrieve name of current user of Lotus Notes by java
  4. Retrieve list of databases on Lotus Notes server
  5. Open Lotus Notes database
  6. Retrieve list of documents in Lotus Notes database
  7. Retrieve list of Lotus Notes forms
  8. Extract Lotus Notes database icon

Task tagged by [Salesforce]

  1. Check Salesforce connection by java
  2. Retrieve Salesforce server instance
  3. Add post and comment to Chatter

Task tagged by [C/C++]

  1. Retrieve CPU brand by C and Win32 API

Task tagged by [java]

  1. Check Lotus Notes connection by java
  2. Check Salesforce connection by java
  3. Execute command line process from java with timeout
  4. Execute thread from java with timeout
  5. Upload file to SharePoint site
  6. Retrieve list of libraries on SharePoint site
  7. Save hash table to file
  8. Load hash table from file
  9. Load hash table from string
  10. Save hash table to string
  11. Encrypt and decrypt string by java
  12. Retrieve version of Lotus Notes by java
  13. Retrieve name of current user of Lotus Notes by java
  14. Retrieve list of databases on Lotus Notes server
  15. Open Lotus Notes database
  16. Retrieve list of documents in Lotus Notes database
  17. Verify table structure
  18. Initialize logger by java
  19. Retrieve list of Lotus Notes forms
  20. Parse simple math expression
  21. Extract summary of web page
  22. Grab jobs from vWorker
  23. Grab jobs from Freelancer
  24. Retrieve Salesforce server instance
  25. Add post and comment to Chatter
  26. Grab jobs from oDesk
  27. Grab jobs from Stack Overflow Careers
  28. Extract Lotus Notes database icon
  29. Run javascript in sandbox
  30. Create javascript sandbox with jsoup support
  31. Grab vBulletin pages in logged-in mode
  32. Add JSON support to javascript sandbox
  33. Grab google search results
  34. Grab categories from Amazon aStores
  35. Grab products from Amazon aStores
  36. Grab categories from BestBuy
  37. Grab products from BestBuy
  38. Grab categories from Walmart
  39. Grab products from Walmart
  40. Grab categories from Newegg
  41. Grab products from Newegg
  42. Add Lucene support to javascript sandbox
  43. Add MySQL support to javascript sandbox
  44. Grab categories from HP Shopping
  45. Grab products from HP Shopping
  46. Grab video from YouTube
  47. Grab video from DailyMotion
  48. Grab book/journal from ScienceDirect
  49. Grab article from ScienceDirect
  50. Grab search results from Google
  51. Grab search results from Bing
  52. Grab search results from Yahoo