몽고DB(mongodb) 접근IP설정
vi etc/mongodb.conf
bind_ip = 0.0.0.0 이면 본인 컴퓨터 아이피로 접근해야 하고,
bind_ip = 127.0.0.1 이면 localhost 로 접근해야 한다.
당신의 업무력 향상과 칼퇴를 돕는 블로그
몽고DB(mongodb) 접근IP설정
vi etc/mongodb.conf
bind_ip = 0.0.0.0 이면 본인 컴퓨터 아이피로 접근해야 하고,
bind_ip = 127.0.0.1 이면 localhost 로 접근해야 한다.
JAXB 기초 (XML 파싱, 마샬, 언마샬 관련)
자바의 XML을 파싱(분석)할 수 있게 도와주는 라이브러리로 JAXB가 있다. JAXB는 XML과 자바 클래스를 바인딩(연결)한다. 다시 말해 간단한 명령어만으로 클래스에 파싱된 XML을 대입해주는 라이브러리이다.
기존의 XML 분석 방법은 XML 전체를 String 형식으로 받아와서 문자열을 자르는 방식(substring)이었다. JAXB는 원하는 태그명, 어트리뷰트명을 기입한 클래스를 마련해두기만 하면 자동적으로 값이 클래스에 들어오게 되는 자동화 라이브러리이다.
1. 마샬(Marshal), 언마샬(Unmarshal)
XML을 파싱할 때 늘 나오는 개념이 언마샬(Unmarshal)과 마샬(Marshal)이다. 언마샬은 XML을 객체로 변환시키는 것이고, 마샬은 객체를 XML로 변환시키는 것이다.
2. 클래스(class), 값(value), 어트리뷰트(Attribute)
|
<all> <store> <itemName>치약</itemName> <price value=”2000″>2000</price> </store> </all> |
만약 <all><store><itemName>치약</itemName><price value=”2000″>2000</price></store></all> 라는 XML이 있다고 하자. 이 때 가장 안쪽에 위치하는 <itemName>, <price> 는 값에 해당한다. 그리고 값을 감싸고 있는 <all>과 <store>는 클래스라고 한다. 헷갈리지 않도록 주의할 점은, <store>가 클래스라는 점이다. 이와 같이 클래스 안에 클래스가 들어갈 수 있다. 특별히 <all>은 가장 위쪽에 위치한 클래스 이므로 루트(root)라고 부른다.
특히 값 중에서 <price>라는 값의 경우, value=”2000″이라는 정보를 태그 안에 갖고 있다. 여기서 value와 같은 요소를 어트리뷰트라고 한다.
3. JAXB의 활용
JAXB에서 root class에는 @XmlRootElement 라는 애너테이션(Annotation, 일종의 구분자. 골뱅이 모양이다)을 붙인다. 나머지 일반적인 class와 값에는 @XmlElement 라는 애너테이션을 붙인다. 자세한 사용법은 아래 자바 예제에서 확인할 수 있다.
4. 필요한 라이브러리 파일
JSOUP 라이브러리는 mvnrepository에서 구할 수 있다. 메이븐(Maven)을 쓰고 있다면 아래 코드를 붙여넣으면 된다.
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.11</version>
</dependency>
5. 자바 예제
예제는 네이버 뉴스 댓글을 분석하는 자바 프로그램의 프로토타입이다.
Rss.java
package com.news;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Rss {
private Channel channel;
public Channel getChannel() {
return channel;
}
@XmlElement
public void setChannel(Channel channel) {
this.channel = channel;
}
}
Channel.java
ppackage com.news;
import javax.xml.bind.annotation.XmlElement;
import java.util.*;
public class Channel {
private List<Item> item;
public List<Item> getItem() {
return item;
}
@XmlElement
public void setItem(List<Item> item) {
this.item = item;
}
}
Item.java
package com.news;
import javax.xml.bind.annotation.XmlElement;
public class Item {
private String title;
private String link;
private String description;
public String getTitle() {
return title;
}
@XmlElement
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
@XmlElement
public void setLink(String link) {
this.link = link;
}
public String getDescription() {
return description;
}
@XmlElement
public void setDescription(String description) {
this.description = description;
}
}
NewsManager.java
package com.news;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.net.*;
import java.util.*;
public class NewsManager {
private String targetUrl = “http://newssearch.naver.com/search.naver?where=rss&query=“;
public static void main(String[] args){
NewsManager m = new NewsManager();
List<Item> list=m.newsListData(“주가”);
for(Item i:list){
System.out.println(i.getTitle() + ” ” + i.getDescription());
}
}
public List<Item> newsListData(String ss){
List<Item> list = new ArrayList<Item>();
try{
JAXBContext jc=JAXBContext.newInstance( Rss.class );
Unmarshaller um=jc.createUnmarshaller();
URL url=new URL( targetUrl + URLEncoder.encode(ss, “UTF-8”) );
Rss rss = (Rss)um.unmarshal(url);
list = rss.getChannel().getItem();
}catch(Exception e){
System.out.println(“newsListData error: “);
e.printStackTrace();
}
return list;
}
}
네이버 뉴스에서 원하는 댓글 얻기
http://newssearch.naver.com/search.naver?where=rss&query=야구
들어가면 네이버 뉴스의 댓글들을 볼 수 있다. 마우스 우클릭해서 페이지 소스보기를 하면 XML형식으로 되어 있음을 알 수 있다. XML을 분석해서 통계를 내거나 솔루션에 사용하면 된다.
[JAVA] jsoup 기초
-본 문서를 읽기 전 필요한 사전 지식 : html(css, jquery), java
JSOUP(제이솝)은 html, xml 등을 파싱하는 자바 라이브러리다. 원래 SOUP(솝)이라는 라이브러리인데, 자바에 맞게 다시 만들어졌으므로 J가 붙어 JSOUP이 되었다. 웹사이트의 내용을 쉽게 파싱(parse)해오고 싶을 때 사용한다. 크롤링(crawl)이라는 용어를 쓰기도 한다.
JSOUP 라이브러리는 mvnrepository에서 구할 수 있다. 2016년 5월 현재 가장 최신 버전은 1.9.2 버전이다.
참고로 메이븐(Maven)에서 쓰고 싶다면 아래 코드를 가져가면 된다.
JSOUP 에서 html 문서 전체를 “도큐먼트”라고 한다. 이 도큐먼트 내부의 (1) 태그 사이의 텍스트, (2) 특정 태그의 어트리뷰트, (3)특정 태그를 포함한 소스 를 가져올 수 있게 해주는게 JSOUP 이다.
0. 임포트할 목록
1. 사이트 연결
System.out.println( doc ); 으로 찍어봐도 좋다. 찍으면 전체 사이트 내용이 출력된다.
2. 복수의 엘리먼트 파싱하기
위 코드는 “class가 box-contents인 div 태그의, class가 title인 strong 태그를 가져온다”는 뜻이다. 이런 설명은 한국말이 더 어렵다.
그냥 태그명을 쓰고 그 뒤에 쩜 클래스명을 주거나, 샵 클래스명을 주면 된다. (1) 클래스 가져오려면, 태그명.클래스명 을 주면 된다. (2) 아이디 가져오려면, 태그명#아이디명 이라고 쓰면 된다. 다시 말해 제이쿼리 셀렉션과 비슷하다.
이 때, 주의할 점은, 한 개가 아니라 해당 패턴에 일치하는 모든 태그를 긁어온다. (문서 내 모든 엘리먼트를 가져온다.)
예) 문서 내 모든 <div class=”a”>를 가져오려면, div.a 를 셀렉트
문서 내 모든 <div id=”b”>를 가져오려면, div#b 를 셀렉트
3. 단일 엘리먼트 파싱하기
System.out.println( oneTitle );
}
여기서 값을 가져오는 방식은 크게 3가지가 있다.
(1) text를 쓰면 태그 사이 글자만 가져온다.
(2) attr을 쓰면 태그 속의 속성(태그의 어트리뷰트)을 가져온다.
만약 그림(img태그)의 주소를 가져오고 싶다면 String strPoster = posterElement.attr(“src”); 식으로 가져오면 된다.
(3) html을 쓰면 태그까지 다 가져온다.
개인적으로 빅데이터 프로젝트를 했을 때는 JSOUP 을 쓰지 않고 자체적으로 개발해서 사용했었다. 주석을 제거하는 등 html태그만을 분석해내는 기술은 제법 까다롭다. 생각보다 많은 예외가 있기 때문에, JSOUP을 쓰는게 좋은 방법이다. 필자는 공부 목적으로 파서기를 코딩했었지만, 어떤 서비스를 구현하기 위해 파싱이 필요한 상황이라면 JSOUP을 추천한다.
MapReduce
MovieMapper.java
package com.sist.hadoop;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class MovieMapper extends Mapper<LongWritable, Text, Text, IntWritable>{
private final IntWritable one = new IntWritable(1);
private Text result = new Text();
String[] feel = { “사랑”,”로맨스”,”매력”,”즐거움”,”스릴”,
“소름”,”긴장”,”공포”,”유머”,”웃음”,”개그”,
“행복”,”전율”,”경이”,”우울”,”절망”,”신비”,
“여운”,”희망”,”긴박”,”감동”,”감성”,”휴머니즘”,
“자극”,”재미”,”액션”,”반전”,”비극”,”미스테리”,
“판타지”,”꿈”,”설레임”,”흥미”,”풍경”,”일상”,
“순수”,”힐링”,”눈물”,”그리움”,”호러”,”충격”,”잔혹”,
“드라마”,”판타지”,”공포”,”멜로”,”애정”,
“로맨스”,”모험”,”느와르”,”다큐멘터리”,
“코미디”,”미스터리”,”범죄”,”SF”,”액션”,”애니메이션” };
Pattern[] pattern = new Pattern[feel.length];
@Override
protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, IntWritable>.Context context)
throws IOException, InterruptedException {
for( int i=0; i<feel.length; i++ ){
pattern[i] = Pattern.compile( feel[i] );
}
Matcher[] matcher = new Matcher[feel.length];
for( int i=0; i<feel.length; i++){
matcher[i] = pattern[i].matcher( value.toString() );
while( matcher[i].find() ){
result.set( feel[i] ); //String 을 Hadoop.Text로 전환
context.write( result, one );
}
}
}
}
MovieDriver.java
package com.sist.hadoop;
import java.util.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import java.io.*;
public class MovieDriver {
public static void main(String[] args) throws Exception{
File dir = new File( “./output” );
if( dir.exists() ){
File[] files = dir.listFiles();
for(File f:files){
f.delete(); // -rf
}
dir.delete(); // rm
}
System.out.println(“11111111111111”);
//Hadoop
Configuration conf = new Configuration();
System.out.println(“2222”);
//JOB : 작업지시
Job job = new Job( conf, “WordCount” );
System.out.println(“333”);
//장비
job.setMapperClass( MovieMapper.class );
job.setReducerClass( MovieReducer.class );
System.out.println(“444”);
//결과값
job.setOutputKeyClass( Text.class );
job.setOutputValueClass( IntWritable.class );
System.out.println(“555”);
//작업하는 내용
FileInputFormat.addInputPath(job, new Path(“/home/sist/bigdataStudy/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/MovieMapReduceProject/desc.txt”));
System.out.println(“666”);
FileOutputFormat.setOutputPath(job, new Path(“./output”));
System.out.println(“777”);
//실행
job.waitForCompletion( true );
}
}
MovieReducer.java
package com.sist.hadoop;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class MovieReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
private IntWritable res = new IntWritable();
@Override
protected void reduce(Text key, Iterable<IntWritable> values,
Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException {
// TODO Auto-generated method stub
int sum = 0;
for( IntWritable i: values ){
sum += i.get(); //get : IntWritable -> int로 바꾼다.
}
res.set( sum );
context.write( key, res );
}
}
JSP에서 실제 저장 위치 기억
jsp 파일에서 getRealPath 할것.
예를 들어 list.jsp 라면 안쪽 내용에 <%=application.getRealPath( “list.jsp” ) %> 라고 입력하면 실제 경로 나온다.
(그림 출력 등을 하고 싶을 때 필수 팁)
<dependency>
<groupId>org.nuiton.thirdparty</groupId>
<artifactId>Rserve</artifactId>
<version>1.7-3</version>
</dependency>
<dependency>
<groupId>org.nuiton.thirdparty</groupId>
<artifactId>REngine</artifactId>
<version>1.7-3</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.13.0-rc1</version>
</dependency>
<dependency>
<groupId>org.nuiton.thirdparty</groupId>
<artifactId>JRI</artifactId>
<version>0.9-6</version>
</dependency>
<dependency>
<groupId>com.github.lucarosellini.rJava</groupId>
<artifactId>JRIEngine</artifactId>
<version>0.9-7</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.18.2-GA</version>
</dependency>
<dependency>
<groupId>org.nuiton.thirdparty</groupId>
<artifactId>Rserve</artifactId>
<version>1.7-3</version>
</dependency>
<dependency>
<groupId>org.nuiton.thirdparty</groupId>
<artifactId>REngine</artifactId>
<version>1.7-3</version>
</dependency>
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-core</artifactId>
<version>4.0.2</version>
</dependency>
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-stream</artifactId>
<version>4.0.2</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<!– <dependency> –>
<!– <groupId>com.oracle</groupId> –>
<!– <artifactId>ojdbc14</artifactId> –>
<!– <version>10.2.0.4.0</version> –>
<!– </dependency> –>
<!– End –>
<!– AspectJ –>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!– AOP추가 –>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.5</version>
</dependency>
<!– AOP추가 –>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<!– AOP추가 –>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.1</version>
</dependency>
<!– tiles –>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-core</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-jsp</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-api</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-servlet</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>commons-digester</groupId>
<artifactId>commons-digester</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr-runtime</artifactId>
<version>3.5.2</version>
</dependency>
<!– XML –>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.11</version>
</dependency>
<!–
jaxb-core
jaxb-impl
jaxb-api
json-simple
commons-lang
ezmorph
–>
<!– JSON –>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>
<!– Logging –>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency>
<!– @Inject –>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!– Servlet –>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!– Test –>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
</additionalBuildcommands>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>org.test.int1.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
TwitterListener.java
package com.sist.mapred;
import twitter4j.StallWarning;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.StatusListener;
public class TwitterListener implements StatusListener{
@Override
public void onException(Exception ex) {
// TODO Auto-generated method stub
System.out.println( “에러 : ” + ex.getMessage() );
ex.printStackTrace();
}
@Override
public void onDeletionNotice(StatusDeletionNotice arg0) {
// TODO Auto-generated method stub
}
@Override
public void onScrubGeo(long arg0, long arg1) {
// TODO Auto-generated method stub
}
@Overridepackage com.sist.mapred;
import twitter4j.FilterQuery;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
public class MainClass {
public static void main(String[] args) throws Exception {
TwitterStream tws = new TwitterStreamFactory().getInstance();
String[] names = {“문재인”,”안철수”,”반기문”,”김무성”,”안희정”,”정의화”,”유승민”,”박지원”,”김부겸”,”박원순”};
FilterQuery fq = new FilterQuery();
TwitterListener listen = new TwitterListener();
tws.addListener( listen );
fq.track( names );
tws.filter( fq );
}
}
public void onStallWarning(StallWarning arg0) {
// TODO Auto-generated method stub
}
@Override
public void onStatus(Status status) {
// TODO Auto-generated method stub
System.out.println( status.getUser().getScreenName() + “:” + status.getText() );
}
@Override
public void onTrackLimitationNotice(int arg0) {
// TODO Auto-generated method stub
}
}
MainClass.java
package com.sist.mapred;
import twitter4j.FilterQuery;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
public class MainClass {
public static void main(String[] args) throws Exception {
TwitterStream tws = new TwitterStreamFactory().getInstance();
String[] names = {“문재인”,”안철수”,”반기문”,”김무성”,”안희정”,”정의화”,”유승민”,”박지원”,”김부겸”,”박원순”};
FilterQuery fq = new FilterQuery();
TwitterListener listen = new TwitterListener();
tws.addListener( listen );
fq.track( names );
tws.filter( fq );
}
}
자바스크립트(js)로 코딩 입문하기
코딩을 입문할만한 언어를 추천하라면 저는 C를 추천하겠습니다. 물론 C는 쉬운 언어가 아닙니다. 저도 C를 잘하지 못합니다.
다만 C를 모르는 사람들은 C에 대해 불필요한 환상과 두려움을 갖습니다. 막상 문법 위주로 훑으면 간단하게 프로그래밍 개념을 익힐 수 있는 언어가 C인데, 환상과 두려움 때문에 자기가 ‘진짜’ 프로그래밍을 모르고 있다고, 할 수 없다고 생각해버립니다. 이런 점 때문에라도 꼭 한 번은 C를 배워야한다고 봅니다.
불필요한 환상과 두려움을 버린다면, 저 역시 사람들에게 스크립트 언어를 추천합니다. 스크립트 언어란 한 줄씩 해석되는 언어를 말합니다. 제일 추천하고 싶은 언어는 자바스크립트(javascript)입니다. 줄여서 js[제이에스]라고 하죠. 편의상 계속 js라 쓰겠습니다.
js는 한 때 대단치 않은 언어로 취급됐습니다. 그런데 웹 생태계가 발전하면서 js도 같이 대단한 언어로 발전했습니다.
여기서 잠깐, 웹 사이트들은 어떤 언어로 만들어졌을까요? C일까요? 웹 사이트를 만들 수 있는 언어는 3가지가 있다고 합니다. php[피에이치피], jsp[제이에스피], asp[에이에스피]. 이것들 말고도 떠오르는 언어와 프레임워크들이 많지만 기본적으로는 이 셋이 웹 사이트 개발계의 삼대장입니다.
우리가 이 셋 중의 하나로 웹 사이트를 개발할 때, 서버 사이드 프로그래밍(server side programming)이라고 부릅니다. 웹 사이트는 기본적으로 서버(server)를 가지게 되는데, 그냥 컴퓨터입니다. 웹 사이트의 파일들이 저장돼있는 컴퓨터를 서버라고 합니다.
반대로 그냥 일반 유저들이 쓰는 컴퓨터를 클라이언트(client)라고 합니다. 그리고 클라이언트에게 보이는 부분을 개발하는 것, 즉, 웹 브라우저에 표시되는 부분을 개발하는 것을 두고 클라이언트 사이드 프로그래밍(client side programming)이라고 합니다. 이를 구성하는 요소가 저 이름도 유명한 html, js, css입니다.
그러니까 ‘서버 단’은 php, jsp, asp라는 세 가지 언어 중에 하나를 ‘택일’해서 개발하고, ‘클라이언트 단’은 html, js, css를 ‘결합’해서 개발합니다. 예를 들면 저는 jsp + html/js/css 개발을 잘하는 편입니다. 기존에는 이게 전통적인 웹 사이트 개발 공식이었다고 보면 됩니다.
그런데 이러한 생태계에 노드js(node.js)는 놈이 등장했습니다. 노드js는 서버 단에서 쓸 수 있는 자바스크립트 언어입니다. 이것은 상당히 혁명적인 이야기죠. 원래 서버 프로그래밍은 클라이언트 프로그래밍보다 어렵다고 알려져 있는 만큼, jsp나 php를 배우는데는 상당한 시간을 들여야 했습니다.
그런데 노드js가 서버를 대체한다면, 이제 js언어 하나로 서버와 클라이언트를 모두 작성할 수 있게 됩니다.
이론적으로는 html, css, js만을 배워서 간단한 웹 사이트를 만들 수 있게 된 것이죠. 지금 보시는 이 ‘디독’이라는 사이트 역시 html, css, js로만 만들어진 사이트입니다. 웹 사이트 하나를 만들어낸다는게 생각보다 쉬운 일은 아닐테지만, 시간이 되는대로 차근차근 설명할 예정입니다.
젠서버(XenServer) 가상화 구조
– 망 분리의 단점 : 많은 비용 -> 대안 : 논리적 망 분리 (ex: 가상화)
– 필요한 컴퓨터 최소 3대 (XenCenter 제외) : AD(Active Directory), Member Server, Xen Server
<FAT32 하드디스크에서 파일 복구하기 연습>
1. 컴퓨터 관리 들어간다.
2. 가상 디스크 만들기 (3GB)
3. 디스크 초기화 하기 (MBR로 할것)
4. 우측에서 디스크 새 볼륨 할당 (이때 FAT32 로 할것)
5. 보기 – 폴더 옵션에서 숨김파일을 볼 수 있게 만든다. (이때, 시스템 숨김파일도 볼 수 있게 체크한다)
6. 디스크 안에 파일을 넣고 shift + delete로 지운다. (여기서는 bbb.jpg를 넣고, shift + delete 지운다)
7. 원하는 파티션 찾아가기
우선 헥스에디터(HxD)로 물리디스크를 연다.

