IT정리노트

블로그 이미지

Edward. K

메멘토적 기억능력을 소유한 개발자 노트.

'Programming'에 해당되는 글 154건

제목 날짜
  • LightBox를 이용한 Gallery 만들기 2009.06.30
  • 24 JavaScript Best Practices for Beginners 2009.06.30
  • cos.jar로 파일 업로드 하기 2009.06.29
  • JavaScript 암호화,복호화 2009.06.29
  • Eclipse 자동주석 설정법2 2009.06.29

LightBox를 이용한 Gallery 만들기

Programming/JavaScript 2009. 6. 30. 14:24
반응형

LightBox2로 만드는 이미지 게시판
 - 원문 : http://www.ibm.com/developerworks/kr/library/wa-ltbox/

게시판을 만들때 유용하겠네요.( 현재 나와있는 이미지 갤러리도 많아용~)


위 캡쳐는 제공된 샘플 파일을 약간 수정한 화면입니다. (gallery.css 파일만 약간 손보면 됩니다.)
반응형
저작자표시 비영리 변경금지 (새창열림)
Posted by Edward. K

24 JavaScript Best Practices for Beginners

Programming/JavaScript 2009. 6. 30. 12:14
반응형

원문 : 24 JavaScript Best Practices for Beginners

1. Use === Instead of ==

JavaScript utilizes two different kinds of equality operators: === | !== and == | != It is considered best practice to always use the former set when comparing.

"If two operands are of the same type and value, then === produces true and !== produces false." - JavaScript: The Good Parts

However, when working with == and !=, you'll run into issues when working with different types. In these cases, they'll try to coerce the values, unsuccessfully.

2. Eval = Bad

For those unfamiliar, the "eval" function gives us access to JavaScript's compiler. Essentially, we can execute a string's result by passing it as a parameter of "eval".

Not only will this decrease your script's performance substantially, but it also poses a huge security risk because it grants far too much power to the passed in text. Avoid it!

3. Don't Use Short-Hand

Technically, you can get away with omitting most curly braces and semi-colons. Most browsers will correctly interpret the following:

  1. if(someVariableExists)   
  2.    x = false  
if(someVariableExists)
   x = false

However, consider this:

  1. if(someVariableExists)   
  2.    x = false  
  3.    anotherFunctionCall();  
if(someVariableExists)
   x = false
   anotherFunctionCall();

One might think that the code above would be equivalent to:

  1. if(someVariableExists) {   
  2.    x = false;   
  3.    anotherFunctionCall();   
  4. }  
if(someVariableExists) {
   x = false;
   anotherFunctionCall();
}

Unfortunately, he'd be wrong. In reality, it means:

  1. if(someVariableExists) {   
  2.    x = false;   
  3. }   
  4. anotherFunctionCall();  
if(someVariableExists) {
   x = false;
}
anotherFunctionCall();

As you'll notice, the indentation mimics the functionality of the curly brace. Needless to say, this is a terrible practice that should be avoided at all costs. The only time that curly braces should be omitted is with one-liners, and even this is a highly debated topic.

  1. if(2 + 2 === 4) return 'nicely done';  
if(2 + 2 === 4) return 'nicely done';

Always Consider the Future

What if, at a later date, you need to add more commands to this if statement. In order to do so, you would need to rewrite this block of code. Bottom line - tread with caution when omitting.

4. Utilize JS Lint

JSLint is a debugger written by Douglas Crockford. Simply paste in your script, and it'll quickly scan for any noticeable issues and errors in your code.

"JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems."
- JSLint Documentation

Before signing off on a script, run it through JSLint just to be sure that you haven't made any mindless mistakes.

5. Place Scripts at the Bottom of Your Page

This tip has already been recommended in the previous article in this series. As it's highly appropriate though, I'll paste in the information.

Remember -- the primary goal is to make the page load as quickly as possible for the user. When loading a script, the browser can't continue on until the entire file has been loaded. Thus, the user will have to wait longer before noticing any progress.

If you have JS files whose only purpose is to add functionality -- for example, after a button is clicked -- go ahead and place those files at the bottom, just before the closing body tag. This is absolutely a best practice.

Better

  1. <p>And now you know my favorite kinds of corn. </p>  
  2. <script type="text/javascript" src="path/to/file.js"></script>  
  3. <script type="text/javascript" src="path/to/anotherFile.js"></script>  
  4. </body>  
  5. </html>  
<p>And now you know my favorite kinds of corn. </p>
<script type="text/javascript" src="path/to/file.js"></script>
<script type="text/javascript" src="path/to/anotherFile.js"></script>
</body>
</html>

6. Declare Variables Outside of the For Statement

When executing lengthy "for" statements, don't make the engine work any harder than it must. For example:

Bad

  1. for(var i = 0; i < someArray.length; i++) {   
  2.    var container = document.getElementById('container');   
  3.    container.innerHtml += 'my number: ' + i;   
  4.    console.log(i);   
  5. }  
for(var i = 0; i < someArray.length; i++) {
   var container = document.getElementById('container');
   container.innerHtml += 'my number: ' + i;
   console.log(i);
}

Notice how we must determine the length of the array for each iteration, and how we traverse the dom to find the "container" element each time -- highly inefficient!

Better

  1. var container = document.getElementById('container');   
  2. for(var i = 0, len = someArray.length; i < len;  i++) {   
  3.    container.innerHtml += 'my number: ' + i;   
  4.    console.log(i);   
  5. }  
var container = document.getElementById('container');
for(var i = 0, len = someArray.length; i < len;  i++) {
   container.innerHtml += 'my number: ' + i;
   console.log(i);
}

