'ITWeb/개발일반'에 해당되는 글 490건

  1. 2010.10.08 Shell 에서 CURL 을 이용해 호출하기
  2. 2010.05.14 SOAP Client 예제 (using java) 1
  3. 2010.05.12 Popup Window auto resize v1.0.0
  4. 2010.05.11 XML Parser javascript class v1.0.0
  5. 2010.05.11 XMLHttpRequest javascript 용 class v1.0.0
  6. 2010.05.07 팝업 차단 alert 띄우기.
  7. 2010.04.13 모바일 브라우저 현황 - by wikipedia
  8. 2010.04.02 Mobile Web 동영상 재생.
  9. 2010.03.16 JUnit 4 - annotation 설명
  10. 2010.03.15 JSTL if 예제들

Shell 에서 CURL 을 이용해 호출하기

ITWeb/개발일반 2010. 10. 8. 18:36

요기 들어 가면.. get, post 방식으로 호출 하는 내용이 자세히 나와 있습니다.
http://curl.haxx.se/docs/httpscripting.html


[Scrap]
Online:  http://curl.haxx.se/docs/httpscripting.html
Date:    May 28, 2008
 
                The Art Of Scripting HTTP Requests Using Curl
                =============================================
 
This document will assume that you're familiar with HTML and general
networking.
 
The possibility to write scripts is essential to make a good computer
system. Unix' capability to be extended by shell scripts and various tools to
run various automated commands and scripts is one reason why it has succeeded
so well.
 
The increasing amount of applications moving to the web has made "HTTP
Scripting" more frequently requested and wanted. To be able to automatically
extract information from the web, to fake users, to post or upload data to
web servers are all important tasks today.
 
Curl is a command line tool for doing all sorts of URL manipulations and
transfers, but this particular document will focus on how to use it when
doing HTTP requests for fun and profit. I'll assume that you know how to
invoke 'curl --help' or 'curl --manual' to get basic information about it.
 
Curl is not written to do everything for you. It makes the requests, it gets
the data, it sends data and it retrieves the information. You probably need
to glue everything together using some kind of script language or repeated
manual invokes.
 
1. The HTTP Protocol
 
HTTP is the protocol used to fetch data from web servers. It is a very simple
protocol that is built upon TCP/IP. The protocol also allows information to
get sent to the server from the client using a few different methods, as will
be shown here.
 
HTTP is plain ASCII text lines being sent by the client to a server to
request a particular action, and then the server replies a few text lines
before the actual requested content is sent to the client.
 
Using curl's option --verbose (-v as a short option) will display what kind of
commands curl sends to the server, as well as a few other informational texts.
--verbose is the single most useful option when it comes to debug or even
understand the curl<->server interaction.
 
2. URL
 
The Uniform Resource Locator format is how you specify the address of a
particular resource on the Internet. You know these, you've seen URLs like
http://curl.haxx.se or https://yourbank.com a million times.
 
3. GET a page
 
The simplest and most common request/operation made using HTTP is to get a
URL. The URL could itself refer to a web page, an image or a file. The client
issues a GET request to the server and receives the document it asked for.
If you issue the command line
 
        curl http://curl.haxx.se
 
you get a web page returned in your terminal window. The entire HTML document
that that URL holds.
 
All HTTP replies contain a set of headers that are normally hidden, use
curl's --include (-i) option to display them as well as the rest of the
document. You can also ask the remote server for ONLY the headers by using the
--head (-I) option (which will make curl issue a HEAD request).
 
4. Forms
 
Forms are the general way a web site can present a HTML page with fields for
the user to enter data in, and then press some kind of 'OK' or 'submit'
button to get that data sent to the server. The server then typically uses
the posted data to decide how to act. Like using the entered words to search
in a database, or to add the info in a bug track system, display the entered
address on a map or using the info as a login-prompt verifying that the user
is allowed to see what it is about to see.
 
Of course there has to be some kind of program in the server end to receive
the data you send. You cannot just invent something out of the air.
 
4.1 GET
 
  A GET-form uses the method GET, as specified in HTML like:
 
        <form method="GET" action="junk.cgi">
          <input type=text name="birthyear">
          <input type=submit name=press value="OK">
        </form>
 
  In your favorite browser, this form will appear with a text box to fill in
  and a press-button labeled "OK". If you fill in '1905' and press the OK
  button, your browser will then create a new URL to get for you. The URL will
  get "junk.cgi?birthyear=1905&press=OK" appended to the path part of the
  previous URL.
 
  If the original form was seen on the page "www.hotmail.com/when/birth.html",
  the second page you'll get will become
  "www.hotmail.com/when/junk.cgi?birthyear=1905&press=OK".
 
  Most search engines work this way.
 
  To make curl do the GET form post for you, just enter the expected created
  URL:
 
        curl "http://www.hotmail.com/when/junk.cgi?birthyear=1905&press=OK"
 
4.2 POST
 
  The GET method makes all input field names get displayed in the URL field of
  your browser. That's generally a good thing when you want to be able to
  bookmark that page with your given data, but it is an obvious disadvantage
  if you entered secret information in one of the fields or if there are a
  large amount of fields creating a very long and unreadable URL.
 
  The HTTP protocol then offers the POST method. This way the client sends the
  data separated from the URL and thus you won't see any of it in the URL
  address field.
 
  The form would look very similar to the previous one:
 
        <form method="POST" action="junk.cgi">
          <input type=text name="birthyear">
          <input type=submit name=press value=" OK ">
        </form>
 
  And to use curl to post this form with the same data filled in as before, we
  could do it like:
 
        curl --data "birthyear=1905&press=%20OK%20" http://www.hotmail.com/when/junk.cgi
 
  This kind of POST will use the Content-Type
  application/x-www-form-urlencoded and is the most widely used POST kind.
 
  The data you send to the server MUST already be properly encoded, curl will
  not do that for you. For example, if you want the data to contain a space,
  you need to replace that space with %20 etc. Failing to comply with this
  will most likely cause your data to be received wrongly and messed up.
 
  Recent curl versions can in fact url-encode POST data for you, like this:
 
        curl --data-urlencode "name=I am Daniel" http://www.example.com
 