위 그림상에 블락 표시된 영역이 파티션이다. 16바이트씩 끊어서 보면 된다. 보면 알겠지만 구조적으로 파티션 4개 밖에 들어갈 자리가 없다. 섹터 하나의 크기는 512바이트이다.
8. 찾은 파티션에서 파일시스템 영역 찾아가기
(1) 예약영역
102a (16진수) -> 4138 (10진수)
(2) 현재 쓰고 있는 영역
17EB -> 6123
파일시스템의 사이즈를 나타냄.
복제본이 하나 더 있기 때문에
곱하기 2를 해야함. 6123 * 2 = 12246
9. 파일시스템의 위치 계산
파일 시스템의 위치는
파티션 위치, 예약 영역, 현재 쓰고 있는 영역 3개를 더하면됨.
128 + 4138 + 12246 = 16512 (섹터 16512 볼것)
섹터 16512에 가보면 디스크가 가진 파일들의 목록이 있을것임.
10. 파일 시스템 (섹터 16512) 에서 파일의 크기 확인
맨끝의 4자리가 용량이다. 10 92 06 00 -> (리틀엔디언) 00069210
11. 파일 영역 찾기

(1) E5가 지워진 파일을 가리키는 시그니처 이므로 E5를 찾는다.
(2) 앞쪽을 지시하는 4바이트와 뒤쪽을 지시하는 4바이트를 리틀엔디언 방식으로 결합한다.
(3) 위 값에서 2를 빼고, 곱하기 8을 한다.
4b (hex) – 2 (dec) = 73 (dec)
73 * 8 = 584
(4) 파일시스템의 위치 섹터와 계산된 값을 더한다.
16512 + 584 = 17096
해당 파일이 있는 위치는 17096. 17096 섹터를 찾아가면 된다.
12. 파일 영역을 찾아서 기억한 크기만큼 블록 지정
섹터 17096 으로 가서 마우스 우클릭하여 블록 선택 – 아까 기억한 파일의 크기 입력

