java

반응형

 

정상적으로 실행되던 톰켓에서 아래와 같은 오류를 뱉어 낼 경우가 간혼 있다.

Setting property 'source' to 'org.eclipse.jst.jee.server:프로젝트명' did not find a matching property.

그럴 경우 톰캣 설정에 Server Option 탭에 아래와 같은 설정 후 재기동.

 


 


반응형

'Programming > Java' 카테고리의 다른 글

[Java] Collection sort  (0) 2016.01.07
[Java] GMT/UTC 날짜 변환  (1) 2015.04.08
올바른 eqals() 사용법  (0) 2014.02.07
[Java] split 문자열 나누기  (0) 2014.02.05
java e.printStackTrace 로그 남기기  (0) 2014.01.17

[C#] short url 생성(bit.ly)

2014. 2. 13. 13:16
반응형
  • C# bit.ly API 연동 방법

SNS를 연동하다 보면 url에 파라미터가 길게 늘어진 url이 보기 거슬릴때가 있다.  

bit.ly를 활용한 long url을 short url로 make해주는 api가 있는데 매우 효율적인 거 같다. 

다만, 일별 쿼터 제한이 있어 동적으로 사용할 경우 제한 횟수 이상의 요청은 원본 URL로 처리가 됨.

사용한 방식은 클라이언트에서 ajax로 bit.ly api를 호출하고 리턴 받은 short url이 쉐어되도록 개발을 진행.. 우선 개발을 하려면 bit.ly 사이트에서 계정을 발급 받아야 함. 

-share.js 

자바스크립트로 short url 생성 방식

<script>

function facebook_sharer(sharer_title, content_title, sharer_URL) {
    sharer_URL = fn_bitly(sharer_URL);
    var sharer_str = encodeURIComponent(sharer_title.replace(/#/gi, "") + content_title);
    var sharer_url = encodeURIComponent(sharer_URL);
    window.open("http://www.facebook.com/sharer.php?u=" + sharer_url + "&t=" + sharer_str, "facebook_sharer", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=800,height=600");
}

function url_sharer(sharer_URL) {
    sharer_URL = fn_bitly(sharer_URL);
    bResult = window.clipboardData.setData("Text", sharer_URL);
    if (bResult) alert('복사되었습니다. 블로그에서 붙여넣기(Ctrl+V)를 이용하세요.');
}

//Short Url Maker
function fn_bitly(longUrl) {
    var shortUrl = "";
    if (longUrl != "") {
        $J.ajax({
            url: '/ajax/bitlyToJson.aspx', //bit.ly api로 다이렉트로 호출해서 short url을 받아도 무방.
            type: 'POST',
            dataType: 'json',
            data: {
                longUrl: longUrl
            },
            timeout: 1000,
            async: false,
            error: function(xhr) {
                //alert('xhr (' + xhr.status + ':'+ xhr.statusText + ':' + xhr.responseText + ')');
            },
            success: function(response) {
                _jsonObject = response.data;
                shortUrl = _jsonObject.url;
            }
        });
        if (shortUrl == "") shortUrl = longUrl;
    }
    return shortUrl;
}

</script>
-bitlyToJson.cs

c# 에서 short url 생성 방식
 

/******************************************************************************
 *  제  목 : bitlyToJson
 *  작성자 : 이종필
 *  작성일 : 2012-11-08
 *  설  명 : Long Url -> Short Url로 Json 리턴
 ******************************************************************************/

#region shortUrl 생성
    ///    /// https://bitly.com/ 사이트에서 발급
    /// format : json
    /// apiKey : R_b7b8ddaf4734eba87237d5ad*******
    /// login : leejon****
    ///    
    private void MakeShorURL(string longurl)
    {
        StringBuilder sb = new StringBuilder();

        //base
        sb.Append(@"http://api.bit.ly/v3/shorten?login=leejon****l&apiKey=R_b7b8ddaf4734eba87237d5ad5*****&format=json&longUrl=");
        //server page
        sb.Append(Server.UrlEncode(longurl));

        // Make Short URL
        WebClient client = new WebClient();
        string shorturl = client.DownloadString(new Uri(sb.ToString()));

        Response.Write(shorturl);
    }

#endregion
결과는 아래와 같이 JSON, XML 데이타로 리턴된다. 
호출하는 데이타 format (json, xml) 파라미터로 제어 가능.
 
-JSON
 
{ "status_code": 200, "status_txt": "OK", "data": { "long_url": "http:\/\/www.naver.com\/", "url": "http:\/\/bit.ly\/YNBfGD", "hash": "YNBfGD", "global_hash": "md7fw", "new_hash": 0 } } 
 
-XML
<response>
 <status_code>200</status_code>
 <status_txt>OK</status_txt>
 <data>
  <url>http://bit.ly/YNBfGD</url>
  <hash>YNBfGD</hash>
  <global_hash>md7fw</global_hash>
  <long_url>http://www.naver.com/</long_url>
  <new_hash>0</new_hash>
 </data>
</response>

 

반응형
반응형
e.printStachTrace 로그

e.printStachTrace 로그 JAVA 코딩 시 가장 많이 사용하는 코드로 예외 메시지 출력을 위해 사용한다.

try {   // ... } catch(Exception e){    e.printStackTrace(); }
printStackTrace() 외에도 printStackTrace(PrintWriter writer)도 존재하고 printStackTrace(PrintStream s)
역시 존재하기 때문에 stackTrace 의 내용을 파일 등에 남기는 것은 그리 어려운 일이 아니다. 
하지만 Log4J 등을 사용하거나 별도로 자신이 만든 로그라이브러리등을 사용할때는, 이를테면 logger.error(e.printStackTrace()); 이런식으로 사용할 수가 없기 때문에, StackTrace 의 내용을 얻어야 하는데... getMessage() 또는 getLocalinzedMessage()를 사용할 수도 있지만 StackTrace에 비해서는 디버깅 정보가 약간 빈약하기 때문에 적절하지 못하다. 
JDK 1.4부터 getStackTrace() 라는 메소드가 추가되었는데 이 메소드는 StackTraceElement의 배열을 리턴해준다. 
따라서 이를 이용해서 아래와 같은 식으로 처리를 해주면 종종 쓸만하다.

 

try {    // ... } catch(Exception e){    StackTraceElement[] elem = e.getStackTrace();    for ( int i = 0; i < elem.length; i++ )       logger.error(elem[i]); }

 

반응형
반응형

JAVA ImageIO 객체 활용

ImageIO.write() 메서드 중 파일로 이미지를 생성하는 예제이다.

static boolean write(RenderedImage im, String formatName, File output)
String imagePath = "이미지경로..";
BufferedImage image = null;

//이미지를 읽어와서 BufferedImage에 넣는다.
'URL imgURL = getClass().getResource(imagePath);
'image = ImageIO.read(imgURL);
int width = image.getWidth();
int height = image.getHeight();

//파일명 자르기
String fileNm = imagePath.substring(imagePath.lastIndexOf("/") + 1);
try {
    // 저장할 이미지의 크기와 타입을 잡아줌.
    BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
    bufferedImage.createGraphics().drawImage(image, 0, 0, this);

    // 해당경로에 이미지를 저장함.
    ImageIO.write(bufferedImage, "jpg", new File("C:/saveImage/" + fileNm));
} catch(Exception e) {
    e.printStackTrace();
}
반응형
반응형
java.lang.IllegalArgumentException: taglib definition not consistent with specification version 
최신버전에 이클립스를 사용할 경우 나타나는 현상. 
web.xml의 taglib 위 아래로 jsp-config 태그로 감싸준다.

  
    http://java.sun.com/jstl/core
    /WEB-INF/tld/c.tld
  


반응형

+ Recent posts

반응형