4.3 File Upload POST
 
  Back in late 1995 they defined an additional way to post data over HTTP. It
  is documented in the RFC 1867, why this method sometimes is referred to as
  RFC1867-posting.
 
  This method is mainly designed to better support file uploads. A form that
  allows a user to upload a file could be written like this in HTML:
 
    <form method="POST" enctype='multipart/form-data' action="upload.cgi">
      <input type=file name=upload>
      <input type=submit name=press value="OK">
    </form>
 
  This clearly shows that the Content-Type about to be sent is
  multipart/form-data.
 
  To post to a form like this with curl, you enter a command line like:
 
        curl --form upload=@localfilename --form press=OK [URL]
 
4.4 Hidden Fields
 
  A very common way for HTML based application to pass state information
  between pages is to add hidden fields to the forms. Hidden fields are
  already filled in, they aren't displayed to the user and they get passed
  along just as all the other fields.
 
  A similar example form with one visible field, one hidden field and one
  submit button could look like:
 
    <form method="POST" action="foobar.cgi">
      <input type=text name="birthyear">
      <input type=hidden name="person" value="daniel">
      <input type=submit name="press" value="OK">
    </form>
 
  To post this with curl, you won't have to think about if the fields are
  hidden or not. To curl they're all the same:
 
        curl --data "birthyear=1905&press=OK&person=daniel" [URL]
 
4.5 Figure Out What A POST Looks Like
 
  When you're about fill in a form and send to a server by using curl instead
  of a browser, you're of course very interested in sending a POST exactly the
  way your browser does.
 
  An easy way to get to see this, is to save the HTML page with the form on
  your local disk, modify the 'method' to a GET, and press the submit button
  (you could also change the action URL if you want to).
 
  You will then clearly see the data get appended to the URL, separated with a
  '?'-letter as GET forms are supposed to.
 
5. PUT
 
The perhaps best way to upload data to a HTTP server is to use PUT. Then
again, this of course requires that someone put a program or script on the
server end that knows how to receive a HTTP PUT stream.
 
Put a file to a HTTP server with curl:
 
        curl --upload-file uploadfile http://www.uploadhttp.com/receive.cgi
 
6. HTTP Authentication
 
HTTP Authentication is the ability to tell the server your username and
password so that it can verify that you're allowed to do the request you're
doing. The Basic authentication used in HTTP (which is the type curl uses by
default) is *plain* *text* based, which means it sends username and password
only slightly obfuscated, but still fully readable by anyone that sniffs on
the network between you and the remote server.
 
To tell curl to use a user and password for authentication:
 
        curl --user name:password http://www.secrets.com
 
The site might require a different authentication method (check the headers
returned by the server), and then --ntlm, --digest, --negotiate or even
--anyauth might be options that suit you.
 
Sometimes your HTTP access is only available through the use of a HTTP
proxy. This seems to be especially common at various companies. A HTTP proxy
may require its own user and password to allow the client to get through to
the Internet. To specify those with curl, run something like:
 
        curl --proxy-user proxyuser:proxypassword curl.haxx.se
 
If your proxy requires the authentication to be done using the NTLM method,
use --proxy-ntlm, if it requires Digest use --proxy-digest.
 
If you use any one these user+password options but leave out the password
part, curl will prompt for the password interactively.
 
Do note that when a program is run, its parameters might be possible to see
when listing the running processes of the system. Thus, other users may be
able to watch your passwords if you pass them as plain command line
options. There are ways to circumvent this.
 
It is worth noting that while this is how HTTP Authentication works, very
many web sites will not use this concept when they provide logins etc. See
the Web Login chapter further below for more details on that.
 
7. Referer
 
A HTTP request may include a 'referer' field (yes it is misspelled), which
can be used to tell from which URL the client got to this particular
resource. Some programs/scripts check the referer field of requests to verify
that this wasn't arriving from an external site or an unknown page. While
this is a stupid way to check something so easily forged, many scripts still
do it. Using curl, you can put anything you want in the referer-field and
thus more easily be able to fool the server into serving your request.
 
Use curl to set the referer field with:
 
        curl --referer http://curl.haxx.se http://daniel.haxx.se
 
8. User Agent
 
Very similar to the referer field, all HTTP requests may set the User-Agent
field. It names what user agent (client) that is being used. Many
applications use this information to decide how to display pages. Silly web
programmers try to make different pages for users of different browsers to
make them look the best possible for their particular browsers. They usually
also do different kinds of javascript, vbscript etc.
 
At times, you will see that getting a page with curl will not return the same
page that you see when getting the page with your browser. Then you know it
is time to set the User Agent field to fool the server into thinking you're
one of those browsers.
 
To make curl look like Internet Explorer on a Windows 2000 box:
 
        curl --user-agent "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)" [URL]
 
Or why not look like you're using Netscape 4.73 on a Linux (PIII) box:
 
        curl --user-agent "Mozilla/4.73 [en] (X11; U; Linux 2.2.15 i686)" [URL]
 
9. Redirects
 
When a resource is requested from a server, the reply from the server may
include a hint about where the browser should go next to find this page, or a
new page keeping newly generated output. The header that tells the browser
to redirect is Location:.
 
Curl does not follow Location: headers by default, but will simply display
such pages in the same manner it display all HTTP replies. It does however
feature an option that will make it attempt to follow the Location: pointers.
 
To tell curl to follow a Location:
 
        curl --location http://www.sitethatredirects.com
 
If you use curl to POST to a site that immediately redirects you to another
page, you can safely use --location (-L) and --data/--form together. Curl will
only use POST in the first request, and then revert to GET in the following
operations.
 
10. Cookies
 
The way the web browsers do "client side state control" is by using
cookies. Cookies are just names with associated contents. The cookies are
sent to the client by the server. The server tells the client for what path
and host name it wants the cookie sent back, and it also sends an expiration
date and a few more properties.
 