Bonus points to the person who leaves a comment showing us how we can further improve the code block above.

7. The Fastest Way to Build a String

Don't always reach for your handy-dandy "for" statement when you need to loop through an array or object. Be creative and find the quickest solution for the job at hand.

  1. var arr = ['item 1', 'item 2', 'item 3', ...];   
  2. var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';  
var arr = ['item 1', 'item 2', 'item 3', ...];
var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';

I won’t bore you with benchmarks; you’ll just have to believe me (or test for yourself) - this is by far the fastest method!

Using native methods (like join()), regardless of what’s going on behind the abstraction layer, is usually much faster than any non-native alternative.
- James Padolsey, james.padolsey.com

8. Reduce Globals

"By reducing your global footprint to a single name, you significantly reduce the chance of bad interactions with other applications, widgets, or libraries."
- Douglas Crockford

  1. var name = 'Jeffrey';   
  2. var lastName = 'Way';   
  3.   
  4. function doSomething() {...}   
  5.   
  6. console.log(name); // Jeffrey -- or window.name  
var name = 'Jeffrey';
var lastName = 'Way';

function doSomething() {...}

console.log(name); // Jeffrey -- or window.name

Better

  1. var DudeNameSpace = {   
  2.    name : 'Jeffrey',   
  3.    lastName : 'Way',   
  4.    doSomething : function() {...}   
  5. }   
  6. console.log(DudeNameSpace.name); // Jeffrey  
var DudeNameSpace = {
   name : 'Jeffrey',
   lastName : 'Way',
   doSomething : function() {...}
}
console.log(DudeNameSpace.name); // Jeffrey

Notice how we've "reduced our footprint" to just the ridiculously named "DudeNameSpace" object.

9. Comment Your Code

It might seem unnecessary at first, but trust me, you WANT to comment your code as best as possible. What happens when you return to the project months later, only to find that you can't easily remember what your line of thinking was. Or, what if one of your colleagues needs to revise your code? Always, always comment important sections of your code.

 
  1. // Cycle through array and echo out each name.    
  2. for(var i = 0, len = array.length; i < len; i++) {   
  3.    console.log(array[i]);   
  4. }  
// Cycle through array and echo out each name. 
for(var i = 0, len = array.length; i < len; i++) {
   console.log(array[i]);
}

10. Embrace Progressive Enhancement

Always compensate for when JavaScript is disabled. It might be tempting to think, "The majority of my viewers have JavaScript enabled, so I won't worry about it." However, this would be a huge mistake.

Have you taken a moment to view your beautiful slider with JavaScript turned off? (Download the Web Developer Toolbar for an easy way to do so.) It might break your site completely. As a rule of thumb, design your site assuming that JavaScript will be disabled. Then, once you've done so, begin to progressively enhance your layout!

11. Don't Pass a String to "SetInterval" or "SetTimeOut"

Consider the following code:

  1. setInterval(   
  2. "document.getElementById('container').innerHTML += 'My new number: ' + i", 3000   
  3. );  
setInterval(
"document.getElementById('container').innerHTML += 'My new number: ' + i", 3000
);

Not only is this code inefficient, but it also functions in the same way as the "eval" function would. Never pass a string to SetInterval and SetTimeOut. Instead, pass a function name.

  1. setInterval(someFunction, 3000);  
setInterval(someFunction, 3000);

12. Don't Use the "With" Statement

At first glance, "With" statements seem like a smart idea. The basic concept is that they can be used to provide a shorthand for accessing deeply nested objects. For example...

  1. with (being.person.man.bodyparts) {   
  2.    arms = true;   
  3.    legs = true;   
  4. }  
with (being.person.man.bodyparts) {
   arms = true;
   legs = true;
}

-- instead of --

  1. being.person.man.bodyparts.arms = true;   
  2. being.person.man.bodyparts.legs= true;  
being.person.man.bodyparts.arms = true;
being.person.man.bodyparts.legs= true;

Unfortunately, after some testing, it was found that they "behave very badly when setting new members." Instead, you should use var.

  1. var o = being.person.man.bodyparts;   
  2. o.arms = true;   
  3. o.legs = true;  
var o = being.person.man.bodyparts;
o.arms = true;
o.legs = true;

13. Use {} Instead of New Object()

There are multiple ways to create objects in JavaScript. Perhaps the more traditional method is to use the "new" constructor, like so:

  1. var o = new Object();   
  2. o.name = 'Jeffrey';   
  3. o.lastName = 'Way';   
  4. o.someFunction = function() {   
  5.    console.log(this.name);   
  6. }  
var o = new Object();
o.name = 'Jeffrey';
o.lastName = 'Way';
o.someFunction = function() {
   console.log(this.name);
}

However, this method receives the "bad practice" stamp without actually being so. Instead, I recommend that you use the much more robust object literal method.

Better

  1. var o = {   
  2.    name: 'Jeffrey',   
  3.    lastName = 'Way',   
  4.    someFunction : function() {   
  5.       console.log(this.name);   
  6.    }   
  7. };  
var o = {
   name: 'Jeffrey',
   lastName = 'Way',
   someFunction : function() {
      console.log(this.name);
   }
};

Note that if you simply want to create an empty object, {} will do the trick.

  1. var o = {};  
var o = {};

"Objects literals enable us to write code that supports lots of features yet still make it a relatively straightforward for the implementers of our code. No need to invoke constructors directly or maintain the correct order of arguments passed to functions, etc." - dyn-web.com

14. Use [] Instead of New Array()

The same applies for creating a new array.

