Javascript 로 홈페이지 즐겨찾기 추가 버튼 및 시작페이지로 등록하기

 

1. 즐겨찾기

 

//즐겨찾기 스크립트
function bookmark_add() {
     bookmark_url  = "도메인입력";
     bookmark_name = "홈페이지 타이틀";
    
     try {
      window.external.AddFavorite(bookmark_url,bookmark_name);
     } catch(e) {
      alert('이 브라우저는 즐겨찾기 추가 기능을 지원하지 않습니다.');
      return false;
     }
 }

 

적용은 아래와 같이..
 <a href="javascript: bookmark_add();">즐겨찾기 추가</a>

 


 2. 시작페이지로


<a href="#" onClick="this.style.behavior='url(#default#homepage)';this.setHomePage('도메인입력');">시작페이지로</a>

 

 

빨간글씨 도메인입력 부분에 원하는 사이트를 적어주면됩니다.

블로그 이미지

슬픈외로움

개발이 어려워? 모든것엔 답이있다...

,

HTTP POST 여러개의 파라미터를 포함한 request 테스트

 

아파치 httpclient 라이브러리를 이용하여 POST 방식으로 페이지를 호출하는 예제입니다.

 

 

package com.redjava.interfaces.https;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class httpClientParams {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		  HttpClient client = new DefaultHttpClient();
		    HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");

		    try {

		      List<namevaluepair> nameValuePairs = new ArrayList<namevaluepair>(1);
		      nameValuePairs.add(new BasicNameValuePair("Email", "jsaclova"));
		      nameValuePairs
		          .add(new BasicNameValuePair("Passwd", "************"));
		      nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
		      nameValuePairs.add(new BasicNameValuePair("source", "Google-cURL-Example"));
		      nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));

		      post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		      HttpResponse response = client.execute(post);
		      BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

		      String line = "";
		      while ((line = rd.readLine()) != null) {
		        System.out.println(line);
		        if (line.startsWith("Auth=")) {
		          String key = line.substring(5);
		          // Do something with the key
		        }

		      }
		    } catch (IOException e) {
		      e.printStackTrace();
		    }
	  }


}
블로그 이미지

슬픈외로움

개발이 어려워? 모든것엔 답이있다...

,

 

 

 

소켓을 통해 네트워크 정보를 보는 기본적인 예제입니다.

 

네트워크 소켓을 열어서 간단한 정보를 확인하는 예제입니다.

 

 

----------network.java-------------

package com.redjava.java.network;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class NetEcho {
 
   public static void main(String[] args) throws IOException {
   
     try {
      Socket echoSocket = new Socket("localhost", 80);
      System.out.println(echoSocket);
     }
     catch(UnknownHostException e) {
      System.err.println("Don't know about host: roseindi.");
      System.exit(1);
     }
     catch (IOException e) {
      System.err.println("I understand about "+ "the host: roseindi.");
      System.exit(1);
     }
   }

}

 

 

실행결과

 

Socket[addr=localhost/127.0.0.1,port=80,localport=51962]

 

 

블로그 이미지

슬픈외로움

개발이 어려워? 모든것엔 답이있다...

,

 

 

 

도메인으로 IP 주소를 알아내는 간단한 예제소스 입니다.

 

// 변수 선언
String hostname = "www.daum.net";

// 호스트 이름으로 ip 주소값 가져오기
InetAddress ipaddress = InetAddress.getByName(hostname);

 

 

------------ network.java ---------------

package com.redjava.java.network;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class NetFindIp {

   public static void main ( String[] args ) throws IOException   {
  
    String hostname = "www.daum.net";  
   
    try{   
     InetAddress ipaddress = InetAddress.getByName(hostname);
     System.out.println("IP address: " + ipaddress.getHostAddress());
     } catch ( UnknownHostException e )    {    
       System.out.println("Could not find IP address for: " + hostname);   
     }
     }
}

블로그 이미지

슬픈외로움

개발이 어려워? 모든것엔 답이있다...

,


getKeepAlive : 소켓이 살아있는지 죽었는지 확인하는 메소드

 

Server는 socket의 끊어지 상태 확인이 어려운 경우가 많으며
socket보다 방화벽의 connection timeout이 짧은 경우 종종 발생합니다.

서버는 소켓이 끊어진지 여부를 모르기 때문에 아래의 절차를 거쳐 socket close후 처리를 합니다.

