'script'에 해당되는 글 8건

  1. 2013.04.23 JSON.simple
  2. 2013.04.19 document.implemention.hasFeature('Core')
  3. 2012.10.04 decodeXSS
  4. 2012.07.06 fileupload
  5. 2012.03.01 정규식 : 특정단어 제외

JSON.simple

2013. 4. 23. 23:45 from script

SIMPLE EXAMPLE

 

 java

 

jsp 




Simple Java toolkit for JSON (JSON.simple)
==========================================

http://www.JSON.org/java/json_simple.zip

1.Why the Simple Java toolkit (also named as JSON.simple) for JSON?

  When I use JSON as the data exchange format between the AJAX client and JSP
  for the first time, what worry me mostly is how to encode Java strings and
  numbers correctly in the server side so the AJAX client will receive a well
  formed JSON data. When I looked into the 'JSON in Java' directory in JSON
  website,I found that wrappers to JSONObject and JSONArray can be simpler,
  due to the simplicity of JSON itself. So I wrote the JSON.simple package.

2.Is it simple,really?

  I think so. Take an example:

  import org.json.simple.JSONObject;

  JSONObject obj=new JSONObject();
  obj.put("name","foo");
  obj.put("num",new Integer(100));
  obj.put("balance",new Double(1000.21));
  obj.put("is_vip",new Boolean(true));
  obj.put("nickname",null);
  System.out.print(obj);

  Result:
  {"nickname":null,"num":100,"balance":1000.21,"is_vip":true,"name":"foo"}

  The JSONObject.toString() will escape controls and specials correctly.

3.How to use JSON.simple in JSP?

  Take an example in JSP:

  <%@page contentType="text/html; charset=UTF-8"%>
  <%@page import="org.json.simple.JSONObject"%>
  <%
    JSONObject obj=new JSONObject();
    obj.put("name","foo");
    obj.put("num",new Integer(100));
    obj.put("balance",new Double(1000.21));
    obj.put("is_vip",new Boolean(true));
    obj.put("nickname",null);
    out.print(obj);
    out.flush();
  %>

  So the AJAX client will get the responseText.

4.Some details about JSONObject?

  JSONObject inherits java.util.HashMap,so it don't have to worry about the
  mapping things between keys and values. Feel free to use the Map methods
  like get(), put(), and remove() and others. JSONObject.toString() will
  combine key value pairs to get the JSON data string. Values will be escaped
  into JSON quote string format if it's an instance of java.lang.String. Other
  type of instance like java.lang.Number,java.lang.Boolean,null,JSONObject and
  JSONArray will NOT escape, just take their java.lang.String.valueOf() result.
  null value will be the JSON 'null' in the result.

  It's still correct if you put an instance of JSONObject or JSONArray into an
  instance of JSONObject or JSONArray. Take the example about:

  JSONObject obj2=new JSONObject();
  obj2.put("phone","123456");
  obj2.put("zip","7890");
  obj.put("contact",obj2);
  System.out.print(obj);

  Result:
  {"nickname":null,"num":100,"contact":{"phone":"123456","zip":"7890"},"balance":1000.21,"is_vip":true,"name":"foo"}

  The method JSONObject.escape() is used to escape Java string into JSON quote
  string. Controls and specials will be escaped correctly into \b,\f,\r,\n,\t,
  \",\\,\/,\uhhhh.

5.Some detail about JSONArray?

  org.json.simple.JSONArray inherits java.util.ArrayList. Feel free to use the
  List methods like get(),add(),remove(),iterator() and so on. The rules of
  JSONArray.toString() is similar to JSONObject.toString(). Here's the example:

  import org.json.simple.JSONArray;

  JSONArray array=new JSONArray();
  array.add("hello");
  array.add(new Integer(123));
  array.add(new Boolean(false));
  array.add(null);
  array.add(new Double(123.45));
  array.add(obj2);//see above
  System.out.print(array);

  Result:
  ["hello",123,false,null,123.45,{"phone":"123456","zip":"7890"}]

