Showing posts with label URL. Show all posts
Showing posts with label URL. Show all posts

Saturday, April 6, 2013

Yii customizing the display of url parameters

Add the following rule to your main.php rules array:
'product/<id:[A-Z0-9]+>'=>'site/product',
 
 
You can then get the value by:
$id = Yii::app()->getRequest()->getQuery('id');

$this->createUrl('product',array('id'=>100));
 
 

<?php $this->widget('zii.widgets.CMenu',array(
	'items'=>array(
		array('label'=>'Product 10', 'url'=>array('/product', 'id' => 20 )),
		array('label'=>'About', 'url'=>array('/site/page', 'view'=>'about')),
		array('label'=>'Contact', 'url'=>array('/site/contact')),
		array('label'=>'Login', 'url'=>array('/site/login'), 'visible'=>Yii::app()->user->isGuest),
		array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/site/logout'), 'visible'=>!Yii::app()->user->isGuest)
	),
)); ?> 
 
 
echo $this->createUrl('post/read',array('id'=>$id))."<BR>";
echo $this->createUrl('post/read',array('id'=>$id, 'title' => "New post title")); 

'post/<id:\d+>/<title>'=>'post/read',
'post/<id:\d+>'=>'post/read' 

Remove index.php from url yii

There is one more thing that we can do to further clean our URLs, i.e., hiding the entry script index.php in the URL. This requires us to configure the Web server as well as the urlManager application component.

We first need to configure the Web server so that a URL without the entry script can still be handled by the entry script. For Apache HTTP server, this can be done by turning on the URL rewriting engine and specifying some rewriting rules. We can create the file /wwwroot/blog/.htaccess with the following content. Note that the same content can also be put in the Apache configuration file within the Directory element for /wwwroot/blog.
RewriteEngine on

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# otherwise forward it to index.php
RewriteRule . index.php
We then configure the showScriptName property of the urlManager component to be false.
Now if we call $this->createUrl('post/read',array('id'=>100)), we would obtain the URL /post/100. More importantly, this URL can be properly recognized by our Web application.

7. Faking URL Suffix

We may also add some suffix to our URLs. For example, we can have /post/100.html instead of /post/100. This makes it look more like a URL to a static Web page. To do so, simply configure the urlManager component by setting its urlSuffix property to the suffix you like.

Thanks for guidance.

One more thing.
How can change static pages urls. E.g; following is url for About page.

http://localhost/main/yii/wf/site/page?view=about

How can I change it to more friendly url by removing '?' sign from url.

ANS:
Add the following line at first of components->urlManager->rules
'site/page/<view:\w+>'=>'site/page'




Thanks in advance

<?php
// uncomment the following to define a path alias
// Yii::setPathOfAlias('local','path/to/local-folder');
// This is the main Web application configuration. Any writable
// CWebApplication properties can be configured here.
return array(
        'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
        'name'=>'My Web Application',

        // preloading 'log' component
        'preload'=>array('log'),

        // autoloading model and component classes
        'import'=>array(
                'application.models.*',
                'application.components.*',
        ),

        // application components
        'components'=>array(
                'user'=>array(
                        // enable cookie-based authentication
                        'allowAutoLogin'=>true,
                ),
                // uncomment the following to enable URLs in path-format
                
                'urlManager'=>array(
                        'urlFormat'=>'path',
                        'showScriptName' => false,
                        'rules'=>array( 
                                'site/page/<view:\w+>'=>'site/page',
                                '<controller:\w+>/<id:\d+>'=>'<controller>/view',
                                '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
                                '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
                        ),
                ),
                
                'db'=>array(
                        'connectionString' => 'sqlite:protected/data/testdrive.db',
                ),
                // uncomment the following to use a MySQL database
                /*
                'db'=>array(
                        'connectionString' => 'mysql:host=localhost;dbname=testdrive',
                        'emulatePrepare' => true,
                        'username' => 'root',
                        'password' => '',
                        'charset' => 'utf8',
                ),
                */
                'errorHandler'=>array(
                        // use 'site/error' action to display errors
            'errorAction'=>'site/error',
        ),
                'log'=>array(
                        'class'=>'CLogRouter',
                        'routes'=>array(
                                array(
                                        'class'=>'CFileLogRoute',
                                        'levels'=>'error, warning',
                                ),
                                // uncomment the following to show log messages on web pages
                                /*
                                array(
                                        'class'=>'CWebLogRoute',
                                ),
                                */
                        ),
                ),
        ),

        // application-level parameters that can be accessed
        // using Yii::app()->params['paramName']
        'params'=>array(
                // this is used in contact page
                'adminEmail'=>'webmaster@example.com',
        ),
);