When a client communicates with a server with a name and path as previously
specified in a received cookie, the client sends back the cookies and their
contents to the server, unless of course they are expired.
 
Many applications and servers use this method to connect a series of requests
into a single logical session. To be able to use curl in such occasions, we
must be able to record and send back cookies the way the web application
expects them. The same way browsers deal with them.
 
The simplest way to send a few cookies to the server when getting a page with
curl is to add them on the command line like:
 
        curl --cookie "name=Daniel" http://www.cookiesite.com
 
Cookies are sent as common HTTP headers. This is practical as it allows curl
to record cookies simply by recording headers. Record cookies with curl by
using the --dump-header (-D) option like:
 
        curl --dump-header headers_and_cookies http://www.cookiesite.com
 
(Take note that the --cookie-jar option described below is a better way to
store cookies.)
 
Curl has a full blown cookie parsing engine built-in that comes to use if you
want to reconnect to a server and use cookies that were stored from a
previous connection (or handicrafted manually to fool the server into
believing you had a previous connection). To use previously stored cookies,
you run curl like:
 
        curl --cookie stored_cookies_in_file http://www.cookiesite.com
 
Curl's "cookie engine" gets enabled when you use the --cookie option. If you
only want curl to understand received cookies, use --cookie with a file that
doesn't exist. Example, if you want to let curl understand cookies from a page
and follow a location (and thus possibly send back cookies it received), you
can invoke it like:
 
        curl --cookie nada --location http://www.cookiesite.com
 
Curl has the ability to read and write cookie files that use the same file
format that Netscape and Mozilla do. It is a convenient way to share cookies
between browsers and automatic scripts. The --cookie (-b) switch automatically
detects if a given file is such a cookie file and parses it, and by using the
--cookie-jar (-c) option you'll make curl write a new cookie file at the end of
an operation:
 
        curl --cookie cookies.txt --cookie-jar newcookies.txt http://www.cookiesite.com
 
11. HTTPS
 
There are a few ways to do secure HTTP transfers. The by far most common
protocol for doing this is what is generally known as HTTPS, HTTP over
SSL. SSL encrypts all the data that is sent and received over the network and
thus makes it harder for attackers to spy on sensitive information.
 
SSL (or TLS as the latest version of the standard is called) offers a
truckload of advanced features to allow all those encryptions and key
infrastructure mechanisms encrypted HTTP requires.
 
Curl supports encrypted fetches thanks to the freely available OpenSSL
libraries. To get a page from a HTTPS server, simply run curl like:
 
        curl https://that.secure.server.com
 
11.1 Certificates
 
  In the HTTPS world, you use certificates to validate that you are the one
  you claim to be, as an addition to normal passwords. Curl supports client-
  side certificates. All certificates are locked with a pass phrase, which you
  need to enter before the certificate can be used by curl. The pass phrase
  can be specified on the command line or if not, entered interactively when
  curl queries for it. Use a certificate with curl on a HTTPS server like:
 
        curl --cert mycert.pem https://that.secure.server.com
 
  curl also tries to verify that the server is who it claims to be, by
  verifying the server's certificate against a locally stored CA cert
  bundle. Failing the verification will cause curl to deny the connection. You
  must then use --insecure (-k) in case you want to tell curl to ignore that
  the server can't be verified.
 
  More about server certificate verification and ca cert bundles can be read
  in the SSLCERTS document, available online here:
 
        http://curl.haxx.se/docs/sslcerts.html
 
12. Custom Request Elements
 
Doing fancy stuff, you may need to add or change elements of a single curl
request.
 
For example, you can change the POST request to a PROPFIND and send the data
as "Content-Type: text/xml" (instead of the default Content-Type) like this:
 
        curl --data "<xml>" --header "Content-Type: text/xml" --request PROPFIND url.com
 
You can delete a default header by providing one without content. Like you
can ruin the request by chopping off the Host: header:
 
        curl --header "Host:" http://mysite.com
 
You can add headers the same way. Your server may want a "Destination:"
header, and you can add it:
 
        curl --header "Destination: http://moo.com/nowhere" http://url.com
 
13. Web Login
 
While not strictly just HTTP related, it still cause a lot of people problems
so here's the executive run-down of how the vast majority of all login forms
work and how to login to them using curl.
 
It can also be noted that to do this properly in an automated fashion, you
will most certainly need to script things and do multiple curl invokes etc.
 
First, servers mostly use cookies to track the logged-in status of the
client, so you will need to capture the cookies you receive in the
responses. Then, many sites also set a special cookie on the login page (to
make sure you got there through their login page) so you should make a habit
of first getting the login-form page to capture the cookies set there.
 
Some web-based login systems features various amounts of javascript, and
sometimes they use such code to set or modify cookie contents. Possibly they
do that to prevent programmed logins, like this manual describes how to...
Anyway, if reading the code isn't enough to let you repeat the behavior
manually, capturing the HTTP requests done by your browers and analyzing the
sent cookies is usually a working method to work out how to shortcut the
javascript need.
 
In the actual <form> tag for the login, lots of sites fill-in random/session
or otherwise secretly generated hidden tags and you may need to first capture
the HTML code for the login form and extract all the hidden fields to be able
to do a proper login POST. Remember that the contents need to be URL encoded
when sent in a normal POST.
 
 
14. Debug
 
Many times when you run curl on a site, you'll notice that the site doesn't
seem to respond the same way to your curl requests as it does to your
browser's.
 
Then you need to start making your curl requests more similar to your
browser's requests:
 
* Use the --trace-ascii option to store fully detailed logs of the requests
   for easier analyzing and better understanding
 
* Make sure you check for and use cookies when needed (both reading with
   --cookie and writing with --cookie-jar)
 
* Set user-agent to one like a recent popular browser does
 
* Set referer like it is set by the browser
 
* If you use POST, make sure you send all the fields and in the same order as
   the browser does it. (See chapter 4.5 above)
 
