View Javadoc

1   /*
2    * Copyright 2002-2009 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package net.sf.json.util;
18  
19  import java.util.Iterator;
20  
21  import net.sf.json.JSON;
22  import net.sf.json.JSONArray;
23  import net.sf.json.JSONNull;
24  import net.sf.json.JSONObject;
25  
26  /**
27   * Provides useful methods for working with JSON and web.
28   *
29   * @author Andres Almiray <aalmiray@users.sourceforge.net>
30   */
31  public class WebUtils {
32     private static final WebHijackPreventionStrategy DEFAULT_WEB_HIJACK_PREVENTION_STRATEGY = WebHijackPreventionStrategy.INFINITE_LOOP;
33     private static WebHijackPreventionStrategy webHijackPreventionStrategy = DEFAULT_WEB_HIJACK_PREVENTION_STRATEGY;
34  
35     /**
36      * Returns the configured WebHijackPreventionStrategy.
37      */
38     public static WebHijackPreventionStrategy getWebHijackPreventionStrategy() {
39        return webHijackPreventionStrategy;
40     }
41  
42     /**
43      * Transforms the input Json string using the configured
44      * WebHijackPreventionStrategy.<br>
45      *
46      * @param json the input string
47      * @return String a transformed json string
48      */
49     public static String protect( JSON json ) {
50        return protect( json, false );
51     }
52  
53     /**
54      * Transforms the input Json string using the configured
55      * WebHijackPreventionStrategy.<br>
56      *
57      * @param json the input string
58      * @param shrink if redundant key quotes may be eliminated.
59      * @return String a transformed json string
60      */
61     public static String protect( JSON json, boolean shrink ) {
62        String output = !shrink ? json.toString( 0 ) : toString( json );
63        return webHijackPreventionStrategy.protect( output );
64     }
65  
66     /**
67      * Sets a WebHijackPreventionStrategy.<br>
68      * Will use default value (WebHijackPreventionStrategy.INFINITE_LOOP) if
69      * null.
70      */
71     public static void setWebHijackPreventionStrategy( WebHijackPreventionStrategy strategy ) {
72        webHijackPreventionStrategy = strategy == null ? DEFAULT_WEB_HIJACK_PREVENTION_STRATEGY
73              : strategy;
74     }
75  
76     /**
77      * Returns a string represenation of a JSON value.<br>
78      * When an object property name does not contain a space (' ') or a colon
79      * (':'), the quotes are omitted. This is done to reduce the amount of bytes
80      * sent to a web browser.<br/>USE WITH CAUTION.
81      */
82     public static String toString( JSON json ) {
83        if( json instanceof JSONObject ){
84           return toString( (JSONObject) json );
85        }else if( json instanceof JSONArray ){
86           return toString( (JSONArray) json );
87        }else{
88           return toString( (JSONNull) json );
89        }
90     }
91  
92     private static String join( JSONArray jsonArray ) {
93        int len = jsonArray.size();
94        StringBuffer sb = new StringBuffer();
95  
96        for( int i = 0; i < len; i += 1 ){
97           if( i > 0 ){
98              sb.append( "," );
99           }
100          Object value = jsonArray.get( i );
101          sb.append( toString( value ) );
102 
103       }
104       return sb.toString();
105    }
106 
107    private static String quote( String str ) {
108       if( str.indexOf( " " ) > -1 || str.indexOf( ":" ) > -1 ){
109          return JSONUtils.quote( str );
110       }else{
111          return str;
112       }
113    }
114 
115    private static String toString( JSONArray jsonArray ) {
116       try{
117          return '[' + join( jsonArray ) + ']';
118       }catch( Exception e ){
119          return null;
120       }
121    }
122 
123    private static String toString( JSONNull jsonNull ) {
124       return jsonNull.toString();
125    }
126 
127    private static String toString( JSONObject jsonObject ) {
128       if( jsonObject.isNullObject() ){
129          return JSONNull.getInstance()
130                .toString();
131       }
132       Iterator keys = jsonObject.keys();
133       StringBuffer sb = new StringBuffer( "{" );
134 
135       while( keys.hasNext() ){
136          if( sb.length() > 1 ){
137             sb.append( ',' );
138          }
139          Object o = keys.next();
140          sb.append( quote( o.toString() ) );
141          sb.append( ':' );
142          sb.append( toString( jsonObject.get( String.valueOf( o ) ) ) );
143       }
144       sb.append( '}' );
145       return sb.toString();
146    }
147 
148    private static String toString( Object object ) {
149       if( object instanceof JSON ){
150          return toString( (JSON) object );
151       }else{
152          return JSONUtils.valueToString( object );
153       }
154    }
155 
156    private WebUtils() {
157    }
158 }