13. 파일 저장
헥스에디터(HxD)에서 새 파일을 열어서
해당 파일의 내용을 붙여넣기 하고 확장자 jpg로 파일 저장하면 파일이 복구된다.
디스크 시그니처 변경

오전 10:26 2016-03-26
컴퓨터 관리 – 좌측 메뉴의 디스크 관리
상단 메뉴의 동작 – VHD 만들기
mbr_ntfs 라는 이름으로 가상 디스크 만들기.
3GB / VHD / 고정크기
디스크 초기화 (MBR : 마스터 부트 레코드)
hxd(hex editor)로 디스크 연다.
관리자 권한으로 hxd 실행 – 기타설정- 디스크 열기
파티션 볼 수 있다.
00은 부팅이 불가능
80은 부팅 가능.
17은 디스크 탐색기에서 나타나지 않는다.
읽기 전용으로 열기 체크를 풀고 디스크를 열자.
(사고 치지 말자. 정확히 가상 드라이브를 선택해야 한다)
ntfs 는 원래 시그니처가 07이다.
07을 17로 바꾸면, 보이지 않게 된다.
디스크관리 상에서 F5를 누르면 새볼륨이라는 글자가 사라진다.
하나의 섹터 512 바이트
리틀 엔디언 방식이라서 거꾸로 읽어야 함.
32009
시스템 영역의 전체 용량
계산기 hex로 두고
320000 을 입력
dex로 바꾼다 (204800)
204800 에 512 를 곱한다.
1024 로 한 번 나누면 키로바이트
1024 로 한 번 더 나누면 메가바이트
그러면 결과적으로 320000 이 100 이 된다.
맨 앞의 한개는 부팅이 되는지 안되는지를 판단한다.
80 이면 부팅 가능.
그다음 세개는 데이터의 시작을 나타낸다.
그다음 07(ntfs)
그다음 3자리는 섹터의 끝을 의미한다
그다음 4자리
시작 데이터의 위치를 나타냄(거꾸로 읽어야한다 리틀 엔디언 : 0800)
2048 섹터에서 시작이 된다는 뜻
그 다음 네자리가 용량
USB를 볼륨이 아니라 폴더로 인식시키면
유해가 가능하다.
DRP나 DRM을 쓰지 않고 읽기만 하게 되어있다?
그룹정책 개체에서
게시 및 할당 만들기.
1. 게시 : 사용자 구성에서 만든다.
2. 할당 : 컴퓨터 구성에서 만든다.
위치는 \\1.0.0.1\install 로 만든다.
설치 사용자 인터페이스옵션 최대
cmd에서 사용자 계정 비밀번호 바꾸기
cmd 열고
net user
이라고 치면 사용자 계정 목록 뜸
net user [사용자계정명] *
이라고 치면 비밀번호 입력하라고 함.
ex ) net user Administrator *
window server 2008 가상화
vmware 기본설정





자바스크립트 쿠키 변경(javascript cookie)
쿠키 조회
javascript:alert(document.cookie)
쿠키 변경
javascript:document.cookie=”key1=value1; key2=value2″
AccessData FTK Imager

손상된 드라이브, 깨진 이미지를 복구하는 프로그램 (무료)
메뉴 – File – Add Evidence Item – Image File – 깨진 파일 선택 – Finish
웹해킹
각종 해킹 문제들을 풀 수 있는 사이트. 특이점은 입구에 로그인 버튼은 있는데, 회원 가입 버튼이 없음. 회원 가입하는 것 부터 직접 찾아내야 한다.
오픈스테고(OpenStego)

그림 파일 등에 원하는 텍스트 파일 등을 숨겨 넣을 수 있게(Data Hiding) 도와주는 프리웨어 프로그램.
(Setup-OpenStego-0.6.1.exe)
HxD Hex Editor 2.2

텍스트 파일 등을 헥스로 볼 수 있게 도와주는 프로그램
(HxDSetupKOR2.2.zip)
Exception printStackTrace 구현
JAVA
|
public static void printError(Exception e) { |
JSP
|
<%!
|
로드 밸런서
1. 좌측 메뉴의 Load Banlancers 클릭
Create Load Balancer 클릭
2. 로드 밸런서 설정
3.
4. vi /var/www/html/index.html 로 내용을 만든다.
리눅스 서버 두 군데에 다 만든다. 내용을 같게 하는게 원칙이지만, 하나는 1을 입력하고 하나는 2를 입력해서 저장하자.
4-1. 다 만든 이후에 service httpd restart 를 입력해서 서버를 재기동한다.

5. 네트워크 및 공유 센터에 들어가서 이더넷을 재설정한다.
6. cmd로 들어가서 nslookup을 친다. 아마존의 DNS Name을 입력해서 어드레스 2개를 얻는다.
어드레스 2개 중 어디를 들어가도 된다. 한 곳에는 1을 썼고, 다른 한 곳에는 2를 썼다면 1과 2가 번갈아 나온다.
실제로는 같은 파일을 유지할 것이기 때문에, 어드레스 2개 중 어디를 들어가도 같은 화면을 본다.

만약에 DNS가 필요하면 둘 중에 어떤 아이피를 DNS 해야할까?
로드 밸런서의 IP로 결정해야 한다.
VirtualBox 정리
























아마존 무료 AWS 등록 (아마존 EC2)
0. 아마존 웹사이트 접속
1. 좌측 상단의 EC2 클릭
2. Create Instance
3. Amazon Linux AMI 2015.09.2 (HVM), SSD Volume Type 을 Select

4. t2.micro 선택
5. Configure Instance Details
6. Add storage
7. Tag Instance
8. Configure Security Group
8. Select an existing key pair or create a new key pair


blob(xml) update하는 방법
blob 데이터형의 컬럼을 update하고 싶을때, blob이 xml 형태라면 그냥 일반적인 sql update 문으로 blob을 update 시킬 수 있다.
만약 아래와 같이 aa 라는 테이블이 있다고 가정하자. aaa 테이블의 content 컬럼은 데이터형이 blob이고, blob의 내용은 xml(혹은 굉장히 긴 텍스트)라고 가정하자.
이때 아래 그림의 “A”와 같이 쿼리를 쓰게 되면 값이 들어가지 않고 hex 에러가 나게 된다.
정상적인 입력을 위해서는 텍스트를 hex코드로 바꿔서 그림의 “B”처럼 update를 하면 된다.
아래 그림은 text를 hex 로 convert한 모습이다. text를 hex로 convert 해주는 사이트는 구글에 검색해보면 엄청나게 많다. 참고로 필자가 이용한 사이트는 http://www.swingnote.com/tools/texttohex.php 이다.

update 후 제대로 blob이 변경되었는지 꼭 확인하자. (sql developer(sql디벨로퍼)에서 blob 다운받기 ( http://blog.naver.com/bb_/220597223225 )
또한 update하기 전에 create table [테이블명2] as select [테이블명1] 으로 꼭 백업을 하자.
[JAVA] replaceFirst을 개선한 replaceOne
자바 String에는 기존에 replace, replaceFirst라는 메서드가 존재한다.
replace는 바꾸고 싶은 값이 n개 있으면 n개가 전부 바뀐다. 딱 하나만 바꿀 때 쓰는 메서드가 replaceFirst다.
그런데 replaceFirst는 파라미터에 정규식을 넣게 되어 있기 때문에, 스트링을 무심코 쓰다 보면 잘못 바뀐다.
특히 소괄호를 한 개만 쓰면 값이 정상적으로 바뀌지 않고 에러가 나는 경우가 있다.
소괄호나 마침표 같은 특수문자 앞에 역슬래시를 2개를 붙이는 방법도 있지만 정규식을 쓰지 않는 메서드를 만드는게 더 편하다고 생각했다.
새로 만든 메서드는 아래와 같다. 정규식이 통하지 않는 replaceOne 이다.
|
public String replaceOne(String fullStr, String oldStr, String newStr) { if (oldStr == null || oldStr.length() == 0) { if (newStr == null || newStr.length() == 0) { int posOldStr = fullStr.indexOf(oldStr); if (posOldStr >= 0) { } catch (Exception e) { if (res == null || res.length() == 0) { return res.toString(); |
public class PathMaker {
/**
* path와 제외할 폴더명들, 제외할 파일명들을 넘기면 어레이리스트로 파일 패스 목록을 리턴하는 메서드.
*
* @param path
* @param exceptFolders
* @param exceptFile
* @return
*/
public ArrayList<String> makePathList(String path, String includePattern, String exceptPattern) {
ArrayList<String> pathList = new ArrayList<String>();
try {
if (path == null || path.length() < 0) {
System.out.println(“패스가 없습니다”);
}
includePattern = includePattern.replace(“.”, “\\.”); // 점은 정규식
// 점으로
includePattern = includePattern.replace(“*”, “.*”); // 별은 정규식
// 모든문자로
includePattern = includePattern.replace(“?”, “.”); // 물음표는 정규식
// 한문자로
exceptPattern = exceptPattern.replace(“.”, “\\.”);
exceptPattern = exceptPattern.replace(“*”, “.*”);
exceptPattern = exceptPattern.replace(“?”, “.”);
// System.out.println(includePattern);
String[] includeArr = includePattern.split(“,”);
String[] exceptArr = exceptPattern.split(“,”);
path = path.replace(“\\”, “/”);
File root = new File(path);
if (root.isDirectory()) {
addPath(root, pathList, includeArr, exceptArr);
} else if (root.isFile()) {
pathList.add(root.getAbsolutePath());
return pathList;
} else {
System.out.println(“해당 패스를 인식할 수 없습니다”);
}
} catch (Exception ex) {
Err.print(ex);
return null;
}
return pathList;
}
public void addPath(File dir, ArrayList<String> pathList, String[] includeArr, String[] exceptArr) {
if(dir.isDirectory()){
String[] dirList = dir.list();
for (int i = 0; i < dirList.length; i++) {
String fullPath = dir.getAbsolutePath() + “\\” + dirList[i];
File file = new File(fullPath);
addPath(file, pathList, includeArr, exceptArr);
}
}
else if(dir.isFile()){
String filePath = dir.getAbsolutePath();
boolean include = false;
for (int k = 0; k < includeArr.length; k++) {
if (filePath.matches(includeArr[k])) {
//매치가 되면 break;
include = true;
break;
}
}
if(!include){
return;
}
for (int k = 0; k < exceptArr.length; k++) {
if (filePath.matches(exceptArr[k])) {
return;
}
}
System.out.println(filePath);
pathList.add(filePath);
}
}
}
/**
* 한글/영어/숫자를 둘러싼 특수문자를 얻어내기 위한 함수.
* 한글 앞, 뒤의 특수문자를 각각 저장해서 스트링 배열 result [0], [1]로 리턴한다.
* 예를 들어 기존 스트링이 !@#$한글%^&* 이라면
* result[0] = “!@#$“
* result[1] = “%^&*”을 돌려 받는다.
* 기존 스트링이 !@#$한글영어한글!@#$%^&*숫자한글영어한글%^&* 이어도 동일한 결과를 리턴받는다.
* (한글/영어/숫자 사이의 특수문자는 무시)
*
* @param origin
* @return
*/
public static String[] getOnlySpecialMark_surrounded(String origin){
String[] result = { “”, “” };
StringBuffer frontBuffer = new StringBuffer();
StringBuffer backBuffer = new StringBuffer();
boolean discoverd_korean = false;
try{
int len = origin.length();
for(int col = 0; col < len; col ++){
String oneChar = origin.substring( col, col+1 );
boolean thisChar_is_specialMark = !oneChar.matches( “[가-힣0-9a-zA-Z]” );
if( thisChar_is_specialMark ){
//특정 특수문자를 발견하면 추가하고 넘어간다.
if( hasMark(origin, col, “\\n“) ||
hasMark(origin, col, “\\r“) ||
hasMark(origin, col, “\\t“) ){
oneChar = origin.substring( col , col+2 );
frontBuffer.append(oneChar);
continue;
}
if( !discoverd_korean ){
frontBuffer.append(oneChar);
}
else{
backBuffer.append(oneChar);
}
}
else{
discoverd_korean = true;
backBuffer.delete( 0, backBuffer.length() );
}
}
}catch(Exception ex){
Err.print(ex);
return result;
}
//저장
result[0] = frontBuffer.toString();
result[1] = backBuffer.toString();
//공백이나 탭만 있을 경우 무의미하므로 지운다
if( result[0].matches(“\\s*\\t*”) ){
result[0] = “”;
}
if( result[1].matches(“\\s*\\t*”) ){
result[1] = “”;
}
return result;
}
/**
* 어떤 스트링의 특정 위치에 특정 글자가 있는지 검사해서 boolean 값으로 돌려받는 메서드.
* @param target
* @param begin_col
* @param find
* @return
*/
public static boolean hasMark(String target, int begin_col, String find){
boolean result = false;
try{
int end_col = begin_col + find.length();
if(target == null || target.length() == 0){
return false;
}
if(find == null || find.length() == 0){
return false;
}
if(begin_col < 0){
return false;
}
if(end_col > target.length()){
return false;
}
String slice_of_target = target.substring(begin_col, end_col);
// System.out.println(slice_of_target);
if (slice_of_target.equals(find)){
result = true;
// System.out.println(“트루!!!”);
}
} catch (Exception ex){
Err.print(ex);
}
return result;
}
/**
* 특정 문자가 스트링에 몇 개 존재하는지 얻는 메서드.
* @param str
* @param mark
* @return
*/
public static int calcCountMark(String str, String mark){
int count = 0;
int begin_col = 0;
try{
if( str == null || str.length() ==0 ){
return 0;
}
while( true ){
if( begin_col > str.length() ){
break;
}
int discover_col = str.indexOf( mark, begin_col );
if( discover_col >= 0){
//찾으면 더 찾기 지속
begin_col = discover_col + 1;
count++;
}
else{
break;
}
}
} catch (Exception ex){
Err.print(ex);
}
return count;
}
/**
* 파일명이나 파일 경로 스트링을 넘기면 파일의 확장자를 가져오는 메서드.
* @param fileName
* @return
*/
public static String getExtension(String fileName){
String extension = null;
try{
if( fileName == null || fileName.length() == 0 ){
return null;
}
int dotPosition = fileName.lastIndexOf(“.”);
if( dotPosition < 1 ){
return null;
}
String frontSlice = fileName.substring(0, dotPosition);
if( frontSlice.length() <= 0 ){
return null;
}
extension = fileName.substring(dotPosition + 1);
if( extension.length() <= 0 ){
return null;
}
}catch(Exception ex){
Err.print(ex);
}
return extension;
}
/**
* 한글 및 한자를 포함하는지 검사하는 메서드.
* @param slice
* @return
*/
public static boolean containKorean(String slice){
boolean containKorean = false;
int len = slice.length();
for(int col = 0; col < len ; col ++){
char oneChar = slice.substring( col, col+1 ).toCharArray()[ 0 ];
if(charIsKorean(oneChar)){
containKorean = true;
break;
}
}
return containKorean;
}
/**
* 글자 한 개(char)가 한글인지 검사하는 메서드.
* @param oneChar
* @return
*/
public static boolean charIsKorean(char oneChar){
boolean isKorean = false;
if(
(oneChar >= 44032 && oneChar <= 55203) //44032 가 ~ 55203 힣
|| (oneChar >= 12593 && oneChar <= 12622) //12593 ㄱ~ 12622 ㅎ
|| (oneChar >= 12623 && oneChar <= 12643) //12623 ㅏ~ 12643 ㅣ
|| (oneChar >= 19968 && oneChar <= 44031)//19968 ~44031 한자 (한 일자부터 거북 구자까지 19968 한일 / 40860 거북구 / 44031한글직전)
){ // 한글체크.
isKorean = true;
}
return isKorean;
}
/**
* 글자 한 개(char)가 한글인지 검사하는 메서드.
* @param oneChar
* @return
*/
public static boolean charIsKorean(char oneChar){
boolean isKorean = false;
if(
(oneChar >= 44032 && oneChar <= 55203) //44032 가 ~ 55203 힣
|| (oneChar >= 12593 && oneChar <= 12622) //12593 ㄱ~ 12622 ㅎ
|| (oneChar >= 12623 && oneChar <= 12643) //12623 ㅏ~ 12643 ㅣ
|| (oneChar >= 19968 && oneChar <= 44031)//19968 ~44031 한자 (한 일자부터 거북 구자까지 19968 한일 / 40860 거북구 / 44031한글직전)
){ // 한글체크.
isKorean = true;
}
return isKorean;
}
HTML5
마크업랭귀지
html4나 xhtml의 부족한 기능 보완. 모바일 지원.
3D그래픽(캔버스), 이펙트(svg)
서버-클라이언트 통신가능(웹소켓)
디바이스 액세스(하드웨어 제어)
플래시, 실버라이트를 대체 가능한 태그 추가
오프라인, 웹 스트로스
embed -> video(스트리밍)
Input datetime
Input email(밸리데이션 가능)
웹 소켓: 과거의 폴링 방식에서 변경
css3 round, shadow, 백그라운드 이미지 n개 설정 가능
session
storage
webSQL
File Drag&Drop
jquery 사용자정의 필터(filter)
-예제
$.expr[‘:’].tttt = function(e) { return $(“input[type=’text’]”); }
$(“:tttt”);
-정의 규칙
jQuery.expr[‘:’].newFilterName =
function(elem, index, match) {
return true;
}
제이쿼리 선택자
1. #id selector $(‘#userId’).val(“선택1”);
2. .class selector $(‘.int’).val(“선택2”).eq(0);
3. tag name $(‘input’).eq(0).val(“선택3”);
4. [attribute] $(‘[maxlength=25]:eq(0)’).val(“선택4”);
5. > $(‘body > div > div:eq(1) > div > div > form > div > input’).first().val(“선택5”);
6. 띄어쓰기 $(‘body div div div div form div input:first’).val(“선택6”);
7. first $(‘input:first’).val(“선택7”);
8. get alert(“선택8 : ” + $(“form div input”).get(0));
9. [index] alert(“선택9 : ” + $(“form div input”)[0]);
10. tag:type $(“input:text”).first().val(“선택10”);
11. 어트리뷰트 포함 $(“input[name*=’serI’]:first”).val(“선택11”);
12. 어트리뷰트 접미사 $(“input[name$=’Id’]:first”).val(“선택12”);
13. 어트리뷰트 접두사 $(“input[name^=’use’]:first”).val(“선택13”);
14. first-child $(‘div #loginForm:first-child div input’).eq(0).val(“선택14”);
15. nth-child $(‘input:nth-child(2):eq(0)’).val(“선택15”);
자바 예약어(자바 키워드) 50개
임포트 : package, import
식별자 : public, protected, private
반환값 : void, double, byte, enum(열거형), int, short, char, float, long, boolean
클래스 : abstract, interface, class
final, const(final과 같음), static, volatile(멀티 스레드 접근시 원본성 보장), strictfp(부동소수점의 정밀도 보장), transient(직렬화방지)
함수:
while, do, for, continue, goto, break, assert(검증),
if, else, switch, case,
return
에러관련 : throw, catch, try, finally, throws
상속관련 : implements, extends
native(다른 랭귀지로 구현한다는 의미) / super(부모), this(나) / instanceof / default / new / synchronized
주로 command pattern에서 특정 클래스의 메소드를 사용하기 위해서 invoke 함수를 사용하는 경우가 있다.
그런데 invoke를 사용했을 때 Exception이 발생하게 되면 InvocationTargetException을 얻게 되고,
내부의 실제 문제가 되는 Exception을 구할 수 없는 경우가 있다.
이럴 때는 getCause();를 이용해 내부의 실제 문제가 되는 Exception을 얻을 수 있다.
이거 하나를 찾음으로써 two man/a month는 절약한듯.. 기쁘다.
아래는 소스.
Method handler = null;
String methodName = null;
Class[] clsParams = null;
Object[] objParams = null;
…
try{
….
handler = this.getClass().getDeclaredMethod( methodName, clsParams );
handler.invoke( this, objParams );
}catch(Exception ex){
Exception inner_ex = new Exception();
if (ex.getCause() instanceof Exception) {
inner_ex = (Exception) ex.getCause();
throw inner_ex;
}
else{
throw ex;
}
}
스프링 MVC패턴 한 장 요약
시퀀스 조회
시퀀스는
select 시퀀스명.CURRVAL from dual;
로 조회한다.
dual은 가상의 테이블이며, 실전에서는 다음값을 가져오기 위해 .NEXTVAL을 쓴다.
만약, “ORA-08002: 시퀀스 시퀀스명.CURRVAL은 이 세션에서는 정의 되어 있지 않습니다”라고 나온다면 해당 세션에서 NEXTVAL을 한 번 이상 쓰지 않았기 때문이다.
이럴 때는 아래와 같이 조회할 수 있다.
SELECT LAST_NUMBER FROM USER_SEQUENCES WHERE SEQUENCE_NAME = ‘시퀀스명(대문자)’;
다중 for문의 레이블
aaa: for(char c=’A’;c<=’C’;c++){
for(int i=1;i<=3;i++){
if(i==2) continue;
if(c==’B’) continue aaa;
System.out.println(“c = ” + c + “,i = ” + i);
}
}
function getValueInTag(_fullstr, _tagname){
var start = 0;
var end = 0;
var find_value = “”;
start = _fullstr.indexOf(“>”, _fullstr.indexOf(“<” + _tagname + “>”));
end = _fullstr.indexOf(“</” + _tagname + “>”);
find_value = _fullstr.substring(start+1, end);
return find_value;
}
내가짬.
파워자바 15장 예외처리
1. 예외처리란?
오류(error)
– 0으로 나눈다(잘못된 연산)
– 한계를 넘은 배열의 인덱스
– 디스크의 하드웨어 에러
– 필요한 파일 누락
오류(error)의 다른 이름 : 예외(Exception)
예외처리 : 오류를 감지하여 프로그램 종료, 오류를 처리후 실행지속
예외도 하나의 객체로 취급 -> 예외 객체 (Exception object)
던지다(throw) : 예외 객체의 생성
잡는다(catch) : 예외를 잡는다.
버그와 예외 : 자바에서는 버그도 예외로 취급하지만, 버그는 개발 과정에서 모두 수정되어야 하는 부분임. 진정한 의미에서의 예외는 ‘예상하지 못했던 상황’을 의미함.
2. 예외처리기의 개요
try{
//대상 코드
}catch([예외종류] [참조변수]){
//예외 처리 내용
}
예외 발생 차단 : 미리 데이터를 테스트해서 예외가 일어나지 않도록 조치.
ex) 나누기 전에 분모가 0인지 미리 검사, Scanner의 scan.nextInt()를 쓰려면 scan.hasNextInt()가 true일 때만 실행.
finally 블록 : 오류가 발생하였건 발생하지 않았던 항상 실행되어야 하는 코드
3. 예외의 종류
자바에서는 오류가 발생하면 예외 객체가 생성된다. 예외 객체는 Throwable로부터 파생되는 여러 클래스들의 인스턴스이다.
Error와 Exception : 모든 예외는 Throwable로부터 상속되어서 Error와 Exception이라고 하는 두 개의 클래스로 나눠진다.
Error란 시스템에서 발생하는 심각한 오류이다. Exception은 프로그래밍 시에 흔히 발생하는 일반 오류를 말한다. Exception은 RuntimeException과 IOException으로 나뉜다. RuntimeException은 실행 중 어느때라도 발생될 수 있는 에러이며, 발생하면 100% 프로그래머 잘못인 프로그래머 버그이다.
체크 예외와 비체크 예외 : RuntimeException은 비체크 예외(unchecked exceptions)이라고도 한다. 컴파일러는 비체크 예외를 예방했는지 확인하지 않으므로, 코드에서 반드시 예방하지 않아도 된다.
반면 체크 예외(checked exceptions)는 그 밖의 모든 예외이다. 체크 예외는 코드에서 반드시 처리해주어야 한다.
다형성과 예외: 예외를 처리할 때에 상위 클래스를 이용하면 하위 클래스까지 포괄적으로 처리할 수 있다.
ex) NumberException을 활용하면 하위 클래스인 TooBigException, TooSmallException 모두 잡을 수 있다.
다만 Exception e 는 하위 클래스를 잡을 수 있으나 분간할 수 없다.
4. 예외와 메소드
키워드 throws는 메소드가 발생할 수 있는 예외들을 나열하는데 사용된다.
예외 발생 메소드 예제 : 예외처리를 하는 방법에는 두 가지가 있다.
(1) try~catch 절은 예외를 그 자리에서 처리한다.
(2) public [형] [메소드명] throws [예외종류]는 예외를 상위 메소드로 전달한다.
※ 메소드의 호출 순서는 호출 스택(call stack)에 의하여 기억된다. 그러므로 메소드가 종료되어도 되돌아갈 메소드를 찾을 수 있다.
5. 예외 생성하기
예외 던지고 받기: 자바에서의 예외는 throw문을 이용하여 발생된다. throw문의 인수는 Throwable에서 파생된 어떤 클래스의 객체라도 가능하다.
사용자 정의 예외: 사용자도 예외 객체를 정의할 수 있다. 보통 Exception 클래스의 서브 클래스를 생성시켜서 만든다.
ex) public class [Exception명] extends Exception {}
여러 개의 예외를 주고 받는 방법: 메소드가 여러 개의 예외를 발생/전달하려면 컴마를 이용하여 예외를 throws 다음에 나열하면 된다.
ex) public void [메소드명] throws NetworkException, DiskException
j쿼리 ajax
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″>
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js“></script>
</head>
<body>
<p>Result : <span id=”time”></span></p>
<script>
$(document).ready(function(){
var xhr = new XMLHttpRequest();
xhr.open(‘GET’, ‘./call_url.jsp’);
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
//$(‘#time’).html(decodeURIComponent(xhr.responseText));
$(‘#time’).text(xhr.responseText);
}
}
xhr.send();
});
</script>
</body>
</html>
한글 in값, 한자 int값, 알파벳 int값
글자(char)의 int값을 알아내는 법은,
(int)’가’
(int)’힣’
식으로 쓰면 된다.
한글의 int값은 ‘가’부터 ‘힣’까지 이므로, 컴퓨터 환경마다 다르지만 일단 내 컴에서는, 44032 ‘가’ ~ 55203 ‘힣’ 이다.
한자는 순서가 정해져 있지 않아서 알아내기가 힘든데, 대충 3천자 정도가 있다고 알려져 있다.
한자의 시작은 19968 ‘一'(한 일)부터이며, 끝은 알 수 없다. 일단 한글의 시작 직전인 44031까지라고 추정해볼 수 있다.
결론은 19968 ‘一'(한 일) ~ 44031 ‘?'(글자가 깨짐)로 쓰거나, 40860 ‘龜’ (거북 구) 까지로 쓰면 될듯 하다.
컴퓨터랑 관계없이 돌도록 하려면 자바에서
int temp_char = (int) str.toCharArray()[ k ];
(temp_char >= 44032 && temp_char <= 55203) 가 아니라,
int temp_char = (int) str.toCharArray()[ k ];
(temp_char >= ‘가’ && temp_char <= ‘힣’)으로 쓰는게 현명하다.
//48~57 : 0~9
//97~122 : a~z
//65~90 : A~Z
//19968~44031 : 한자. 一 ~ ?
//44032 가 ~ 55203 힣
//12593 ㄱ~ 12622 ㅎ
//12623 ㅏ~ 12643 ㅣ
sql developer(sql디벨로퍼)에서 blob 받기

sql developer에서 blob을 받으려면 위 그림처럼 수행하면 된다.
DB에 접속 – 블랍이 있는 테이블 선택 – <데이터> 탭 선택 – 블랍이 있는 컬럼 더블클릭 – 연필 모양 클릭 – “값 편집”창에서 “다운로드” 클릭
쿠키(Cookie)
$(document).ready(function(){
// 저장된 쿠키값을 가져와서 ID 칸에 넣어준다. 없으면 공백으로 들어감.
var userInputId = getCookie(“userInputId”);
$(“input[name=’input_userID’]”).val(userInputId);
if($(“input[name=’input_userID’]”).val() != “”){
$(“#remember”).attr(“checked”, true);
}
});
function setCookie(cookieName, value, exdays){
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var cookieValue = escape(value) + ((exdays==null) ? “” : “; expires=” + exdate.toGMTString());
document.cookie = cookieName + “=” + cookieValue;
}
function deleteCookie(cookieName){
var expireDate = new Date();
expireDate.setDate(expireDate.getDate() – 1);
document.cookie = cookieName + “= ” + “; expires=” + expireDate.toGMTString();
}
function getCookie(cookieName) {
cookieName = cookieName + ‘=’;
var cookieData = document.cookie;
var start = cookieData.indexOf(cookieName);
var cookieValue = ”;
if(start != -1){
start += cookieName.length;
var end = cookieData.indexOf(‘;’, start);
if(end == -1)end = cookieData.length;
cookieValue = cookieData.substring(start, end);
}
return unescape(cookieValue);
}
로그인 버튼 누르는 부분에 아래를 넣는다.
//쿠키보관
if($(“#remember”).is(“:checked”)){
var userInputId = $(“input[name=’input_userID’]”).val();
setCookie(“userInputId”, userInputId, 7); // 7일 동안 쿠키 보관
}
else{
deleteCookie(“userInputId”);
}
getElementsByName
ex) document.getElementsByName(“tag_name”)[0].value = “값”;
getElementById 는 Element 이지만
getElementsByName 는 name이 여러개가 있을 수 있으므로 Elements 를 쓰고
뒤에 배열식으로 [숫자]를 붙인다.
[JAVA] 자바 파일카피 / 자바 파일복사 / java copy file (191205 수정)
|
FileInputStream inputStream = new FileInputStream( origin_file ); |
이를 쓸만한 메서드 형태로 만들어보면 아래와 같다.
|
public boolean copyFile(File originFile, File newFile) throws Exception { long size = fcin.size(); } finally { } else { // 역슬래시를 슬래시로 모두 변경 // 슬래시 2개를 슬래시 1개로 모두 변경 // 필요한 디렉토리 만들기 if (lastSlashPos > -1) { } else { return bResult; |