Today I face a problem ,I try to get my URLs to contain double quotes (") and other special character.
But these characters are encoded and send through the net.So I go in deatil about URL encoding.
URL encoding, is a mechanism for encoding information in a Uniform Resource Identifier (URI)
under certain circumstances.The characters allowed in a URI are either reserved or unreserved (or a
percent character as part of a percent-encoding). Reserved characters are those characters that sometimes
have special meaning. For example, forward slash characters are used to separate different parts of a URL
(or more generally, a URI). Unreserved characters have no such meanings. Using percent-encoding,
reserved characters are represented using special character sequences.
URL Encoded Characters
backspace %08
tab %09
linefeed %0A
creturn %0D
space %20
! %21
" %22
# %23
$ %24
% %25
& %26
' %27
( %28
) %29
* %2A
+ %2B
, %2C
- %2D
. %2E
/ %2F
0 %30
1 %31
2 %32
3 %33
4 %34
5 %35
6 %36
7 %37
8 %38
9 %39
: %3A
; %3B
< %3C
= %3D
> %3E
? %3F
@ %40
A %41
B %42
C %43
D %44
E %45
F %46
G %47
H %48
I %49
J %4A
K %4B
L %4C
M %4D
N %4E
O %4F
P %50
Q %51
R %52
S %53
T %54
U %55
V %56
W %57
X %58
Y %59
Z %5A
[ %5B
\ %5C
] %5D
^ %5E
_ %5F
` %60
a %61
b %62
c %63
d %64
e %65
f %66
g %67
h %68
i %69
j %6A
k %6B
l %6C
m %6D
n %6E
o %6F
p %70
q %71
r %72
s %73
t %74
u %75
v %76
w %77
x %78
y %79
z %7A
{ %7B
| %7C
} %7D
~ %7E
http://en.wikipedia.org/wiki/Percent-encoding
The PUT method the more efficient way of uploading files to a server. This is because in a POST upload the files needs to be combined together into a multipart message and this message has to be decoded at the server. In contrast, the PUT method allows you to simply write the contents of the file to the socket connection that is established with the server.
Disadvantages of POST file upload
When using the POST method, all the files are combined together into a single multipart/form-data type object. This MIME message when transferred to the server has to be decoded by the server side handler. The decoding process may consume significant amounts of memory and CPU cycles for very large files.
Disadvantages of PUT file upload
The disadvantage with the PUT method is that if you are on a shared hosting environment it may not be available to you.
Http Put definition from w3school
The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI. If a new resource is created, the origin server MUST inform the user agent via the 201 (Created) response. If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request. If the resource could not be created or modified with the Request-URI, an appropriate error response SHOULD be given that reflects the nature of the problem. The recipient of the entity MUST NOT ignore any Content-* (e.g. Content-Range) headers that it does not understand or implement and MUST return a 501 (Not Implemented) response in such cases.
If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those entries SHOULD be treated as stale. Responses to this method are not cacheable.
The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request — the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI,
it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.
A single resource MAY be identified by many different URIs. For example, an article might have a URI for identifying “the current version” which is separate from the URI identifying each particular version. In this case, a PUT request on a general URI might result in several other URIs being defined by the origin server.
HTTP/1.1 does not define how a PUT method affects the state of an origin server.
PUT requests MUST obey the message transmission requirements set out in section 8.2.
Unless otherwise specified for a particular entity-header, the entity-headers in the PUT request SHOULD be applied to the resource created or modified by the PUT.
Resemble Upload using PUT
http://wiki.restlet.org/developers/172-restlet/154-restlet.html
http://php.net/manual/en/features.file-upload.put-method.php
http://geekswithblogs.net/narent/archive/2008/01/04/118224.aspx
http://stackoverflow.com/questions/812711/how-do-you-do-an-http-put
From PHP manual:-
require() and include() are identical in every way except how they handle failure. include() produces a Warning while require() results in a Fatal Error. In other words, don’t hesitate to use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless. Be sure to have an appropriate include_path setting as well.
So that means, if you want to ensure that file1.php must be read before execute anything else, then you should use require.
If you just want to load a ‘not that important’ template header then you can use include function.
URL rewriting can be one of the best and quickest ways to improve the usability and search friendliness of your site. The Apache server’s mod_rewrite module gives you the ability to transparently redirect one URL to another, without the user’s knowledge. This opens up all sorts of possibilities, from simply redirecting old URLs to new addresses, to cleaning up the ‘dirty’ URLs coming from a poor publishing system — giving you URLs that are friendlier to both readers and search engines.
http://www.example.com/catalog.php?category=laptop&prodId=14
There are a number of problems with an URL of this kind:
Exposes the underlying technology of the website (in this case PHP). This can give potential hackers clues as to what type of data they should send along with the query string to perform a ‘front-door’ attack on the site. Information like this shouldn’t be given away if you can help it.
The URL is littered with awkward punctuation, like the question mark and ampersand. Those & characters, in particular, are problematic because if another webmaster links to this page using that URL, the un-escaped ampersands will mess up their XHTML conformance. They will have to laboriously replace all the ampersands with & character entities, which are often forgotten.
Static URLs are known to be better than Dynamic URLs because of a number of reasons
1. Static URLs typically Rank better in Search Engines.
2. Search Engines are known to index the content of dynamic pages a lot slower compared to static pages.
3. Static URLs are always more friendlier looking to the End Users.
What are .htaccess files?
They are invisible plain text files where one can store server directives. Server directives are anything you might put in an Apache config file (httpd.conf) or even a php.ini, but unlike those “master” directive files, these .htaccess directives apply only to the folder in which the .htaccess file resides, and all the folders inside. The .htaccess file is a configuration file for the server.
Comment:- everything following a hash symbol in an .htaccess file is ignored as a comment
Beginning..
Options +FollowSymLinks
RewriteEngine On
FollowSymLinks is a security requirement of the rewrite engine. It is required to be on, and in most cases will already be set in the httpd.conf. If you know you do not need this line, you can leave it out. Otherwise, it does no harm to restate it. RewriteEngine On is fairly self-explanatory. We are telling Apache to activate the rewrite engine because we want to use it. You can now setup your rewrites.
Regular Expressions
A complete guide to regular expressions is rather beyond the scope of this article. However, important points to remember are that the entire pattern is treated as a regular expression, so always be careful of characters that are “special” characters in regular expressions such as .(DOT stands for any character).
- . (any character)
- * (zero of more of the preceding)
- + (one or more of the preceding)
- {} (minimum to maximum quantifier)
- ? (ungreedy modifier)
- ! (at start of string means “negative pattern”)
- ^ (start of string, or “negative” if at the start of a range)
- $ (end of string)
- [] (match any of contents)
- - (range if used between square brackets)
- () (group, backreferenced group)
- | (alternative, or)
- \ (the escape character itself)
Flags
Flags are added to the end of a rewrite rule to tell Apache how to interpret and handle the rule. They are comma-separated, and contained in square brackets. Here’s a list of the flags, with their meanings
- C (chained with next rule)
- CO=cookie (set specified cookie)
- E=var:value (set environment variable var to value)
- F (forbidden – sends a 403 header to the user)
- G (gone – no longer exists)
- H=handler (set handler)
- L (last – stop processing rules)
- N (next – continue processing rules)
- NC (case insensitive)
- NE (do not escape special URL characters in output)
- NS (ignore this rule if the request is a subrequest)
- P (proxy – i.e., apache should grab the remote content specified in the substitution section and return it)
- PT (pass through – use when processing URLs with additional handlers, e.g., mod_alias)
- R (temporary redirect to new URL)
- R=301 (permanent redirect to new URL)
- QSA (append query string from request to substituted URL)
- S=x (skip next x rules)
- T=mime-type (force specified mime type)
Internal Redirect .php files to .html files
Redirects all files that end in .html to be served from filename.php so it looks like all your pages are .html but really they are .php
RewriteRule ^(.*)\.html$ $1.php [R=301,L]
Rewrite underscores to hyphens for SEO URL
Converts all underscores “_” in urls to hyphens “-” for SEO benefits… See the full article for more info.
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule !\.(html|php)$ – [S=4]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4-$5 [E=uscor:Yes]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4 [E=uscor:Yes]
RewriteRule ^([^_]*)_([^_]*)_(.*)$ $1-$2-$3 [E=uscor:Yes]
RewriteRule ^([^_]*)_(.*)$ $1-$2 [E=uscor:Yes]
RewriteCond %{ENV:uscor} ^Yes$
RewriteRule (.*) http://d.com/$1 [R=301,L]
Only allow GET and PUT Request Methods
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_METHOD} !^(GET|PUT)
RewriteRule .* – [F]
Mod_rewrite is built on top of the Perl Compatible Regular Expression (PCRE) vocabulary.
Redirect Old domain to New domain (htaccess redirect)
Create a .htaccess file with the below code, it will ensure that all your directories and pages of your old domain will get correctly redirected to your new domain.
The .htaccess file needs to be placed in the root directory of your old website (i.e the same directory where your index file is placed)
Options +FollowSymLinks
RewriteEngine on
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]
In addition to the redirect I would suggest that you contact every backlinking site to modify their backlink to point to your new website.
Note* This .htaccess method of redirection works ONLY on Linux servers having the Apache Mod-Rewrite moduled enabled.
Moved DocumentRoot
Usually the DocumentRoot of the webserver directly relates to the URL “/“. But often this data is not really of top-level priority, it is perhaps just one entity of a lot of data pools. For instance at our Intranet sites there are /e/www/ (the homepage for WWW), /e/sww/ (the homepage for the Intranet) etc. Now because the data of the DocumentRoot stays at /e/www/ we had to make sure that all inlined images and other stuff inside this data pool work for subsequent requests.
We redirect the URL / to /e/www/:
RewriteEngine on RewriteRule ^/$ /e/www/ [R]
Note that this can also be handled using the RedirectMatch directive:
RedirectMatch ^/$ http://example.com/e/www/
Rewriting product.php?id=12 to product-12.html
It is a simple redirection in which .php extension is hidden from the browser’s address bar and dynamic url (containing “?” character) is converted into a static URL.
RewriteEngine on
RewriteRule ^product-([0-9]+)\.html$ product.php?id=$1
Rewriting product.php?id=12 to product/ipod-nano/12.html
SEO expert always suggest to display the main keyword in the URL. In the following URL rewriting technique you can display the name of the product in URL.
RewriteEngine on
RewriteRule ^product/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ product.php?id=$2
Redirecting non www URL to www URL
If you type yahoo.com in browser it will be redirected to http://www.yahoo.com. If you want to do same with your website then put the following code to .htaccess file. What is benefit of this kind of redirection?? Please check the post about SEO friendly redirect (301) redirect in php and .htaccess.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^optimaxwebsolutions\.com$
RewriteRule (.*) http://www.optimaxwebsolutions.com/$1 [R=301,L]
Rewriting yoursite.com/user.php?username=xyz to yoursite.com/xyz
Have you checked zorpia.com.If you type http://zorpia.com/roshanbh233 in browser you can see my profile over there. If you want to do the same kind of redirection i.e http://yoursite.com/xyz to http://yoursite.com/user.php?username=xyz then you can add the following code to the .htaccess file.
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ user.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ user.php?username=$1
Redirecting the domain to a new subfolder of inside public_html.
Suppose the you’ve redeveloped your site and all the new development reside inside the “new” folder of inside root folder.Then the new development of the website can be accessed like “test.com/new”. Now moving these files to the root folder can be a hectic process so you can create the following code inside the .htaccess file and place it under the root folder of the website. In result, http://www.test.com point out to the files inside “new” folder.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^test\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.test\.com$
RewriteCond %{REQUEST_URI} !^/new/
RewriteRule (.*) /new/$1
Shortening URLs
One common use of mod_rewrite is to shorten URL’s. Shorter URL’s are easier to remember and, of course, easier to type. An example..
Options +FollowSymlinks
RewriteEngine On
RewriteRule ^grab /public/files/download/download.php
this rule would transform this user’s URL..
http://mysite/grab?file=my.zip
server-side, into..
http://mysite/public/files/download/download.php?file=my.zip
Everyone likes short URL’s, and so will you; using this technique, you can move/public/files/download/ to anywhere else in your site, and all the old links still work fine; simply alter your .htaccess file to reflect the new location. edit one line, done – nice – means even when stuff is way deep in your site you can have cool links like this.. /trueview/sample.php and this; links which are not only short, but flat..
Cairngorm a MVC framework for Flex
Posted: November 23, 2010 in Cairngorm, FlexTags: Cairngorm, Flex
Model–View–Controller (MVC) is a software architecture currently considered an architectural pattern used in software engineering. The model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller). In event-driven systems, the model notifies observers (usually views) when the information changes so that they can react.
The view renders the model into a form suitable for interaction, typically a user interface element. Multiple views can exist for a single model for different purposes. A viewport typically has a one to one correspondence with a display surface and knows how to render to it.
The controller receives input and initiates a response by making calls on model objects. A controller accepts input from the user and instructs the model and viewport to perform actions based on that input.
An MVC application may be a collection of model/view/controller triads, each responsible for a different UI element. The Swing GUI system, for example, models almost all interface components as individual MVC systems.
Cairngorm is based on the MVC model. It is specifically designed to facilitate complex state and data synchronization between the client and the server, while keeping the programming of the View layer detached from the data implementation. The role of the View layer in a Cairngorm application is to throw events and bind to data stored in the Model. Components on the View can bind to Value Objects or other properties in the Model (data) layer. In a Cairngorm Model, related data are stored in Value Objects (VOs), while simple variables can be stored as direct properties of the ModelLocator class. A static reference to the ModelLocator singleton instance is used by the View layers to locate the required data. The Controller is the most sophisticated part of the Cairngorm architecture. The Controller layer is implemented as a singleton FrontController. The FrontController instance, which receives every View-generated event, dispatches the events to the assigned Command class based on the event’s declared type. The Command class then processes the event by running the Command class’ execute() method, which is an ICommand interface method. The event object may include additional data if required by the developer. The execute() method can update the central Model, as well as invoke a Service class which typically involves communication with a remote server. The IResponder interface, which is also implemented by the Command class, includes onResult and onFault methods to handle responses returned from the invoked remote service.
Core Principles
• Minimize script block logic in MXML, extract into behavior objects following Single Responsibility Principle.
• Prefer small classes with high functional cohesion (every method refers to all properties).
• Show the intent of code clearly. Understand options in loose coupling and apply when motivations are clear.
• Allow modular development and testing; organize by functional areas, control and limit dependencies between functional areas, extract and control shared infrastructure.
• Perform automated, functional testing.
• Perform automated unit testing and differentiate from automated functional testing; emphasize on behavior instead of structure and wiring.
• Control quality and streamline a release with build automation.
• Prefer convention over configuration.
• Create genuinely reusable view and non-visual (i.e. formatters, validators, log targets) components only using Flex SDK APIs without domain or IoC framework knowledge.
Now I am going to describe how to develop a contact management system using Cairngorm framework
The functionalities are
• Add new contact
• Display contact
• Search
• Update
• Delete
Step 1: Create Database and Tables
Step 2: Create a VO (Value Object)
Step 3: Create View
Step 4: Create Model
Step 5: Create DAO (Data Access Object)
Step 6: Create Event
Step 7: Create Command Classes
File Upload from Flex to Mysql Database Java Code Part-2
Posted: November 20, 2010 in File Upload, JavaTags: Flex, Java, Magento
Today I am going to describe how to insert the uploaded file in to Mysql database.For this we need apache fileupload jar files commons-fileupload-1.2.1.jar and commons.io-1.4.jar. . You can download the latest version of the package from http://commons.apache.org/downloads/download_fileupload.cgi.
Now first I am writing a class file
FileUploadListner.java
package servlet;
import org.apache.commons.fileupload.ProgressListener;
public class FileUploadListener implements ProgressListener
{
private volatile long
bytesRead = 0L,
contentLength = 0L,
item = 0L;
public FileUploadListener()
{
super();
}
public void update(long aBytesRead, long aContentLength, int anItem)
{
bytesRead = aBytesRead;
contentLength = aContentLength;
item = anItem;
}
public long getBytesRead()
{
return bytesRead;
}
public long getContentLength()
{
return contentLength;
}
public long getItem()
{
return item;
}
}
Now I am writing a servlet which will insert the file into database.
MyUploadServlet.java
package servlet;
import DBConnection;
import javax.servlet.http.HttpServlet;
import javax.servlet.Servlet;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.sql.*;
public class MyUploadServlet extends HttpServlet implements Servlet
{
private String filename;
public MyUploadServlet()
{
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
DBConnection con=new DBConnection();
PrintWriter ptr=response.getWriter();
String jnan="";
// create file upload factory and upload servlet
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// set file upload progress listener
FileUploadListener listener = new FileUploadListener();
HttpSession session = request.getSession();
session.setAttribute("LISTENER", listener);
// upload servlet allows to set upload listener
upload.setProgressListener(listener);
List uploadedItems = null;
FileItem fileItem = null;
try
{
// iterate over all uploaded files
uploadedItems = upload.parseRequest(request);
Iterator i = uploadedItems.iterator();
String str1[]={"","","","","","","","","","","","",""};
int cc=0;
while (i.hasNext())
{
fileItem = (FileItem) i.next();
if(fileItem.isFormField() == true&&cc!=2)
{
jnan=String.valueOf(fileItem);
jnan=jnan.substring(jnan.indexOf("FieldName=")+10,jnan.length());
str1[cc]=jnan;
cc++;
}
if (fileItem.isFormField() == false)
{
if (fileItem.getSize() > 0)
{
File uploadedFile = null;
String myFullFileName = fileItem.getName(),
myFileName = "",
slashType = (myFullFileName.lastIndexOf("\\") > 0) ? "\\" : "/"; // Windows or UNIX
int startIndex = myFullFileName.lastIndexOf(slashType);
//Get File Name
myFileName = myFullFileName.substring(startIndex + 1, myFullFileName.length());
//Get File Extension
String fileExt=myFileName.substring(myFileName.indexOf("."),myFileName.length());
// Create new File object
try{
ByteArrayInputStream bs=new ByteArrayInputStream(fileItem.get());
String query="INSERT INTO image(img) VALUES(?)";
PreparedStatement pst=con.conn.prepareStatement(query);
pst.setBinaryStream(1, bs,(int)fileItem.getSize());
pst.execute();
}
catch(Exception e)
{
System.out.println("in MyUploadServlet..Error:- "+e.getMessage());
}
}
}
}
}
catch (FileUploadException e)
{
System.out.println("in MyUploadServlet..Error:- "+e.getMessage());
}
catch (Exception e)
{
System.out.println("in MyUploadServlet..Error:- "+e.getMessage());
}
finally
{
con.DisconnectCon();
}
}
}
Here DBConnection is a class file.I am using this class to connect to mysql database from my eclipse.I made a connection pooling from apache tomcat 5.5 to Mysql.This class file is given below.
DBConnection.java:-
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class DBConnection {
private javax.naming.Context ic;
private javax.sql.DataSource ds;
public java.sql.Connection conn;
public DBConnection()
{
try
{
ic=(Context)new InitialContext().lookup("java:comp/env");
ds=(DataSource)ic.lookup("jdbc/MyJndiName");
conn=ds.getConnection();
}
catch(Exception e)
{
System.out.println("Error in DBConnection "+e.getMessage());
}
}
public void DisconnectCon()
{
try
{
conn.close();
}
catch(Exception e)
{
System.out.println("Error in DisconnectCon "+e.getMessage());
}
}
}
Done….The file is there in Database…