6.What is JSONValue for?

  org.json.simple.JSONValue is use to parse JSON data into Java Object.
  In JSON, the topmost entity is JSON value, not the JSON object. But
  it's not necessary to wrap JSON string,boolean,number and null again,
  for the Java has already had the according classes: java.lang.String,
  java.lang.Boolean,java.lang.Number and null. The mapping is:

  JSON          Java
  ------------------------------------------------
  string      <=>   java.lang.String
  number      <=>   java.lang.Number
  true|false  <=>   java.lang.Boolean
  null        <=>   null
  array       <=>   org.json.simple.JSONArray
  object      <=>       org.json.simple.JSONObject
  ------------------------------------------------

  JSONValue has only one kind of method, JSONValue.parse(), which receives
  a java.io.Reader or java.lang.String. Return type of JSONValue.parse()
  is according to the mapping above. If the input is incorrect in syntax or
  there's exceptions during the parsing, I choose to return null, ignoring
  the exception: I have no idea if it's a serious implementaion, but I think
  it's convenient to the user.

  Here's the example:

  String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
  Object obj=JSONValue.parse(s);
  JSONArray array=(JSONArray)obj;
  System.out.println(array.get(1));
  JSONObject obj2=(JSONObject)array.get(1);
  System.out.println(obj2.get("1"));

  Result:
  {"1":{"2":{"3":{"4":[5,{"6":7}]}}}}
  {"2":{"3":{"4":[5,{"6":7}]}}}

7.About the author.

  I'm a Java EE developer on Linux.
  I'm working on web systems and information retrieval systems.
  I also develop 3D games and Flash games.

  You can contact me through:
  Fang Yidong<fangyidong@yahoo.com.cn>
  Fang Yidong<fangyidng@gmail.com>

  http://www.JSON.org/java/json_simple.zip

[출처] json simple test|작성자 우앙

'script' 카테고리의 다른 글

document.implemention.hasFeature('Core')  (0) 2013.04.19
decodeXSS  (0) 2012.10.04
fileupload  (0) 2012.07.06
정규식 : 특정단어 제외  (0) 2012.03.01
undefined, null, typeof  (0) 2012.01.11
Posted by 에시드 :

document.implemention.hasFeature()

boolean hasFeature(String feature, String version);

전달인자

feature 지원여부를 알아볼 기능 이름

version 지원 여부를 알아볼 기능의 버전 번호. 버전에 상관없이  지원여부만 확인하려면, null 또는 빈문자열("").

           DOM 레벨2명세서에서 지원하는 버전번호는 1.0과 2.0이다.

반환값

DOM 구현에서 특정기능의 특정버전을 완벽히 지원하면 true, 아니면 false를 반환한다.

버전번호를 지정하지 않고, DOM 구현에서 특정기능의 한버전만이라도 완벽히 지원하면 true

 

feature

Core : Node, Element, Document, Text와 그밖의 모든 DOM구현에서 기본적인 역활을 담당하는 인터페이스들을 구현한다.

          표준을 준수하는 모든 구현은 이모듈을 지원해야 한다.

HTML : HTMLElement, HTMLDocument와 그밖의 HTML에 특수한 인터페이스를 구현한다.

XML : Entity, EntityReference, ProcessingInstruction, Notation과 XML 문서에 대해 유용하게 사용할수있는 기타 노드 타입을

        구현한다.

StyleSheets : 스타일시트와 관현해 공통적인 정보를 알려주는 간단한 인터페이스를 구현한다.

CSS : CSS 스타일시트에 특수한 인터페이스를 구현한다.

CSS2 : CSS2Properties 인터페이스를 구현한다.

Events : 기본적인 이벤트 처리 인터페이스를 구현한다.

UIEvents : 사용자인터페이스 관련 이벤트를 처리하는 인터페이스를 구현한다.

MouseEvents : 마우스 이벤트를 처리하는 인터페이스를 구현한다.

HTMLEvents : HTML 이벤트를 처리하는 인터페이스를 구현한다.

MutationEvents : 문서변경 이벤트를 처리하는 인터페이스를 구현한다.

Range : 문서의 특정구역을 조작하는 인터페이스를 구현한다.

Traversal : 향상된 문서 탐색기능을 지원하는 인터페이스를 구현한다.

Views : 문서 뷰를 위한 인터페이스를 구현한다.

 

다음과 같이 사용한다.

 

 


 
 
 

 