Okay

  1. var a = new Array();   
  2. a[0] = "Joe";   
  3. a[1] = 'Plumber';  
var a = new Array();
a[0] = "Joe";
a[1] = 'Plumber';

Better

  1. var a = ['Joe','Plumber'];  
var a = ['Joe','Plumber'];

"A common error in JavaScript programs is to use an object when an array is required or an array when an object is required. The rule is simple: when the property names are small sequential integers, you should use an array. Otherwise, use an object." - Douglas Crockford

15. Long List of Variables? Omit the "Var" Keyword and Use Commas Instead

  1. var someItem = 'some string';   
  2. var anotherItem = 'another string';   
  3. var oneMoreItem = 'one more string';  
var someItem = 'some string';
var anotherItem = 'another string';
var oneMoreItem = 'one more string';

Better

  1. var someItem = 'some string',   
  2.     anotherItem = 'another string',   
  3.     oneMoreItem = 'one more string';  
var someItem = 'some string',
    anotherItem = 'another string',
    oneMoreItem = 'one more string';

...Should be rather self-explanatory. I doubt there's any real speed improvements here, but it cleans up your code a bit.

17. Always, Always Use Semicolons

Technically, most browsers will allow you to get away with omitting semi-colons.

  1. var someItem = 'some string'  
  2. function doSomething() {   
  3.   return 'something'  
  4. }  
var someItem = 'some string'
function doSomething() {
  return 'something'
}

Having said that, this is a very bad practice that can potentially lead to much bigger, and harder to find, issues.

Better

  1. var someItem = 'some string';   
  2. function doSomething() {   
  3.   return 'something';   
  4. }  
var someItem = 'some string';
function doSomething() {
  return 'something';
}

18. "For in" Statements