A very good helper to make sure you do this right, is the LiveHTTPHeader tool
that lets you view all headers you send and receive with Mozilla/Firefox
(even when using HTTPS).
 
A more raw approach is to capture the HTTP traffic on the network with tools
such as ethereal or tcpdump and check what headers that were sent and
received by the browser. (HTTPS makes this technique inefficient.)
 
15. References
 
RFC 2616 is a must to read if you want in-depth understanding of the HTTP
protocol.
 
RFC 2396 explains the URL syntax.
 
RFC 2109 defines how cookies are supposed to work.
 
RFC 1867 defines the HTTP post upload format.
 
http://www.openssl.org is the home of the OpenSSL project
 
http://curl.haxx.se is the home of the cURL project
:

SOAP Client 예제 (using java)

ITWeb/개발일반 2010. 5. 14. 22:03
http://www.soapuser.com/client2.html

정리가 잘 된것 같아서 일단 북마킹... ㅎㅎ
첨부파일은.. 해당 사이트에서 받은 server/client 소스 코드 입니다. :)
:

Popup Window auto resize v1.0.0

ITWeb/개발일반 2010. 5. 12. 10:23

팝업창을 띄우거나 페이지내 동적인 iframe 을 삽입 하다 보면 창 크기를 조절 해야 할 때가 있지요.
팝업창의 경우
window.resizeTo 나 resizeBy 로 조절 하는데 resizeTo 는 브라우저간 표현 방식이 조금씩 달라서 사용하기 지랄 입니다.
resizeBy 의 경우 상대적인 크기로 작거나 크거나 했을 경우 그 차이만큼 조절이 가능 하니 어지간 하면 다 적용 됩니다.


frame 의 경우
쉽게 보면.. wysiwyg 에디터의 경우 frame 컨트롤을 하잖아요... 그걸 활용해서 조절 하면 됩니다.
아래 코드 중 IE 에서는 scrollHeight 를 사용하고 있고 그 이외에서는 body 에.. div 를 하나 삽입 한 후 offsetTop 으로 사용하고 있죠.
이유는.. scrollHeight 는 body 의 컨텐츠가 찾이 하는 높이가 되고.. offsetTop 은.. offsetParent 노드의 top 에서 삽입된 div 객체까지의 상대적인 거리가 되니까.. 동적으로 높이 조절이 가능하게 됩니다.

Ref. https://developer.mozilla.org/en/DOM/element.offsetTop
Ref. https://developer.mozilla.org/en/DOM/element.scrollHeight



/*
 * IFrame & Popup Window Resize Control Module
 *
 * @package
 * @path
 * @filename    resize.js
 * @author      
 * @date        2010/05/11
 *
 * Change History
 * Date         Engineer                Type        Description
 * ----------   ------------------      ---------   --------------------
 * 2010/05/11   Henry Jeong      Create      Initial Create
 */
/*
 *
 * IFrame & Popup Window Resize module object
 *
 */
var JResize = function () {};
/*
 * @param
 *    iframeid : frame id to resize
 *    popupid : popup window id to resize
 *    minHeight : resize minimize
 *    width : popup window option
 *    heigh : popup window optiont
 */
JResize.prototype.vars = {
 iframeid:"",
 popupid:"",
 minHeight:0,
 width:0,
 height:0
}
JResize.prototype.setIframeId = function (v) {
 JResize.vars.iframeid = v;
}
JResize.prototype.setPopupId = function (v) {
 JResize.vars.popupid = v;
}
JResize.prototype.setMinHeight = function (v) {
 JResize.vars.minHeight = v;
}
/*
 * iframe auto resize
 * must window.onload = JResize.setIframe;
 */
JResize.prototype.setIframe = function () {
 var iframeid = JResize.vars.iframeid;
 var iframeObj = document.getElementById(iframeid);
 var minHeight = JResize.vars.minHeight;
 var h;
 try {
  var doc = iframeObj.contentDocument || iframeObj.contentWindow.document;
  
  if (doc.location.href == 'about:blank') {
   iframeObj.style.height = minHeight+'px';
   return;
  }
  if ( /MSIE/.test(navigator.userAgent) ) {
   h = doc.body.scrollHeight;
  } else {
   var divObj = doc.body.appendChild(document.createElement('DIV'))
   h = divObj.offsetTop;
   divObj.style.clear = 'both';
   divObj.parentNode.removeChild(divObj);
  }
  if (h < minHeight) h = minHeight;
  iframeObj.style.height = h + 'px';
  setTimeout( function () {
   JResize.setIframe();
  }, 200);
 } catch (e) {
  setTimeout( function () {
   JResize.setIframe();
  }, 200);
 }
}
/*
 * popup auto resize
 */
JResize.prototype.setPopup = function () {
 var ua = navigator.userAgent;
 var w = JResize.vars.width;
 var h = JResize.vars.height;
 document.body.style.overflow='hidden';
 if ( /MSIE/.test(navigator.userAgent) ) {
  window.resizeBy(w-document.documentElement.clientWidth, h-document.documentElement.clientHeight);
 } else {
  window.resizeBy(w-window.innerWidth, h-window.innerHeight);
 }
}
JResize = new JResize();
/*
// this is frame sample code.
<iframe id="commentlist" name="commentlist" src="./frame.html" width="906" height="100"  frameborder="1" marginwidth="0" marginheight="0" scrolling="no"></iframe>
<script language="javascript">
<!--
JResize.vars.iframeid = "commentlist";
JResize.vars.minHeight = "200";
window.onload = JResize.setIframe;
//-->
</script>
// this is popup sample code.
<script type="text/javascript">
<!--
JResize.vars.width = 400;
JResize.vars.height = 246;
window.onload = JResize.setPopup;
//-->
</script>
*/
:

XML Parser javascript class v1.0.0

