Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 21-30 of 36 total

find out the current url / uri in *.rhtml file

// find out the current url / uri in *.rhtml file
// is quite simple with the request object

<% page = request.request_uri %>
page: <%= page %>

// but then different urls mean the same page
// (../admin = ../admin/ = ../admin/index = ..admin/index/)
// and maybe the id is unwanted too (../admin/show/8)
// so below is an alternative with control on which parameter is used

<% page = "/" + request.path_parameters['controller'] + "/" + request.path_parameters['action'] %>
page: <%= page %>

Python - getFile Internet

// Scaricare un file dalla rete

package get.file.example;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

public class GetFileExample
{
	public GetFileExample()
	{
		try
		{
			byte[] bite = new byte[2048];
			int read;
			URL url = new URL("http://switch.dl.sourceforge.net/sourceforge/pys60miniapps/FlickrS60_src_v0.1b.tar.bz2");
			
			BufferedInputStream bis = new BufferedInputStream(url.openStream());
			FileOutputStream fos = new FileOutputStream("/tmp/file.tar.bz2");
			
			while((read = bis.read(bite))>0)
			{
				fos.write(bite, 0, read);
				System.out.println("--");
			}
			
			fos.close();
			bis.close();
			
			System.out.println("FINE");
			
		}
		catch(MalformedURLException e)
		{
			e.printStackTrace();
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args)
	{
		new GetFileExample();
	}
}

check url with php

// description of your code here

function http_test_existance($url) {
 return (($fp = @fopen($url, 'r')) === false) ? false : @fclose($fp);
}

replace file extension with apache rewrite

// in this example *.html is replaced by *.php
// its a redirect [R] and it is is permanent (code is 301)

RewriteEngine On
RewriteBase   /the_directory

RewriteRule  ^(.*).html$ $1.php [R=301]

URL/URI Validations in Rails

Here is a quick/basic URI validation library for your Rails app:

require 'net/http'

# Original credits: http://blog.inquirylabs.com/2006/04/13/simple-uri-validation/
# HTTP Codes: http://www.ruby-doc.org/stdlib/libdoc/net/http/rdoc/classes/Net/HTTPResponse.html

class ActiveRecord::Base
  def self.validates_uri_existence_of(*attr_names)
    configuration = { :message => "is not valid or not responding", :on => :save, :with => nil }
    configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)
    
    raise(ArgumentError, "A regular expression must be supplied as the :with option of the configuration hash") unless configuration[:with].is_a?(Regexp)
    
    validates_each(attr_names, configuration) do |r, a, v|
        if v.to_s =~ configuration[:with] # check RegExp
              begin # check header response
                  case Net::HTTP.get_response(URI.parse(v))
                    when Net::HTTPSuccess then true
                    else r.errors.add(a, configuration[:message]) and false
                  end 
              rescue # Recover on DNS failures.. 
                  r.errors.add(a, configuration[:message]) and false
              end
        else
          r.errors.add(a, configuration[:message]) and false
        end 
    end
  end
end


Save the code above into a file in your 'lib' directory. ex: validates_uri_existence_of.rb. Include the file in your environment.rb (ex: require 'validates_uri_existence_of').

And now you can use the validator in any model by calling:
validates_uri_existence_of :url, :with =>
        /(^$)|(^(http|https)://[a-z0-9] ([-.]{1}[a-z0-9] )*.[a-z]{2,5}(([0-9]{1,5})?/.*)?$)/ix


Above code validates the URI/URL against a regular expression first, and then does a HEAD query to confirm that the page is alive (HTTPSuccess code is returned). You could easily modify the code to extend the functionality as you wish.

More info in this post.

rewrite rules

// if cms has cryptic urls
// in apache url-rewriting with .htaccess can help

RewriteRule cms/fest$ cms/index.php?option=content&task=view&id=176&Itemid=202 [NC]


// [NC] = not case-sensitive

Load a Web page in Ruby and print information

Found at http://www.juretta.com/log/2006/08/13/ruby_net_http_and_open-uri/

require 'open-uri'
require 'pp'

open('http://www.juretta.com/') do |f|
  # hash with meta information
  pp  f.meta
   
  # 
  pp "Content-Type: " + f.content_type
  pp "last modified" + f.last_modified.to_s
  
  no = 1
  # print the first three lines
  f.each do |line|
    print "#{no}: #{line}"
    no += 1
    break if no > 4
  end
end

Grab HTML From Sites and Echo Results

Grabs specified tags from any url on the net and then echos each of the results on a seperate line, you then have the option to remove the tags from the echoed results.

<?php

$config['url']       = "http://www.business-tycoon.com"; // url of html to grab
$config['start_tag'] = "<b>"; // where you want to start grabbing
$config['end_tag']   = "</b>"; // where you want to stop grabbing
$config['show_tags'] = 0; // do you want the tags to be shown when you show the html? 1 = yes, 0 = no

class grabber
{
	var $error = '';
	var $html  = '';
	
	function grabhtml( $url, $start, $end )
	{
		$file = file_get_contents( $url );
		
		if( $file )
		{
			if( preg_match_all( "#$start(.*?)$end#s", $file, $match ) )
			{				
				$this->html = $match;
			}
			else
			{
				$this->error = "Tags cannot be found.";
			}
		}
		else
		{
			$this->error = "Site cannot be found!";
		}
	}
	
	function strip( $html, $show, $start, $end )
	{
		if( !$show )
		{
			$html = str_replace( $start, "", $html );
			$html = str_replace( $end, "", $html );
			
			return $html;
		}
		else
		{
			return $html;
		}
	}
}

$grab = new grabber;
$grab->grabhtml( $config['url'], $config['start_tag'], $config['end_tag'] );

echo $grab->error;

foreach( $grab->html[0] as $html )
{
	echo htmlspecialchars( $grab->strip( $html, $config['show_tags'], $config['start_tag'], $config['end_tag'] ) ) . "<br>";
}

?>

Validate URIs by Pinging the Server

require 'open-uri'

class ActiveRecord::Base
  def self.validates_uri_existence_of(*attr_names)
    configuration = { :message => "is not a valid web address" }
    configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)
    validates_each attr_names do |m, a, v|
      begin
        # Try to open the URI
        open v
      rescue
        # Report the error if it throws an exception
        m.errors.add(a, configuration[:message])
      end
    end
  end
end


Details on my blog.

Thai election ID checking

The online service here aims to help people
check where they are to vote. However, it can be
used as ID certification as well.
# nnnn is the id to be checked
http://www.dopa.go.th/cgi-bin/inqelect.sh?pid=nnnn

Here I make it into a function call.
import urllib, re
def getname(id):
  url = 'http://www.dopa.go.th/cgi-bin/inqelect.sh?pid=' + str(id)
  src = urllib.urlopen(url).read()
  pat = '<H3> *(.*?) *<'
  name = re.findall(pat, src)[0]  # don't use other info
  return name

print getname(5100900050063)  # show a name (one of my relatives)
« Newer Snippets
Older Snippets »
Showing 21-30 of 36 total