When looping through items in an object, you might find that you'll also retrieve method functions as well. In order to work around this, always wrap your code in an if statement which filters the information

  1. for(key in object) {   
  2.    if(object.hasOwnProperty(key) {   
  3.       ...then do something...   
  4.    }   
  5. }  
for(key in object) {
   if(object.hasOwnProperty(key) {
      ...then do something...
   }
}

As referenced from JavaScript: The Good Parts, by Douglas Crockford.

19. Use Firebug's "Timer" Feature to Optimize Your Code

Need a quick and easy way to determine how long an operation takes? Use Firebug's "timer" feature to log the results.

  1. function TimeTracker(){   
  2.  console.time("MyTimer");   
  3.  for(x=5000; x > 0; x--){}   
  4.  console.timeEnd("MyTimer");   
  5. }  
function TimeTracker(){
 console.time("MyTimer");
 for(x=5000; x > 0; x--){}
 console.timeEnd("MyTimer");
}

20. Read, Read, Read...

While I'm a huge fan of web development blogs (like this one!), there really isn't a substitute for a book when grabbing some lunch, or just before you go to bed. Always keep a web development book on your bedside table. Here are some of my JavaScript favorites.

  • Object-Oriented JavaScript
  • JavaScript: The Good Parts
  • Learning jQuery 1.3
  • Learning JavaScript

Read them...multiple times. I still do!

21. Self-Executing Functions

Rather than calling a function, it's quite simple to make a function run automatically when a page loads, or a parent function is called. Simply wrap your function in parenthesis, and then append an additional set, which essentially calls the function.

  1. (function doSomething() {   
  2.    return {   
  3.       name: 'jeff',   
  4.       lastName: 'way'  
  5.    };   
  6. })();  
(function doSomething() {
   return {
      name: 'jeff',
      lastName: 'way'
   };
})();

22. Raw JavaScript Can Always Be Quicker Than Using a Library

JavaScript libraries, such as jQuery and Mootools, can save you an enormous amount of time when coding -- especially with AJAX operations. Having said that, always keep in mind that a library can never be as fast as raw JavaScript (assuming you code correctly).

jQuery's "each" method is great for looping, but using a native "for" statement will always be an ounce quicker.

23. Crockford's JSON.Parse

Although JavaScript 2 should have a built-in JSON parser, as of this writing, we still need to implement our own. Douglas Crockford, the creator of JSON, has already created a parser that you can use. It can be downloaded HERE.

Simply by importing the script, you'll gain access to a new JSON global object, which can then be used to parse your .json file.

  1. var response = JSON.parse(xhr.responseText);   
  2.   
  3. var container = document.getElementById('container');   
  4. for(var i = 0, len = response.length; i < len; i++) {   
  5.   container.innerHTML += '<LI>' + response[i].name + ' : ' + response[i].email + '';   
  6. }   
  7. /LI>  
 var response = JSON.parse(xhr.responseText);

 var container = document.getElementById('container');
 for(var i = 0, len = response.length; i < len; i++) {
   container.innerHTML += '
  • ' + response[i].name + ' : ' + response[i].email + ''; }
  • 24. Remove "Language"

    Years ago, it wasn't uncommon to find the "language" attribute within script tags.

    1. <script type="text/javascript" language="javascript">   
    2. ...   
    3. </script>  
    <script type="text/javascript" language="javascript">
    ...
    </script>
    

    However, this attribute has long since been deprecated; so leave it out.


    생각없이 사용해 왔거나..혹은 왜 이렇게 안했지..라며 등한시 했던 것들..
    습관의 무서움..
    반응형
    저작자표시 비영리 변경금지 (새창열림)
    Posted by Edward. K

    cos.jar로 파일 업로드 하기

    Programming/JAVA 2009. 6. 29. 18:07
    반응형

    cos.jar로 파일 업로드 하기

    cos-05Nov2002.zip
    파일업로드를 하려면 기본적인 POST방식으로는 안되고 파일업로드를 처리할 수 있는 무언가(?) 있어야 한다.

    일단 jsp에서 파일 업로드를 선택하는 form에서 entype이 multipart/form-data로 보내야 한다. 그렇지 않으면  받는쪽에서 파일을 받을 수가 없다. 파일이 없으면 보통의 form은 entype을 바꾸어 주지 않아도 된다.

    view plaincopy to clipboardprint?
    1. <form name="writeForm" method="post" action="writeProc.jsp" enctype="multipart/form-data" >  
    2.      <input type="file" name="attachFile" size="40" />  
    3. </form>  

    이제 받아야 하는데 이걸 받는 역할을 cos.jar 가 한다. 폼전송을 multipart/form-data로 보냈기 때문에 기존에 폼을 받던 request.getParameter()로는 받을 수가 없다. 그래서 cos.jar가 파일도 받고 폼의 다른 값들도 다 받아주는 역할을 한다.

    cos는 com.oreilly.servlet의 약자이다. 보면 알겠지만 보통 java에서 package를 정의할 때 쓰는 방식이고 이 팩키지를 jar로 묶어서 cos.jar라고 배포를 하는 것이다. cos.jar의 페이지에서 cos-05Nov2002.zip 를 다운로드 가능하다.(파일명에서 보아 알겠지만 2002년 11월이 가장 최신판이다  ㅡ..ㅡ) 다운받은 파일안에 lib에 있는 cos.jar를 WAS쪽에 넣어도 되고 해당 프로젝트의 WEB-INF안에 lib안에 넣어도 된다. cos.jar를 사용한다고 했지만 정확히는 cos.jar의 MultipartRequest를 이용해서 파일을 받는다.

    view plaincopy to clipboardprint?
    1. <%@ page import="com.oreilly.servlet.MultipartRequest" %>    
    2. <%   
    3.      int maxPostSize = 10 * 1024 * 1024; // 10MB   
    4.      saveDirectory = config.getServletContext().getRealPath("/upload");   
    5.      MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize, "utf-8");   
    6.   
    7.      Enumeration formNames=multi.getFileNames();  // 폼의 이름 반환   
    8.   
    9.      String fileInput = "";   
    10.      String fileName = "";   
    11.      String type = "";   
    12.      File fileObj = null;   
    13.      String originFileName = "";       
    14.      String fileExtend = "";   
    15.      String fileSize = "";   
    16.   
    17.      while(formNames.hasMoreElements()) {   
    18.           fileInput = (String)formNames.nextElement();                // 파일인풋 이름   
    19.           fileName = multi.getFilesystemName(fileInput);            // 파일명   
    20.           if (fileName != null) {   
    21.                type = multi.getContentType(fileInput);                   //콘텐트타입       
    22.                fileObj = multi.getFile(fileInput);                             //파일객체   
    23.                originFileName = multi.getOriginalFileName(fileInput);           //초기 파일명   
    24.                fileExtend = fileName.substring(fileName.lastIndexOf(".")+1); //파일 확장자   
    25.                fileSize = String.valueOf(fileObj.length());                    // 파일크기   
    26.           }   
    27.      }   
    28. %>   

    위의 소스가 MultipartRequest를 이용한 파일 받기 예제이다. 소스가 그렇게 어렵지 않기 때문에 크게 어려운 부분은 없다고 생각한다. MultipartRequest에 파라미터를 넘기기 위해서 최대용량과 저장폴더의 실제경로를 미리 만들어 주고 MultipartRequest의 객체 생성을 할 때 request와 함께 넘겨준다. MultipartRequest는 아주 다양하게 오버라이딩되어 있기 때문에 전달해야하는 파라미터에 대해서는 원하는 대로 사용할 수 있다. MultipartRequest의 정의는 cos.jar쪽 페이지 에 자세하기 나와 있다.

    파일이 몇개가 넘어오든 간에 MultipartRequest에서는5번라인의 객체생성 부분에서 모두 파일이 업로드 되어 저장되고 그 뒤에 저장한 파일들의 정보를 가져오는 형태로 되어 있다. 이 말은 정보를 얻기 전에 파일 저장이 먼저 되기 때문에 파일의 어떤 정보를 검사해서 저장할지 말지를 결정하는 것이 안된다는 얘기고 저장한 다음에 검사를 해서 삭제해 주는 형태가 되어야 할 것이다.

    7번 라인에서는 Enumeration으로 multi객체로 부터 전달받은 폼의 이름을 구해온다. 9~14번에서 while루프 안에서 사용한 변수들을 초기화 하고 16번라인부터 7번에서 구해온 폼이름을 통해서 파일객체를 가져오면서 다 가져올때까지 루프를 돈다. while형태로 되어 있기 때문에 단일 파일이든 여러개의 파일이 올라오든 모두 처리가 가능하다. while문 안에서는 각 파일의 정보를 구해온다. 이렇게 구해온 정보는 보통은 Database에 넣을 목적으로 구해 올 것이며 필요한 것만 가져와서 사용하면 되겠다.

    여기서 input=file외에 다른 input에 대한 값들을 가져오려면 request.getParameter()대신에 multi.getParameter()를 사용해주면 된다. (여기서 multi는 위에 예제소스에서 만든 MultipartRequest의 객체이다.) 사용법은 동일하다.





    각자 다르겠지만 일반적으로 서버에 파일을 저장할 때는 사용자가 올린 파일명을 그대로 올리지 않는다. 이는 여러가지 이유가 있는데 jsp같은 경우는 올리지 못하게 하는게 일반적이고 올리더라도 실행되지 않도록 확장자를 날리는 등의 조치를 취함으로써 보안처리를 해준다. 또한 같은 파일명이 있을 경우에 이전파일을 덮어쓰면 안되기 때문에 같은 파일명이 있을 경우에 대한 처리를 해야하고 우리같은 경우는 한글로 된 파일명은 서버에 따라서 문제가 생길수도 읽고 띄어쓰기나 특수기호등 파일명에 대한 안정성을 보장할 수 없기 때문에 나같은 경우는 대게 영문이나 숫자의 조합으로 특정파일명을 만들어서 저장한 뒤에 디비에는 서버쪽 파일명과 초기파일명을 둘다 넣어좋고 서버쪽 파일명을 이용해서 찾고 다운할때나 보여줄때는 초기파일명을 가지고 처리한다.


    이렇게하려면 업로드할때 파일명을 바꾸어 주어야 한다. MultipartRequest객체를 생성할 때 파일명을 수정하도록 파라미터를 하나 더 주면 된다.

    MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize, "utf-8", new DefaultFileRenamePolicy());

    4번째 파라미터로 DefaultFileRenamePolicy를 넘겨준다. DefaultFileRenamePolicy는 cos.jar는 안에 존재하는 클래스이다. 파일명을 어떻게 바꾼다라는 규칙이 정해져 있는 클래스를 파라미터로 넘겨주고 파일을 업로드 할때 그 규칙에 따라 파일명이 바뀌어서 올라간다. 여기서 DefaultFileRenamePolicy는 같은 파일명이 있는지를 검사하고 있을 경우에는 파일명뒤에 숫자를 붙혀준다. ex: aaa.zip, aaa1.zip, aaa2.zip 이런 식으로...

    이 규칙에 따르면 중복에 대한처리는 할 수 있지만 그 외의 경우에는 대응할 수가 없다. 그래서 DefaultFileRenamePolicy의 규칙을 필요하다면 수정해 주어야 한다. cos.jar안에 src파일도 있으니 직접 수정하고 다시 jar로 만들어도 되고 cos.jar는 그대로 두고 따로 클래스를 만들어서 MultipartRequest객체를 생성할 때 내가 만든 클랙스를 넘겨주어도 된다.

    MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize, "utf-8", new MyFileRenamePolicy());

    MyFileRenamePolicy 클래스는 FileRenamePolicy로 부터 상속도 받아야 하고 혹시모를 다른 충돌도 막기 위해서 DefaultFileRenamePolicy와 동일하게 com.oreilly.servlet.multipart라는 팩키지를 만들어서 넣는다.

    DefaultFileRenamePolicy.java
    view plaincopy to clipboardprint?
    1. package com.oreilly.servlet.multipart;   
    2. import java.io.*;   
    3.   
    4. public class DefaultFileRenamePolicy implements FileRenamePolicy {   
    5.      public File rename(File f) {   
    6.           if (createNewFile(f)) {   
    7.                return f;   
    8.           }   
    9.           String name = f.getName();   
    10.           String body = null;   
    11.           String ext = null;   
    12.   
    13.           int dot = name.lastIndexOf(".");   
    14.           if (dot != -1) {   
    15.                body = name.substring(0, dot);   
    16.                ext = name.substring(dot);  // includes "."   
    17.           }   
    18.           else {   
    19.                body = name;   
    20.                ext = "";   
    21.           }   
    22.   
    23.           int count = 0;   
    24.           while (!createNewFile(f) && count < 9999) {   
    25.                count++;   
    26.                String newName = body + count + ext;   
    27.                f = new File(f.getParent(), newName);   
    28.           }   
    29.           return f;   
    30.      }   
    31.   
    32.      private boolean createNewFile(File f) {   
    33.           try {   
    34.                 return f.createNewFile();   
    35.           }   
    36.           catch (IOException ignored) {   
    37.                return false;   
    38.           }   
    39.      }   
    40. }   

    이게 기존에 있는 DefaultFileRenamePolicy.java의 소스이다. 소스는 처음에는 좀 어색하지만 그리 어렵지 않다. rename()이 처음 호출되는데 createNewFile()를 실행해서(5라인) 파일생성이 가능하면 그대로 끝을 내고 생성을 못했으면 파일명의 점(.)을 기준으로 파일명과 확장자를 나누어서 저장한다.(13라인) 그리고 파일생성이 가능할 때까지(중복파일이 없을때까지) 루프를 돌아서 파일명+숫자+확장자형태로 다시 만들어서 리턴한다.(23라인)



    MyFileRenamePolicy.java
    view plaincopy to clipboardprint?
    1. package com.oreilly.servlet.multipart;   
    2. import java.io.*;   
    3. import java.util.Date;   
    4. import java.text.SimpleDateFormat;   
    5.   
    6. public class AlmapFileRenamePolicy  implements FileRenamePolicy {   
    7.      public File rename(File f) {   
    8.           long currentTime = System.currentTimeMillis();   
    9.           SimpleDateFormat simDf = new SimpleDateFormat("yyyyMMddHHmmss");   
    10.           int randomNumber = (int)(Math.random()*100000);   
    11.        
    12.           String uniqueFileName = "" + randomNumber + simDf.format(new Date(currentTime));   
    13.   
    14.           String name = f.getName();   
    15.           String body = null;   
    16.           String ext = null;   
    17.   
    18.           int dot = name.lastIndexOf(".");   
    19.           if (dot != -1) {   
    20.                body = name.substring(0, dot);   
    21.                ext = name.substring(dot);  // includes "."   
    22.           }   
    23.           else {   
    24.                body = name;   
    25.                ext = "";   
    26.           }   
    27.        
    28.           String tempName = uniqueFileName + ext;   
    29.           f = new File(f.getParent(), tempName);   
    30.           if (createNewFile(f)) {   
    31.                return f;   
    32.           }   
    33.   
    34.           int count = 0;   
    35.           while (!createNewFile(f) && count < 9999) {   
    36.                count++;   
    37.                String newName = uniqueFileName + "_" + count + ext;   
    38.                f = new File(f.getParent(), newName);   
    39.           }   
    40.   
    41.           return f;   
    42.      }   
    43.   
    44.      private boolean createNewFile(File f) {   
    45.           try {   
    46.                return f.createNewFile();   
    47.           }   
    48.           catch (IOException ignored) {   
    49.                return false;   
    50.           }   
    51.      }   
    52. }   

    새로 만든 파일 명명규칙인 MyFileRenamePolicy이다. 기존에 있던 것에서 파일명명하는 방식만 약간 바꾼 것이다. 앞에것보다는 약간 길어졌지만 간단하다. 파일중복을 줄이기 위해서 5자리짜리 랜덤수와 현재날짜시간의 조합으로 유니크한파일명을 만든다(12라인) 앞에것과 동일하게 점(.)을 기준으로 파일명과 확장자를 분리하고(18라인) 분리한파일명대신 유니크한 파일명과 확장자를 조합해서 임시로 파일명을 만든 다음에 파일생성을 시도한다.(28라인) 성공하면 그대로 끝내고 실패하면 루프를 돌면서 파일생성가능할때까지 카운트를 올려서 유니크한 파일명_카운트.확장자형태가 되도록 만든다.


    이렇게 모든 파일은 랜덤수+현재시간.확장자의 형태로 만든다.여기서는 파일명으로 수자만 사용했지만 원하는 규칙대로 만들어서 클래스를 구성해 주면 그에 맞게 리네임을 할 수 있다.
    크리에이티브 커먼즈 라이센스
    Creative Commons License
    이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-동일조건변경허락 2.0 대한민국 라이센스 에 따라 이용하실 수 있습니다.

    반응형
    저작자표시 비영리 변경금지 (새창열림)
    Posted by Edward. K

    JavaScript 암호화,복호화

    Programming/JavaScript 2009. 6. 29. 16:58
    반응형


    [JS] 자바스크립트 암호화 및 복호화   [2004년 작성된 문서..]
           http://blog.naver.com/devstory/120008203476

     * 암호화, 복호화 ( encode, decode ) 파일 첨부

    scrDeEn.zip

    - 암호화 방법( Microsoft script Encoder 도움말 ) 

    script Encoder는 스크립팅 코드만 인코딩합니다. 이때 파일에서 변경하지 않은 다른 내용들은 일반 텍스트로
    나타납니다. script Encoder를 사용하려면 일반적인 방법으로 스크립트를 개발하고 디버그한 다음,
     최종 스크립트를 인코딩하십시오. script Encoder는 원본 코드에 들어 있는 표식을 사용하여 인코딩 시작점을
    식별합니다.

    Visual Basic® scripting Edition(VBscript)을 사용할 때 다음 예제와 같이 인코딩 표식을 사용하여
    일반 텍스트 저작권 정보를 표시할 수 있습니다.

    <scRIPT LANGUAGE="VBscript">
    'Copyrightⓒ 1998. XYZ Productions. All rights reserved.
    '**Start Encode**
    ' 여기에 사용자 코드를 작성합니다.
    </scRIPT> 

    Jscript®를 사용할 때 인코딩 표식은 다음과 같습니다.

    <scRIPT LANGUAGE="Jscript">
    //Copyrightⓒ 1998. ZYX Productions. All rights reserved.
    //**Start Encode**
    // 여기에 사용자 코드를 작성합니다.
    </scRIPT>

     script Encoder를 실행하면 스크립트 블록 내의 시작 표식 앞에 있는 부분은 인코딩되지 않고 스크립트 볼록의
    나머지 부분은 모두 인코딩됩니다. 그러므로 시작 표식을 생략하면 전체 스크립트 블록이 인코딩되고,
    스크립트 블록 끝에 시작 표식이 있으면 전혀 인코딩되지 않습니다.

    인코딩한 뒤에 <scRIPT> 태그에 들어 있는 언어 지시자가 변경되는 것에 유의하십시오.

    VBscript를 사용할 때 새 지시자는 다음과 같습니다.  

    <scRIPT LANGUAGE="VBscript.Encode">

    Jscript(또는 Javascript)를 사용할 때 새 지시자는 다음과 같습니다.
    <scRIPT LANGUAGE="Jscript.Encode">

    script Encoder는 MS-DOS 명령줄이나 다음과 같이 실행 대화 상자에서 실행합니다.
    SRCENC [switches] inputfile outputfile

    이 유틸리티의 구문은 script Encoder 구문에 설명되어 있습니다.
    쉽게 수정하거나 볼 수 없도록 스크립트 원본 코드를 인코딩합니다.

    SCRENC [/s] [/f] [/xl] [/l defLanguage ] [/e defExtension] inputfile outputfile  

    요소 설명
    /s 선택적인 요소. 이 스위치를 사용하면 script Encoder를 실행할 때 화면에 출력 메시지가 표시되지 않습니다. 생략하면 기본적으로 상세한 출력 메시지가 표시됩니다.
    /f 선택적인 요소. 출력 파일이 입력 파일을 덮어씁니다. 이 요소를 사용하면 입력 원본 파일을 더 이상 사용할 수 없습니다. 생략하면 입력 원본 파일이 보존됩니다.
    /xl 선택적인 요소. @language 지시어가 .ASP 파일의 맨 앞부분에 추가되지 않습니다. 생략하면 모든 .ASP 파일에 @language 지시어가 추가됩니다.
    /l defLanguage 선택적인 요소. 인코딩할 때 사용할 기본 스크립트 언어(Jscript® 또는 VBscript)를 지정합니다. 인코딩하는 파일의 스크립트 블록(언어 특성이 없음)은 지정된 이 언어로 인코딩됩니다. 생략하면 HTML 페이지와 스크립트릿에서는 Jscript가 기본 스크립트 언어가 되고 .ASP 파일에서는 VBscript가 기본 스크립트 언어가 됩니다. 일반 텍스트 파일에서는 파일 확장명(.js 또는 .vbs)에 따라 기본 스크립트 언어가 정해집니다.
    /e defExtension 선택적인 요소. 입력 파일의 파일 형식을 지정합니다. 입력 파일의 확장명으로 파일 형식을 결정할 수 없을 때 즉, 입력 파일의 확장명이 인식 가능한 확장명은 아니지만 파일의 내용이 인식 가능한 형식일 때, 이 스위치를 사용하여 파일 형식을 지정합니다. 이 요소의 기본값은 없습니다. 파일 확장명으로 파일 형식을 알 수 없을 때 이 요소를 지정하지 않으면 script Encoder에서 해당 파일이 인코딩되지 않습니다. 인식 가능한 파일 확장명은 asa, asp, cdx, htm, html, js, sct, vbs 등입니다.
    inputfile 필수적인 요소. 인코딩할 입력 파일의 이름입니다. 현재 디렉터리에 대한 상대 경로가 포함되어야 합니다.
    outputfile 필수적인 요소. 출력 파일의 이름입니다. 현재 디렉터리에 대한 상대 경로가 포함되어야 합니다.

    - 복호화 방법

    Usage: scrdec14 <infile> <outfile> [-cp codepage] [-urldec]

    Code pages can be 932 - Japanese
                      936 - Chinese (Simplified)
                      950 - Chinese (Traditional)
                      949 - Korean (Wansung)
                     1361 - Korean (Johab)
    Any other code pages don't need to be specified.
    Use -urldec to unescape %xx style encoding on the fly.
     

    infile 은 암호화 되어 있는 파일 outfile 은 복호화 되어서 나오는 파일 

    예제>D:\GUNHO\JS\ENDEC>scrdec14 test.html result.html 

    위와 같이 실행한 후 나온 결과 파일의 자바 스크립트 내용은 16진수로 되어있으므로
    unescape 로 다시 변경한 다음 alert 나 innerText 를 이용하여 소스를 확인하시면 됩니다.

     

    스크립트(Script) 코드를 암호화 시켜보자(Encode/Decode)   : 윗글과 동일하나..최근 작성된 문서
        http://www.mungchung.com/xe/lecture/4137

    스크립트 코드를 보안상 이유로 인코드를 하는 경우 있는데 아시는 분들은 다 아시겠지요 -_- 도움말 보면 왜 사용해야하는지 사용상 주의 사항들 그런것 잘 나와 있습니다. 그러니 자세한 내용은 도움말 참조하세요.

    *) 스크립트 Encode

    일단 encode 하는 프로그램 다운 받아야 합니다. http://www.microsoft.com/downloads/details.aspx?displaylang=ko&FamilyID=e7877f67-c447-4873-b1b0-21f0626a6329 여기 가서 받으면 됩니다. 다운 받아서 설치합니다. 그런후 아래 코드를 복사해서 test.html 파일로 만듭니다.

    <script language="vbscript"> ' 스크립트 Encoder 예제 sub test() msgbox ("클릭했어요") end sub </script> <input type="button" value="버튼입니다" onclick="test()">

    이 test.html 파일의 스크립트 부분을 encode 하면 도스창에서 아래와 같은 명령을 내리면 됩니다. (혹 SRCENC.exe를 못찾는 경우 Script Encoder가 설치된 디렉토리로 가서 실행시키면 됩니다.)

    SRCENC "원본파일" "내보낼파일"

    이렇게 해서 내보낸 파일의 소스를 보면 아래와 같습니다.

    <script language="VBScript.Encode"> ' 스크립트 Encoder 예제 '**Start Encode**#@~^NQAAAA==@#@&/;(PD+/D`*@#@&,P~Ps/L8K6PvE클릭했어요J*@#@&U[PkE(@#@&PQoAAA==^#~@</script> <input type="button" value="버튼입니다" onclick="test()">

    *) 스크립트 Decode

    인코딩한 파일을 test1.html 이라했을때 이 파일을 다시 decode 하는 방법은 아래 유틸을 다운받아야 합니다. http://www.virtualconspiracy.com/index.php?page=scrdec/download 이 프로그램 다운 받은 후에 도스창에서 다음과같은 명령 실행하면 인코딩된 스크립트를 디코딩 해줍니다.

    scrdec18.exe "인코딩된파일" "내보낼파일"



     

    반응형
    저작자표시 비영리 변경금지 (새창열림)
    Posted by Edward. K

    Eclipse 자동주석 설정법

    Programming/JAVA 2009. 6. 29. 10:27
    반응형


    이클립스에서 파일을 생성할때 자동으로 기본 templete 코드를 생성하기 위한 방법이다.

    클래스 생성시 주석과, 로깅처리를 자동으로 추가되도록 설정해본다.


    1. 이클립스 환경설정.
         



    2.  code templetes > New Java files


    3. Edit 버튼을 선택하고 기본 주석 설정과 로깅 처리를 위한 클래스를 임포트해준다.


    4. Code Templates > Class body  :   로그 코드를 작성한다.
       


    5.  이제 클래스를 생성해보자.



    6. 클래스를 생성해보자~!
       


    7. 클래스 생성만으로 기본적인 주석과 로그 객체 생성이 완료되었다.
       


    p.s > author 정보는  eclipse 폴더> eclipse.ini  파일에 추가한 것입니다.
             -Duser.name=<a href='http://eknote.tistory.com' target='_blank'>edward</a>


    참...쉽죠~~

    다음은 입력된 코드 템플릿입니다.

     -- New Java Files
      ${filecomment}
      /*
       * Copyright Edward by Comas.,
       * All rights reserved.
       *
       * This software is the confidential and proprietary information
       * of Comas Corp. ("Confidential Information").
       */
      ${package_declaration}

      import org.apache.commons.logging.Log;  // Logging 처리를 위한 import
      import org.apache.commons.logging.LogFactory;
      /**
       * <pre>
       * ${package_name}
       *    |_ ${file_name}
       * </pre>
       * @date : ${date} ${time}
       * @version :
       * @author : ${user}
       */
      ${typecomment}
      ${type_declaration}


    -- Class Body
     private static Log log = LogFactory.getLog(${type_name}.class);

         >   ${type_name}.class 대신에  this.getClass().getName()  을 넣어도 되겠죠~



     

    반응형
    저작자표시 비영리 변경금지 (새창열림)
    Posted by Edward. K
    이전페이지 다음페이지
    블로그 이미지

    메멘토적 기억능력을 소유한 개발자 노트.

    by Edward. K

    공지사항

      최근...

    • 포스트
    • 댓글
    • 트랙백
    • 더 보기

    태그

    • flex
    • 사업 이야기
    • android
    • 이클립스
    • 중독성게임
    • STS
    • 플래시 게임
    • tomcat
    • iBATIS
    • netbeans
    • rocketdock
    • ERwin
    • egov
    • toad
    • 개한민국
    • 캡쳐툴
    • 색상코드표
    • EkNote
    • EditPlus
    • eclipse plugin
    • 가상화폐무료
    • Flash Player
    • Jboss
    • 미네르바
    • 전자정부프레임워크
    • Eclipse
    • 컴퓨터 관리
    • Graphic
    • 이미지 편집
    • sqlgate

    글 보관함

    «   2025/12   »
    일 월 화 수 목 금 토
    1 2 3 4 5 6
    7 8 9 10 11 12 13
    14 15 16 17 18 19 20
    21 22 23 24 25 26 27
    28 29 30 31

    링크

    카테고리

    분류 전체보기 (792)
    행운이와함께 (1)
    EkNote Project (18)
    ARIS (0)
    Android (2)
    LINK (39)
    UML (9)
    Programming (154)
    Cobol (0)
    ASP (0)
    CSS (5)
    C_C++ (2)
    IBatis (2)
    JSP (3)
    JAVA (76)
    JavaScript (44)
    PHP (2)
    Utility (76)
    Protable (3)
    MobileProgram (4)
    SKT (0)
    KTF (0)
    LGT (0)
    자료들 (4)
    DB (82)
    mongoDB (0)
    MySQL (8)
    Oracle (61)
    MSSQL (4)
    Graphic (8)
    Flash (3)
    PhotoShop (3)
    SourceFactory (4)
    Collection (73)
    작가의기막힌상상력 (14)
    미소를찾아보는공간 (44)
    내심장은작동중일까 (6)
    멀더와스컬리의노트 (3)
    이건어디에사용할까 (6)
    Edward (275)
    나만 알기엔 아까워 (100)
    기억하기 위한 기록 (123)
    시선이 머무는 공간 (50)
    숨기고 싶은 이야기 (2)

    카운터

    Total
    Today
    Yesterday
    방명록 : 관리자 : 글쓰기
    Edward. K's Blog is powered by daumkakao
    Skin info material T Mark3 by 뭐하라
    favicon

    IT정리노트

    메멘토적 기억능력을 소유한 개발자 노트.

    • 태그
    • 링크 추가
    • 방명록

    관리자 메뉴

    • 관리자 모드
    • 글쓰기
    • 분류 전체보기 (792)
      • 행운이와함께 (1)
      • EkNote Project (18)
      • ARIS (0)
      • Android (2)
      • LINK (39)
      • UML (9)
      • Programming (154)
        • Cobol (0)
        • ASP (0)
        • CSS (5)
        • C_C++ (2)
        • IBatis (2)
        • JSP (3)
        • JAVA (76)
        • JavaScript (44)
        • PHP (2)
      • Utility (76)
        • Protable (3)
      • MobileProgram (4)
        • SKT (0)
        • KTF (0)
        • LGT (0)
        • 자료들 (4)
      • DB (82)
        • mongoDB (0)
        • MySQL (8)
        • Oracle (61)
        • MSSQL (4)
      • Graphic (8)
        • Flash (3)
        • PhotoShop (3)
      • SourceFactory (4)
      • Collection (73)
        • 작가의기막힌상상력 (14)
        • 미소를찾아보는공간 (44)
        • 내심장은작동중일까 (6)
        • 멀더와스컬리의노트 (3)
        • 이건어디에사용할까 (6)
      • Edward (275)
        • 나만 알기엔 아까워 (100)
        • 기억하기 위한 기록 (123)
        • 시선이 머무는 공간 (50)
        • 숨기고 싶은 이야기 (2)

    카테고리

    PC화면 보기 티스토리 Daum

    티스토리툴바