if( socket.isConnected() == true && socket.getKeepAlive() == false) {
  socket.setKeepAlive(true);
  if(socket.getKeepAlive() == false) { // Socket 연결이 끊어 졌는지 확인
    socket.close();
    releaseSocket(socket, endpoint);
    socketsPool.clear(socketKey);
    socket = (Socket) socketsPool.borrowObject(socketKey);
  }
}


----- network.java ----
package com.redjava.java.network;

import java.net.*;
import java.io.*;

public class NetGetKeepAlive{
 
 public static final short TIME_PORT = 135;
 
 public static void main(String[] args) throws IOException{
  
  String hostName = null;
  System.out.println();
  
  try{
   Socket socket= new Socket(hostName,TIME_PORT);
   System.out.println("socket =" + socket);
   System.out.println("Keep Alive="+ socket.getKeepAlive());
   System.out.println("Send Buffer size ="+ socket.getSendBufferSize());
   System.out.println("output ="+socket.isOutputShutdown());
   System.out.println("port is =" + socket.getPort());
   System.out.println("socket address ="+socket.getLocalSocketAddress());
   InetAddress in= socket.getInetAddress();
   System.out.println(in);
   System.out.println("\n");
   System.out.print("RAW IP Address - (byte[]) : ");
   byte[] b1 = in.getAddress();
   
   for (int i=0; i< b1.length; i++) {
    if (i > 0) {
     System.out.print(".");}
     System.out.print(b1[i]);
   }

  }
  catch (UnknownHostException  e) {
   e.printStackTrace();
  }
  catch (IOException e) {
   e.printStackTrace();
  }
 }
}


--- 실행결과 ---
socket =Socket[addr=localhost/127.0.0.1,port=135,localport=52195]
Keep Alive=false
Send Buffer size =8192
output =false
port is =135
socket address =/127.0.0.1:52195
localhost/127.0.0.1

RAW IP Address - (byte[]) : 127.0.0.1

 

블로그 이미지

슬픈외로움

개발이 어려워? 모든것엔 답이있다...

,

 

지정된 폴더에 있는 파일들을 zip으로 압축하는 샘플 예제입니다.

 

지정된 폴더내의 모든 파일들을 zip으로 압축하는 샘플 예제

 

 // 지정된 위치에 압축파일 생성
private static final String OUTPUT_ZIP_FILE = "C:\\Workspace\\folderfile.zip";

 // 압축할 폴더 위치 지정
private static final String SOURCE_FOLDER = "C:\\Workspace";

 // ZipFolder 생성
ZipFolder ZipFolder = new ZipFolder();

 // FileOutputStream 생성
FileOutputStream fos = new FileOutputStream(zipFile);

 // ZipOutputStream 생성
ZipOutputStream zos = new ZipOutputStream(fos);

 // ZipEntry 생성
ZipEntry ze= new ZipEntry(file);

 // FileInputStream 생성
FileInputStream in = new FileInputStream(SOURCE_FOLDER + File.separator + file);

 // 읽은 파일 쓰기
zos.write(buffer, 0, len);


---- Compression.java
package com.redjava.java.io.Compression;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFolder {
 
   List<string> fileList;
   
     private static final String OUTPUT_ZIP_FILE = "C:\\Workspace\\folderfile.zip";
     private static final String SOURCE_FOLDER = "C:\\Workspace";
 
     ZipFolder(){
      fileList = new ArrayList<string>();
     }
 
     public static void main( String[] args )  {
      
      ZipFolder ZipFolder = new ZipFolder();
      ZipFolder.generateFileList(new File(SOURCE_FOLDER));
      ZipFolder.zipIt(OUTPUT_ZIP_FILE);
     }
 
     public void zipIt(String zipFile){
 
       byte[] buffer = new byte[1024];
       try{
       FileOutputStream fos = new FileOutputStream(zipFile);
       ZipOutputStream zos = new ZipOutputStream(fos);
  
       System.out.println("ZipFile : " + zipFile);
  
       for(String file : this.fileList){
        System.out.println("File 추가 : " + file);
        ZipEntry ze= new ZipEntry(file);
           zos.putNextEntry(ze);
  
           FileInputStream in = new FileInputStream(SOURCE_FOLDER + File.separator + file);
  
           int len;
           while ((len = in.read(buffer)) > 0) {
            zos.write(buffer, 0, len);
           }
  
           in.close();
       }
  
       zos.closeEntry();
       zos.close();
  
       System.out.println("압축이 완료되었습니다.");
   }catch(IOException ex){
      ex.printStackTrace();  
   }
    }

     public void generateFileList(File node){
   if(node.isFile()){
    fileList.add(generateZipEntry(node.getAbsoluteFile().toString()));
   }
  
   if(node.isDirectory()){
    String[] subNote = node.list();
    for(String filename : subNote){
     generateFileList(new File(node, filename));
    }
   }
 
     }

     private String generateZipEntry(String file){
      return file.substring(SOURCE_FOLDER.length()+1, file.length());
     }


}
</string></string>