ITWeb/개발일반 2010. 5. 11. 12:34
XMLHttpRequest 와 더불어 유용할 것 같아서 만들었습니다.
역시 다른데 코드는 제 스타일도 아니고 읽기도 힘들고 그래서.. 후다닥 만들었다는..
recursive call 을 하기는 하지만 나름 쉽게 작성했습니다.
코드 가지고 태클은 금지.. ㅎㅎ



/*
 * XMLParser Control Module
 *
 * @package
 * @path
 * @filename    xmlparser.js
 * @author      
 * @date        2010/05/03
 *
 * Change History
 * Date         Engineer                Type        Description
 * ----------   ------------------      ---------   --------------------
 * 2010/05/03 Henry Jeong  create  initialize
 */
/*
 *
 * XMLParser module object
 *
 */
var JXmlParser = function() {
};
/*
 *
 * xml parser variables
 */
JXmlParser.prototype.vars = {
 parser : null,
 doc : null,
 xmldata : null,
 root : null,
 xml : null
}
JXmlParser.prototype.init = function() {
 if (window.DOMParser) {
  JXmlParser.vars.parser = new DOMParser();
  JXmlParser.vars.doc = JXmlParser.vars.parser.parseFromString(
    JXmlParser.vars.xmldata, "text/xml");
  JXmlParser.vars.root = JXmlParser.vars.doc.childNodes.item(0);
 } else {
  JXmlParser.vars.doc = new ActiveXObject("Microsoft.XMLDOM");
  JXmlParser.vars.doc.async = "false";
  JXmlParser.vars.doc.loadXML(JXmlParser.vars.xmldata);
  JXmlParser.vars.root = JXmlParser.vars.doc.documentElement;
 }
 JXmlParser.vars.xml = new Object();
 JXmlParser.vars.xml["length"] = JXmlParser.vars.root.childNodes.length;
}
JXmlParser.prototype.setXml2Array = function(pobj, node) {
 var len = node.length;
 if (window.DOMParser) {
  for ( var i = 0; i < len; i++) {
   if (node[i].nodeName.charAt(0) == "#") {
    continue;
   }
   pobj[i] = new Object();
   pobj[i][node[i].nodeName] = new Object();
   pobj[i][node[i].nodeName]["value"] = node[i].textContent;
   pobj[i][node[i].nodeName]["length"] = node[i].childNodes.length;
   pobj[i][node[i].nodeName]["attributes"] = new Object();
   if (node[i].attributes && node[i].attributes.length > 0) {
    var loop = node[i].attributes.length;
    for ( var j = 0; j < loop; j++) {
     pobj[i][node[i].nodeName]["attributes"][node[i].attributes[j].nodeName] = node[i].attributes[j].nodeValue;
    }
   }
   if (node[i].childNodes.length > 0) {
    JXmlParser.setXml2Array(pobj[i][node[i].nodeName],
      node[i].childNodes, node[i].childNodes.length);
   }
  }
 } else {
  for ( var i = 0; i < len; i++) {
   if (node[i].nodeName.charAt(0) == "#") {
    continue;
   }
   pobj[i] = new Object();
   pobj[i][node[i].nodeName] = new Object();
   pobj[i][node[i].nodeName]["value"] = node[i].text;
   pobj[i][node[i].nodeName]["length"] = node[i].childNodes.length;
   pobj[i][node[i].nodeName]["attributes"] = new Object();
   if (node[i].attributes && node[i].attributes.length > 0) {
    var loop = node[i].attributes.length;
    for ( var j = 0; j < loop; j++) {
     pobj[i][node[i].nodeName]["attributes"][node[i].attributes[j].nodeName] = node[i].attributes[j].text;
    }
   }
   if (node[i].childNodes.length > 0) {
    JXmlParser.setXml2Array(pobj[i][node[i].nodeName],
      node[i].childNodes, node[i].childNodes.length);
   }
  }
 }
}
JXmlParser = new JXmlParser();
/*
 * <script type="text/javascript"> <!-- var objDivDebug =
 * document.getElementById("divDebug");
 *
function run() {
 JXmlParser.vars.xmldata = "<?xml version='1.0' encoding='UTF-8'?><parser><totalcount type='number'><total>A</total><total>B</total></totalcount><items name='user' type='image'><item><seq>1</seq><id><![CDATA[jjeong****]]></id><originalImage><![CDATA[http://www.naver.com]]></originalImage><viewImage><![CDATA[http://www.naver.com]]></viewImage><thumbImage><![CDATA[http://www.naver.com]]></thumbImage><cheerMessage><![CDATA[한국어 테스트.]]></cheerMessage><register><![CDATA[20100503175621]]></register></item><item><seq>2</seq><id><![CDATA[layd****]]></id><originalImage><![CDATA[http://www.naver.com]]></originalImage><viewImage><![CDATA[http://www.naver.com]]></viewImage><thumbImage><![CDATA[http://www.naver.com]]></thumbImage><cheerMessage><![CDATA[CHEER MESSAGE]]></cheerMessage><register><![CDATA[20100503175621]]></register></item></items></parser>";
 
 JXmlParser.init();
 JXmlParser.setXml2Array(JXmlParser.vars.xml, JXmlParser.vars.root.childNodes); 
 
 objDivDebug.innerHTML += JXmlParser.vars.xml.length +  "<br>";
 objDivDebug.innerHTML += JXmlParser.vars.xml[0]["totalcount"].value +  "<br>";
 objDivDebug.innerHTML += JXmlParser.vars.xml[0]["totalcount"].attributes.type +  "<br>";
 objDivDebug.innerHTML += JXmlParser.vars.xml[0]["totalcount"].length +  "<br>";
 objDivDebug.innerHTML += JXmlParser.vars.xml[0]["totalcount"][0]["total"].value +  "<br>";
 objDivDebug.innerHTML += JXmlParser.vars.xml[0]["totalcount"][0]["total"].length +  "<br>";
 objDivDebug.innerHTML += JXmlParser.vars.xml[0]["totalcount"][1]["total"].value +  "<br>";
 objDivDebug.innerHTML += JXmlParser.vars.xml[0]["totalcount"][1]["total"].length +  "<br>";
 objDivDebug.innerHTML += JXmlParser.vars.xml[1]["items"].value +  "<br>";
 objDivDebug.innerHTML += JXmlParser.vars.xml[1]["items"].attributes.name +  "<br>";
 objDivDebug.innerHTML += JXmlParser.vars.xml[1]["items"].length +  "<br>"; 
 objDivDebug.innerHTML += JXmlParser.vars.xml[1]["items"][0]["item"] .length+  "<br>";
 objDivDebug.innerHTML += JXmlParser.vars.xml[1]["items"][0]["item"][0]["seq"] .value+  "<br>";
 objDivDebug.innerHTML += JXmlParser.vars.xml[1]["items"][0]["item"][1]["id"] .value+  "<br>";
}
 * //--> </script>
 */