'script' 카테고리의 다른 글

JSON.simple  (0) 2013.04.23
decodeXSS  (0) 2012.10.04
fileupload  (0) 2012.07.06
정규식 : 특정단어 제외  (0) 2012.03.01
undefined, null, typeof  (0) 2012.01.11
Posted by 에시드 :

decodeXSS

2012. 10. 4. 09:50 from script

  /* 변환값을 되돌리는 XSS 함수입니다. */
function decodeXSS(value){

    value = value.replace("&amp;", "&");
    value = value.replace("&#35;", "#");
    value = value.replace("&lt;", "<");
    value = value.replace("&gt;", ">");
    value = value.replace("&#40;", "\(");
    value = value.replace("&#41;", "\)");
    value = value.replace("&#39;", "'");
    //value = value.replace("eval\\((.*)\\)", "");
    value = value.replace("&#34;", "\"");

    return value;
}

function cleanXSS(value){

    value = value.replace("&", "&amp;");
    value = value.replace("#", "&#35;");
    value = value.replace("<", "&lt;");
    value = value.replace(">", "&gt;");
    value = value.replace("\\(", "&#40;");
    value = value.replace("\\)", "&#41;");
    value = value.replace("'", "&#39;");
    value = value.replace("eval\\((.*)\\)", "");
    value = value.replace("\"","&#34;");

    return value;
}

'script' 카테고리의 다른 글

JSON.simple  (0) 2013.04.23
document.implemention.hasFeature('Core')  (0) 2013.04.19
fileupload  (0) 2012.07.06
정규식 : 특정단어 제외  (0) 2012.03.01
undefined, null, typeof  (0) 2012.01.11
Posted by 에시드 :

fileupload

2012. 7. 6. 14:23 from script

 // iplanet 연동으로 인해 was까지 딜레이로 uploadMonitor Sync용 딜레이 연산
 function filesize1(){
  //alert(uploadLen);
  var fileObj = null;
  var len = "";
  fileObj = document.getElementById("file1");
  if(navigator.userAgent.indexOf('MSIE') < 0){
  // IE 아닐경우
   if(typeof FileReader !=="undefined"){   
    len = fileObj.files[0].size;
   }
  } else if(navigator.userAgent.indexOf('MSIE') > 0){
  // IE
   if(navigator.appVersion.indexOf("MSIE 6.") > 0){
   //IE6 
    var img = new Image();
    img.dynsrc = fileObj.value;
    len = img.fileSize;

   } else {
   // IE7,9
    var fso=new ActiveXObject('Scripting.FileSystemObject');
    var f =fso.GetFile(fileObj.value);
    //alert(f.Size);
    //alert(f.DateCreated);
    len = f.size;
    f = null;
    fso = null;
   }
  }
  // 최대 50MB len은 MB로 계산
  len = len/(1024*1024);
  var strLen = len+"";  
  uploadLen = strLen.substring(0 , strLen.indexOf("."));
  if(uploadLen == 0 || uploadLen < 5 ){
   msec = 3000;
  } else {
   msec = uploadLen * 600;
  }
  alert(msec);
  
 }
 
 function getSize(){
  var str = document.all;
  alert(str.gimg.fileSize);
 }

 

 

 

 var uploadLen = "0";
 var msec = 3000;

 // 파일 업로드 상태 바를 보여준다.
 function upload() {
  startProgress2(msec);
  document.uploadFrm.submit();
 }

 $(document).ready(function() {
  if("<%=uploadType%>" == "template") {
   $("#attention").each(function() {
    $(this).show();
   });
  }
 });

 

 

 

 

var timer;


function refreshProgress() {
    UploadMonitor.getUploadInfo(updateProgress);
}

function updateProgress(uploadInfo) {
    if (uploadInfo.inProgress) {
     clearInterval(timer);
     timer = 0;
        document.getElementById('uploadbutton').disabled = true;
        document.getElementById('file1').disabled = true;

        var fileIndex = uploadInfo.fileIndex;

        var progressPercent = Math.ceil((uploadInfo.bytesRead / uploadInfo.totalSize) * 100);

        document.getElementById('progressBarText').innerHTML = 'upload in progress: ' + progressPercent + '%, transfered ' + uploadInfo.bytesRead + ' of ' + uploadInfo.totalSize + ' bytes';
       
        widthMultiplier = document.getElementById('progressBarBox').clientWidth / 100;
       
        document.getElementById('progressBarBoxContent').style.width = parseInt(progressPercent * widthMultiplier) + 'px';

        window.setTimeout('refreshProgress()', 500);
    }
    else {
        document.getElementById('uploadbutton').disabled = false;
        document.getElementById('file1').disabled = false;
    }
    return true;
}

function startProgress() {
    document.getElementById('progressBarBoxContent').style.width = 0 + 'px';
    document.getElementById('progressBarText').innerHTML = 'upload in progress: 0%';
    document.getElementById('uploadbutton').disabled = true;
    window.setTimeout("refreshProgress()", 1500);
    document.getElementById('progressBar').style.display = 'block';

    return true;
}

function startProgress2(value) {
 var msec = value;
 
    document.getElementById('progressBarBoxContent').style.width = 0 + 'px';
    //document.getElementById('progressBarText').innerHTML = 'upload in progress: 0%';
    document.getElementById('progressBarText').innerHTML = 'upload in progress: 0%, initialization, wait a minute';
    document.getElementById('uploadbutton').disabled = true;
    //window.setTimeout("refreshProgress()", msec);
    timer = setInterval("refreshProgress()",3000);

    document.getElementById('progressBar').style.display = 'block';

    return true;
}

'script' 카테고리의 다른 글

document.implemention.hasFeature('Core')  (0) 2013.04.19
decodeXSS  (0) 2012.10.04
정규식 : 특정단어 제외  (0) 2012.03.01
undefined, null, typeof  (0) 2012.01.11
offsetHeight, clientHeight, scrollHeight  (0) 2011.09.19
Posted by 에시드 :

정규식 : 특정단어 제외

2012. 3. 1. 21:46 from script

 

[ ] ( ) - + ` _ 제외한 모든 특수문자 검출  

 var regex=/[^\[\]\(\)\-\+\`_ㄱ-힣a-zA-Z0-9]/

 

 

[^abc] 는 a,b,c 는 3요.


약 abc 요?


replace.(/abc/g, '');


/abc 속/; 다.


\w(?=abc) 면 abc 는 \w

요.

 

-------------------------------------------------------------------------------------

\b([^a\s]|a+b[^ac\s])+\b

이 패턴은 완전하지는 않지만 상당히 가깝습니다.

 

아이디어는 있는데 정규식에 익숙하지 않아서 구현이 잘 안됩니다.

 

([a를 포함하지 않은 문자] | a+bb | a+[a,b를 포함하지않은 문자])+ 를 해주면

a+ 로 끝나거나 a+b로 끝나는 단어가 빠집니다. 이를 더 추가해주면 될것 같은데

의도하는 대로 되지가 않네요.

 

위에서 정규식을 설명하면 이렇습니다.

 

만약 a를 포함하지 않은 경우에는 처음 a를 포함하지 않은 문자들의 조합으로

해결이 됩니다.

 

a를 포함한 경우를 봅니다. 다시 다른 글자들과 이어질려면 abb꼴이면 됩니다.

이것도 a+bb에 의해서 해결이 됩니다.

 

a를 포함하지만 b가 이어 나오지 않는 다면 문제가 되지 않습니다.

이것도 a+[a,b를 포함하지 않는 문자]에 의해서 해결이 됩니다. [앞부분]

 

문제는 a+로 끝나거나 a+b로 끝나는 것이 빠진다는 점입니다. [뒷부분]

그래서 (앞부분|앞부분 뒷부분|뒷부분) 과 같은 꼴이면 되겠습니다.

 

문제는 이러한 것을 정규식으로 표현해 볼려고 해도 제대로 표현이

안된다는 점입니다.


'script' 카테고리의 다른 글

decodeXSS  (0) 2012.10.04
fileupload  (0) 2012.07.06
undefined, null, typeof  (0) 2012.01.11
offsetHeight, clientHeight, scrollHeight  (0) 2011.09.19
자바스크립트 챠트 이미지  (0) 2011.09.19
Posted by 에시드 :