블로그 이미지

슬픈외로움

개발이 어려워? 모든것엔 답이있다...

,

 

지정된 파일을 zip으로 압축하는 샘플 예제입니다

 

java 에서 지정된 파일을 zip 형태로 압축하는 샘플예제 입니다.

 

// 압축할 위치 및 압축파일명 지정
FileOutputStream fos = new FileOutputStream("C:\\Workspace\\file.zip");

 // ZipOutputStream 생성
ZipOutputStream zos = new ZipOutputStream(fos);

 // 압축할 파일명 지정
ZipEntry ze= new ZipEntry("test copy");

 // 지정한 파일명에 압축해서 넣을 압축파일 지정
zos.putNextEntry(ze);
 FileInputStream in = new FileInputStream("C:\\Workspace\\test.txt");
 
 
--- Compression.java ---
 
package com.redjava.java.io.Compression;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Zip {
 
 public static void main( String[] args ){
  byte[] buffer = new byte[1024];
 
     try{
      FileOutputStream fos = new FileOutputStream("C:\\Workspace\\file.zip");
      
      ZipOutputStream zos = new ZipOutputStream(fos);
      ZipEntry ze= new ZipEntry("test copy");
      ZipEntry ze2= new ZipEntry("test1 copy");
     
      zos.putNextEntry(ze);
      FileInputStream in = new FileInputStream("C:\\Workspace\\test.txt");
 
      int len;
      while ((len = in.read(buffer)) > 0) {
       zos.write(buffer, 0, len);
      }
      in.close();
      
      zos.putNextEntry(ze2);
      FileInputStream in2 = new FileInputStream("C:\\Workspace\\test1.inf");
      
      int len2;
      while ((len2 = in2.read(buffer)) > 0) {
       zos.write(buffer, 0, len2);
      }
 
      in2.close();
 
      zos.closeEntry();
      zos.close();
 
      System.out.println("Zip 압축이 완료되었습니다.");
 
     }catch(IOException ex){
        ex.printStackTrace();
     }
 }
}

 

블로그 이미지

슬픈외로움

개발이 어려워? 모든것엔 답이있다...

,

Javascript 의 random 함수를 사용하여 랜덤한 수를 구하는 방법입니다.

 

Math.random() 함수를 호출하게 되면, 기본적으로 소숫점 17 자리의 랜덤한

숫자가 발생되어지게 됩니다.

 

var a = Math.random();

결과 = 0.19049736162660652

 

이제 이렇게 발생한 수를 이용하시면 되는데요..

만약 1 ~ 10 사이의 랜덤한 수를 뽑는다고 한다면, 이론적으로 Math.random() 으로

발생한 숫자에 10 을 곱해서 정수형 숫자가 나오게 합니다.

 

a = a * 10;

결과 = 1.9049736162660652

 

이런 결과가 나오겠네요.  여기에서 다른 Javascript 함수인 Math.floor() 함수를 이용하여 소숫점 아래자리를 버립니다.

< Math.floor 함수는 소숫점 아래 자리를 버리는 함수 >

 

a = Math.floor(a);

결과 = 1

 

이런 결과가 나오게 됩니다.

 

이렇게 하게되면 나올 수 있는 결과값은 0 ~ 9 까지 나올 수 있게 됩니다.

우리가 구하려는 범위는 1~ 10 사이 이기 때문에,  나온 결과값에 +1 을 해주게되면

1~10 사이의 랜덤한 숫자를 구할 수 있게 되는 것입니다.

 

지금까지의 과정을 한줄로 요약하면....

 

var a = Math.floor(Math.random()*10) + 1;

결과 =  1 ~ 10 사이의 랜덤한 숫자

 

 

 

블로그 이미지

슬픈외로움

개발이 어려워? 모든것엔 답이있다...

,