Sunday, February 24, 2013

validating fqdn url email hostname using java regular expression

Using java Pattern class to validate the FQDN, URL, E-Mail address hostname


import java.io.*;
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
 

public class Validator 
{
    private static final Pattern emailPattern = Pattern.compile("^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$", Pattern.CASE_INSENSITIVE);


    private static final Pattern fqdnPattern = Pattern.compile("(?=^.{1,254}$)(^(?:(?!\\d+\\.|-)[a-zA-Z0-9_\\-]{1,63}(?<!-)\\.?)+(?:[a-zA-Z]{2,})$)", Pattern.CASE_INSENSITIVE);

     private static final Pattern hostPattern = Pattern.compile("^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\\-]*[A-Za-z0-9])$", Pattern.CASE_INSENSITIVE);

    private static final Pattern urlPattern = Pattern.compile("[^(http\\:\\/\\/[a-zA-Z0-9_\\-]+(?:\\.[a-zA-Z0-9_\\-]+)*\\.[a-zA-Z]{2,4}(?:\\/[a-zA-Z0-9_]+)*(?:\\/[a-zA-Z0-9_]+\\.[a-zA-Z]{2,4}(?:\\?[a-zA-Z0-9_]+\\=[a-zA-Z0-9_]+)?)?(?:\\&[a-zA-Z0-9_]+\\=[a-zA-Z0-9_]+)*)$]", Pattern.CASE_INSENSITIVE);


    public static boolean isInteger(String intVal)
    {
        try {
            int i = new Integer(intVal);
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    public static boolean isBoolean(String boolVal)
    {
        try {
            boolean b = new Boolean(boolVal);
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    public static boolean isFloat(String floatVal)
    {
        try {
            float f = new Float(floatVal);
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    public static boolean isLong(String logVal)
    {
        try {
            long l = new Long(logVal);
            return true;
        } catch(Exception e) {
        }
        return false;
    }

    public static boolean isFQDN(String fqdnVal)
    {
        try {
                   Matcher matcher = fqdnPattern.matcher(fqdnVal); 
                return matcher.matches(); 
        } catch (Exception e){
        }
        return false;


    }

    public static boolean isURL(String url)
    {
        try {
                   Matcher matcher = urlPattern.matcher(url); 
                return matcher.matches(); 
        } catch (Exception e){
        }
        return false;

    }

    public static boolean isEmailAddr(String emailAddr)
    {
        try {
                   Matcher matcher = emailPattern.matcher(emailAddr); 
                return matcher.matches(); 
        } catch (Exception e){
        }
        return false;
    }

    public static boolean isHost (String hostname)
    {
        try {
                   Matcher matcher = hostPattern.matcher(hostname); 
                return matcher.matches(); 
        } catch (Exception e){
        }
        return false;
    }

    public static void main(String args[])
    {
        try {
            String action = args[0];
            String input = args[1];
            boolean result = false;
            if (action.equals("email")) {
                result = isEmailAddr(input);   
            } else if (action.equals("host")) {
                result = isHost(input);
            } else if(action.equals("url")) {
                result = isURL(input);
            } else if(action.equals("fqdn")) {
                result = isFQDN(input);
            }
            System.out.println("RESULT : " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Wednesday, December 5, 2012

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

Tuesday, December 4, 2012

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