*/

:

XMLHttpRequest javascript 용 class v1.0.0

ITWeb/개발일반 2010. 5. 11. 12:26
여기 저기 널린 코드들은 많은데 맘에 드는 코드가 별로 없어서 기냥 만들었습니다.
도대체 코드를 보기 힘들게 작성하는 이유는 무슨 심리 인지.. 좀 쉽게 작성 하면 어디 덧나나.. ㅡ.ㅡ;;
참고 사이트 : http://www.w3.org/TR/XMLHttpRequest/

뭐 아래 코드가 잘 짜진것도 아니지만.. 보기 쉽게 하려고 쬐금 노력은 했다는.. ㅎㅎ
이것도 보기 힘들다면.. 패스~



/*
 * XMLHttpRequest Control Module
 *
 * @package
 * @path
 * @filename    xhr.js
 * @author      
 * @date        2010/05/03
 *
 * Change History
 * Date         Engineer                Type        Description
 * ----------   ------------------      ---------   --------------------
 * 2010/05/03 Henry Jeong  create  initialize
 */
/*
 *
 * XMLHttpRequest module object
 *
 */
var JXhr = function() {
};
/*
 *
 * xmlhttprequest variables
 */
JXhr.prototype.vars = {
 xhr : null,
 onreadystatechange : null,
 onload : null,
 onerror : null,
 onresponse : null,
 contenttype : "text/xml",
 overridemimetype : "text/xml",
 method : "GET",
 callUrl : "",
 async : true,
 header : [], // setRequestHeader
 responsedata : "XML", // responseText, responseXML
 params : ""
}
JXhr.prototype.init = function() {
 if (window.XMLHttpRequest) {
  JXhr.vars.xhr = new XMLHttpRequest();
  JXhr.vars.xhr.onreadystatechange = JXhr.vars.onreadystatechange;
 } else if (window.ActiveXObject) {
  try {
   JXhr.vars.xhr = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (e) {
   JXhr.vars.xhr = false;
  }
  if (JXhr.vars.xhr) {
   JXhr.vars.xhr.onreadystatechange = JXhr.vars.onreadystatechange;
  }
 }
}
JXhr.prototype.open = function() {
 var openUrl = JXhr.vars.callUrl;
 if (JXhr.vars.method == "GET") {
  if (JXhr.vars.params != "") {
   openUrl += "?" + JXhr.vars.params;
  }
 }
 JXhr.vars.xhr.open(JXhr.vars.method, openUrl, JXhr.vars.async);
}
JXhr.prototype.send = function() {
 switch (JXhr.vars.method) {
 case "GET":
  JXhr.vars.xhr.send(null);
  break;
 case "POST":
  JXhr.vars.xhr.setRequestHeader("Content-type",
    "application/x-www-form-URLencoded");
  JXhr.vars.xhr.setRequestHeader("Content-length",
    JXhr.vars.params.length);
  JXhr.vars.xhr.setRequestHeader("Connection", "close");
  JXhr.vars.xhr.send(JXhr.vars.params);
  break;
 }
}
JXhr = new JXhr();
/*
 * <script type="text/javascript"> <!-- function getReadyStateChage () { if (
 * JXhr.vars.xhr.readyState == 4 ) { if ( JXhr.vars.xhr.status == 200 ||
 * JXhr.vars.xhr.statusText == "OK" ) { JXhr.vars.onresponse(); } else {
 * document.getElementById("divDebug").innerHTML = JXhr.vars.xhr.statusText + "<br>" +
 * document.getElementById("divDebug").innerHTML; } } }
 *
 * function getResponseData () { if ( JXhr.vars.responsedata == "XML" ) {
 * JXhr.vars.xhr.responseXML; } else { JXhr.vars.xhr.responseText; } }
 *
 * function run() { JXhr.vars.onreadystatechange = getReadyStateChage;
 * JXhr.vars.onresponse = getResponseData; JXhr.vars.method = "GET";
 * JXhr.vars.callUrl = "http://HOSTNAME/test.txt";
 * JXhr.vars.async = true; JXhr.vars.responsedata = "TEXT"; JXhr.vars.params =
 * "";
 *
 * JXhr.init(); JXhr.open(); JXhr.send(); } //--> </script>
 */

:

팝업 차단 alert 띄우기.

ITWeb/개발일반 2010. 5. 7. 20:31
내용에 오류가 있어서 수정 합니다.
크롬이 좀 문제가 있더군요.
크롬의 경우 팝업창을 차단 하기는 하지만 내부적으로 차단된 팝업창이 모두 로딩 된 상태로 유지 되기 때문에 모든 요소에 접근이 가능 하더군요.
왜 이렇게 만들었는지 짧은 생각으로는 사실 좀 이해가 안가긴 합니다.

var objWin = window.open(URL, WINDOWNAME, OPTIONS);
 
 if ( navigator.userAgent.indexOf("Chrome") > -1 ) {
   // chrome 의 경우 최초 한번은 감지가 가능 하나 두번째 부터는 이미 팝업창이 로딩된 상태이기 때문에 감지가 안됩니다.
 } else {
  // FF, IE, Safari, Opera 감지 가능
  if( typeof(win) == "undefined" || win == null || typeof(win.name) == "undefined"){
   alert("팝업 차단됨");
  }
 }

Chrome 의 경우 팝업차단 감지를 완벽하게 하는 방법을 아시는 분은 정보 공유 좀 부탁 드려요.. ^^;

Tip.
팝업차단은 사용자에 의한 1차 클릭과 액션에 의한건 모두 허용 됩니다.
다만 사용자의 1차 액션이후에 자동으로 발생 하게 되는 액션에 대해서는 모두 차단 됩니다.
역시 사용자의 액션이 아닌 자동으로 발생 하게 되는 액션에 대해서도 모두 차단 됩니다.

 



window.open 을 사용 하다 보면.. popup block 으로 정상적인 실행이 안될 때가 있죠..
이런 경우 popup block 에 예외 항목 등록을 해 달라는 alert 을 띄워 주면 단편적인 방법으로는 해결을 할 수 있을 듯 합니다.

각 브라우저 별로 popup block 방법이 좀 다릅니다.
아래 조건절 순서에 맞게 등록 하시면 거의 대부분 브라우저에서 alert 메시지를 띄울 수 있습니다.

테스트 브라우저 : IE, FF, CHROME, SAFARI, OPERA

var objWin = window.open(URL, WINDOWNAME, OPTIONS);

if ( typeof(objWin) == "undefined" ||
    objWin == null ||
    typeof(objWin.name) == "undefined" ||
    typeof(objWin.document.READATTR) == "undefined" ) {
    alert("팝업이 차단 되었습니다. \n ABCD.COM을 등록해 주세요.");
}

여기서 typeof(objWin.document.READATTR) 이 부분은 chrome 때문에 들어간 부분 입니다.
실제 chrome 에서는 objWin 이 object로, objWin.name 이 string 으로 objWin.document 가 object 로 return 해줍니다.
즉 window 객체는 가지고 있으나 실제 페이지 로딩은 되지 않았기 때문에 해당 페이지내 elements 나 attributes 를 read 하면 undefined 로 떨어집니다.
꼭 이렇게 해야 하는건 아니지만 이런 식으로 하면 된다 정도로 이해 하시면 될 것 같내요.. ㅎㅎ

위 코드는 팝업차단이 설정된 경우에만 테스트 된 코드 입니다.
팝업 차단이 해제된 경우에는 아직 테스트를 못한 코드이니 ㅎㅎ 감안하셔서 보세요.
:

모바일 브라우저 현황 - by wikipedia

ITWeb/개발일반 2010. 4. 13. 11:34
원본글 : http://en.wikipedia.org/wiki/Mobile_browser


Default browsers used by major mobile phone and PDA vendors

Browser↓ Creator↓ FOSS↓ Current layout engine↓ Software license↓ Notes↓
jB5 Browser Comviva No jB5 Browser Engine proprietary Linux, Symbian, Windows Mobile, and Brew platforms. jB5 Profiles addresses all segments of phones - Feature Phone and Smartphone.
Polaris browser 6 Series [|Infraware Inc] No Lumi proprietary Nokia, Samsung, LG Electronics, KYOCERA and other Smartphone and cellular phone in USA, China, Korea, etc
Polaris browser 7 Series [|Infraware Inc] No WebKit proprietary Nokia, Samsung, LG Electronics, KYOCERA and other Smartphone and cellular phone in USA, China, Korea, etc
Kindle Basic Web Amazon.com No NetFront proprietary -
Android browser Google Yes WebKit Apache 2.0 and GPL v2 -
WebOS Browser Palm No Webkit proprietary -
BlackBerry Browser Research in Motion No Mango proprietary -
Blazer Palm No NetFront[citation needed] proprietary installed on all newer Palm Treos and PDAs
Firefox for mobile Mozilla Yes Gecko MPL 1.1 or later, GNU GPL 2.0 or later, GNU LGPL 2.1 or later Currently released for Nokia Maemo and in development for Android
Internet Explorer Mobile Microsoft No - proprietary -
Iris Browser Torch Mobile Inc. ? WebKit proprietary Acquired by Research in Motion - No longer supports Windows Mobile or Linux
Myriad Browser (Previously Openwave Mobile Browser) Myriad Group No Fugu (Next version to useWebKit)[5] proprietary Acquired from Openwave in 2008
NetFront ACCESS Co., Ltd. No NetFront proprietary -
Nokia Series 40 Browser Nokia No WebKit[6] proprietary -
Obigo Browser Obigo AB No - proprietary 100% owned by Teleca AB
Opera Mobile Opera Software No Presto proprietary Capable of reading HTML and reformat for small screens, installed on many phones
PlayStation Portable web browser Sony No NetFront proprietary
Safari Apple Inc No WebKit proprietary on iPhone and iPod Touch
Skyfire Mobile Browser Skyfire No Gecko proprietary Renders Flash 10, Ajax and Silverlight content. Currently supports Windows Mobile 5/6.x,Symbian S60 3rd & 5th Edition platforms (Touch/Non-Touch).
NetSailor Browser Fantalog Interactive No proprietary Convergence Web Browser for the expression of Multi-media in Korea
uZard Web Logicplant Co., Ltd. No MoRDAC (Mobile oriented Remote Display and Control) proprietary on Samsung, LG Electronics and other smartphones and cellular phones in Korea
Vision Mobile Browser Novarra ? proprietary ? -
Web Browser for S60 Nokia ? WebKit ? -
:

Mobile Web 동영상 재생.

ITWeb/개발일반 2010. 4. 2. 13:56
얼마전 테스트 할 내용이 있어서.. iphone 과 옴니아2 에서 테스트를 한 내용입니다.
모바일 웹 서비스의 경우 동영상 재생을 어떻게 할까.. 궁금 하여 테스트를..

미디어 서버가 없기때문에 다운로드 방식으로만 테스트를 진행했습니다.
이럴경우 데이터요금이 엄청 많이 나올수 있다는 점.. 일반 사용자들에게 충분히 알려줘야 할 듯 합니다.


IPHONE 에서의 영상재생 방법

mp4, mov 등의 mpeg4 나 h.264 로 인코딩 된 파일이면 영상 재생이 가능 합니다.
제가 영상관련해서 전문가는 아니기 떄문에 자세한건.. 패스~

웹 소스코드내에 아래와 같이 <a> 태그를 이용해서 링크만 걸면 다운로드 형태로 영상 재생이 가능 합니다.
아주 쉽죠..

MOV : <a href='http://movies.apple.com/media/en/iphone/2009/tours/apple-iphone3gs-guided_tour-en-20090629_320x180.mov?width=320&height=180'>영상보기</a>
M4V : <a href='http://..../iphone.m4v'>영상보기</a>
MP4 : <a href='http://..../iphone2.mp4'>영상보기</a>


옴니아2 에서 영상재생 방법

wmv 등의 미디어플레이어에서 재생 가능한 파일이면 영상 재생이 가능 합니다.
iphone 과 다르게 http의 다운로드 형태로 진행을 하게 되면 미디어 플레이어로 재생이 될 때도 있고 안될때도 있고 상황에 따라 다르게 동작을 합니다.

웹 소스코드내에 아래와 같이 <a> 태그를 이용하고 protocol 을 http 가 아닌 rtsp protocol 로 링크를 작성 하시면 영상 재생이 가능 합니다.

RTSP WMV : <a href='rtsp://..../winmo.wmv'>영상보기</a>

단말기에 flash 사용이 가능한 브라우저가 탑재되어 있다면 flash player 에 FLV 파일로 웹페이지내 embeded 형태로 영상재생도 가능 합니다.
이 방법은 iphone 에서는 안되는 방법이니 참고하세요... (이미 다 아시겠지만)

:

JUnit 4 - annotation 설명

ITWeb/개발일반 2010. 3. 16. 17:00
@Test annotation
Test Case 를 만들어 줍니다. (선언)
 

@Test

public void blahMethod() {
    String result = "blah";

    assertEquals("blah", result);

}


@Before & @After annotation

각각 setup 과 tearDown method 를 위한 annotation

@Before

public void blahBeforeTest() {
    blah = new Blah();

}

@After

public void blahAfterTest() {
    blah = null;

}


@BeforeClass & @AfterClass
@BeforeClass : test case 수행 이전에 한번 실행, @AfterClass : test case 수행 후 한번 실행

@BeforeClass

public void blahBeforeTest() {
}

@AfterClass

public void blahAfterTest() {

}


@Ignore
Test Case 수행을 무시


@기타
@Ignore("무시이유작성")
@Test(timeout = 1000) : 시정한 시간이 경과 하면 test fail. (miiseconds)


사용하면 편한 mock 객체
- easymock
- mockito
:

JSTL if 예제들

ITWeb/개발일반 2010. 3. 15. 18:27


JSTP core tag:if
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
<head><title>Using the Core JSTL tags</title></head>
<body>
<h2>Here are the available Time Zone IDs on your system</h2>
<jsp:useBean id="zone" class="com.java2s.ZoneWrapper" /> 
<jsp:useBean id="date" class="java.util.Date" /> 

<c:if test="${date.time != 0}" >

    <c:out value="Phew, time has not stopped yet...<br /><br />" escapeXml="false" />

</c:if>

<c:set var="zones" value="${zone.availableIDs}" scope="session" />

    <c:forEach var="id" items="${zones}">

        <c:out value="${id}<br />" escapeXml="false" />


    </c:forEach>

</body>
</html>
// Save the ZoneWrapper.class into WEB-INF/classes/com/java2s
//ZoneWrapper.java

package com.java2s;           


import java.util.TimeZone;

public class ZoneWrapper {

  public ZoneWrapper() {
  }

  public String[] getAvailableIDs() {

    return TimeZone.getAvailableIDs();

  }

}



JSTL RT If
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jstl/core-rt" prefix="c-rt" %>
<html>
  <head>
    <title>If Caseless</title>
  </head>

  <body>
    <c:set var="str" value="jStL" />

    <jsp:useBean id="str" type="java.lang.String" />

    <c-rt:if test='<%=str.equalsIgnoreCase("JSTL")%>'> They are
    equal</c-rt:if>
  </body>
</html>




JSTL If Else
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
  <head>
    <title>Using Choose,Otherwise and When</title>
  </head>

  <body>
    <c:if test="${pageContext.request.method=='POST'}">Ok, we'll
    send 
    <c:out value="${param.enter}" />

    <c:choose>
      <c:when test="${param.enter=='1'}">pizza.
      <br />
      </c:when>

      <c:otherwise>pizzas.
      <br />
      </c:otherwise>
    </c:choose>
    </c:if>

    <form method="post">Enter a number between and 5:
    <input type="text" name="enter" />

    <input type="submit" value="Accept" />

    <br />
    </form>
  </body>
</html>




JSTL If No Body
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
  <head>
    <title>If with NO Body</title>
  </head>

  <body>
    <c:if test="${pageContext.request.method=='POST'}">
    <c:if test="${param.guess=='5'}" var="result" />

    I tested to see if you picked my number, the result was 
    <c:out value="${result}" />
    </c:if>

    <form method="post">Guess what number I am thinking of?
    <input type="text" name="guess" />

    <input type="submit" value="Try!" />

    <br />
    </form>
  </body>
</html>



If with Body
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
  <head>
    <title>If with Body</title>
  </head>

  <body>
    <c:if test="${pageContext.request.method=='POST'}">
      <c:if test="${param.guess=='5'}">You guessed my number!
      <br />

      <br />

      <br />
      </c:if>

      <c:if test="${param.guess!='5'}">You did not guess my number!
      <br />

      <br />

      <br />
      </c:if>
    </c:if>

    <form method="post">Guess what number I am thinking of?
    <input type="text" name="guess" />

    <input type="submit" value="Try!" />

    <br />
    </form>
  </body>
</html>

: