메뉴 건너뛰기

Bigdata, Semantic IoT, Hadoop, NoSQL

Bigdata, Hadoop ecosystem, Semantic IoT등의 프로젝트를 진행중에 습득한 내용을 정리하는 곳입니다.
필요한 분을 위해서 공개하고 있습니다. 문의사항은 gooper@gooper.com로 메일을 보내주세요.


Drools 슬라이딩 윈도우 예제

총관리자 2016.07.28 15:03 조회 수 : 67

---결과 값 -------------

 init session.getFactCount() = 0

speed: 602.92267

speed: 601.1532

speed: 607.839

speed: 600.9022

speed: 609.21796

speed: 602.91187

speed: 604.02515

speed: 608.272

speed: 607.80176

speed: 606.90405

AA001 average speed: 605.982958984375

AA001 average speed: 605.982958984375

AA001 average speed: 605.982958984375

AA001 average speed: 605.982958984375

AA001 average speed: 605.982958984375

AA001 average speed: 605.982958984375

AA001 average speed: 605.982958984375

AA001 average speed: 605.982958984375

AA001 average speed: 605.982958984375

AA001 average speed: 605.982958984375

 matched count of Fact = 10


-------sliding_rules.drl--------------

package com.gooper.drool_test;


import com.gooper.drool_test.model.FlightStatus

import com.gooper.drool_test.model.FlightControl

import com.gooper.drool_test.model.EmergencySignal


declare FlightStatus

    @role(event)

end


declare EmergencySignal

    @role(event)

end


rule "First contact"

salience 100

when

    $currentFlight : FlightStatus() from entry-point "flight-control"

    not (exists (FlightStatus(this != $currentFlight, flight == $currentFlight.flight) from entry-point "flight-control"))

    $control : FlightControl()

then

    $control.addFlight($currentFlight);

    System.out.println("First contact with Flight " + $currentFlight.getFlight());

end


rule "flight arrival"

when

    $flight : FlightStatus() from entry-point "flight-arrival"

    $control : FlightControl()

    // Obtain resources to prepare the flight landing

then

    System.out.println("Flight " + $flight.getFlight() + " arriving to " + $control.getAirport() + ". Sending instructions");

    // Send instructions to arriving flight

end


rule "flight average speed"

when

    $flight : FlightStatus() from entry-point "flight-control"

    $averageSpeed : Number(floatValue > 0) from accumulate(FlightStatus(flight==$flight.flight, $speed:speed) over window:length(5) 

                                                          from entry-point "flight-control",

                                                          average($speed))

then

    System.out.println($flight.getFlight() + " average speed: " + $averageSpeed);

end



-------------------SlidingWindow.java-----------------------

package com.gooper.drool_test;


import java.util.concurrent.TimeUnit;


import org.drools.core.time.SessionPseudoClock;

import org.kie.api.KieBase;

import org.kie.api.KieBaseConfiguration;

import org.kie.api.conf.EventProcessingOption;

import org.kie.api.io.ResourceType;

import org.kie.api.runtime.KieSession;

import org.kie.api.runtime.KieSessionConfiguration;

import org.kie.api.runtime.conf.ClockTypeOption;

import org.kie.api.runtime.rule.EntryPoint;

import org.kie.internal.KnowledgeBaseFactory;

import org.kie.internal.builder.KnowledgeBuilder;

import org.kie.internal.builder.KnowledgeBuilderFactory;

import org.kie.internal.io.ResourceFactory;


import com.gooper.drool_test.custom.CustomAgendaEventListener;

import com.gooper.drool_test.custom.CustomWorkingMemoryEventListener;

import com.gooper.drool_test.helper.FlightSimulation;

import com.gooper.drool_test.model.FlightStatus;


import org.kie.internal.builder.KnowledgeBuilderError;


/* 

 * Sliding-window test

 */

public class SlidingWindow {


public static final void main(String[] args) {

               try {


              // 지식 빌더 생성

                    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

                    

                    // 지식 빌더에 룰정의파일 설정

                    kbuilder.add(ResourceFactory. newClassPathResource("sliding_rules.drl"), ResourceType. DRL );


if (kbuilder.hasErrors()) {

if(kbuilder.getErrors().size() > 0) {

for(KnowledgeBuilderError kerror : kbuilder.getErrors()) {

System.out.println("error :" + kerror);

}

}

}

// 설정정보를 변경하기위한 config접근 정보를 얻음

KieBaseConfiguration config = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();

config.setOption(EventProcessingOption.STREAM);

KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();

conf.setOption(ClockTypeOption.get("pseudo"));

// 새로운 지식 베이스 생성

                    KieBase kiebase = kbuilder.newKnowledgeBase();

                    

                    // 새로운 지식 베이스 세션 생성

                    KieSession session = kiebase.newKieSession(conf,null);

                    

                    // logger등록(팩트에 의해 생성된 엑티베이션(Activation)관련 이벤트만 로깅)

                    //session.addEventListener(new CustomAgendaEventListener());

                    

                    // logger등록(팩트의 추가/수정/제거 이벤트에 대한 정보)

                    //session.addEventListener(new CustomWorkingMemoryEventListener());

                    

                    System.out.println(" init session.getFactCount() = " + session.getFactCount());

                    

                    // SessionClock의 레퍼런스를 얻는다

                    SessionPseudoClock clock = session.getSessionClock();

                    

                    FlightSimulation flightAA001 = new FlightSimulation("AA001", "San Francisco", "Los Angeles", 270);

                    

                    for(int i = 0; i < 10; i++) {

                    FlightStatus flightStatus = flightAA001.update();

                    EntryPoint flightArrivalEntryPoint = session.getEntryPoint("flight-control");

                    flightArrivalEntryPoint.insert(flightStatus);

                    clock.advanceTime(5,  TimeUnit.MINUTES);

                    Thread.sleep(100);

                    }

                    

                    int matchedCnt = session.fireAllRules();

                    System.out.println(" matched count of Fact = " + matchedCnt);

                    

                    session.dispose();


              } catch (Throwable t) {

                     t.printStackTrace();

              }

       }

}


----------------------FlightSimulation.java------------------------

package com.gooper.drool_test.helper;


import java.util.Random;

import com.gooper.drool_test.model.FlightStatus;



/**

 * 

 * @author Lucas Amador

 * 

 */

public class FlightSimulation {


    private static final int AIRPORT_AIR_SPACE = 50;

    private Random rnd = new Random();


    private final String flight;

    private final String origin;

    private final String destination;

    private long distance;

    private boolean landed;


    public FlightSimulation(String flight, String origin, String destination, long distance) {

        this.flight = flight;

        this.origin = origin;

        this.destination = destination;

        this.distance = distance;

    }


    public FlightStatus update() {

        FlightStatus flightStatus = new FlightStatus();

        flightStatus.setFlight(flight);

        flightStatus.setDestination(destination);

        flightStatus.setOrigin(origin);

        flightStatus.setDestination(destination);

        this.distance = calculateDistance();

        flightStatus.setDistance(this.distance);

        flightStatus.setSpeed(currentSpeed());

        System.out.println("speed: " + flightStatus.getSpeed());

        return flightStatus;

    }


    private long calculateDistance() {

        if ((distance - AIRPORT_AIR_SPACE) <= AIRPORT_AIR_SPACE) {

            landed = true;

            return 0;

        }

        return distance - AIRPORT_AIR_SPACE;

    }


    private float currentSpeed() {

        return (rnd.nextFloat() * 10) + 600;

    }


    public boolean isLanded() {

        return landed;

    }


}





--------------------------FlightStatus.java--------------------
package com.gooper.drool_test.model;

import java.util.Date;

/**
 * 
 * @author Lucas Amador
 * 
 */
public class FlightStatus {

    private String flight;
    private Date timestamp;
    private String origin;
    private String destination;
    private long distance;
    private float speed;
    private boolean processed;

    public String getFlight() {
        return flight;
    }

    public void setFlight(String flight) {
        this.flight = flight;
    }

    public Date getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }

    public String getOrigin() {
        return origin;
    }

    public void setOrigin(String origin) {
        this.origin = origin;
    }

    public String getDestination() {
        return destination;
    }

    public void setDestination(String destination) {
        this.destination = destination;
    }

    public long getDistance() {
        return distance;
    }

    public void setDistance(long distance) {
        this.distance = distance;
    }

    public float getSpeed() {
        return speed;
    }

    public void setSpeed(float speed) {
        this.speed = speed;
    }

    public void setProcessed(boolean processed) {
        this.processed = processed;
    }

    public boolean getProcessed() {
        return processed;
    }

@Override
public String toString() {
return "FlightStatus [flight=" + flight + ", timestamp=" + timestamp + ", origin=" + origin + ", destination="
+ destination + ", distance=" + distance + ", speed=" + speed + ", processed=" + processed
+ ", getFlight()=" + getFlight() + ", getTimestamp()=" + getTimestamp() + ", getOrigin()=" + getOrigin()
+ ", getDestination()=" + getDestination() + ", getDistance()=" + getDistance() + ", getSpeed()="
+ getSpeed() + ", getProcessed()=" + getProcessed() + ", getClass()=" + getClass() + ", hashCode()="
+ hashCode() + ", toString()=" + super.toString() + "]";
}
    
    

}

번호 제목 글쓴이 날짜 조회 수
740 bananapi 5대(ubuntu계열 리눅스)에 yarn(hadoop 2.6.0)설치하기-ResourceManager HA/HDFS HA포함, JobHistory포함 총관리자 2015.04.24 19143
739 mapreduce appliction을 실행시 "is running beyond virtual memory limits" 오류 발생시 조치사항 총관리자 2017.05.04 16898
738 org.apache.hadoop.hdfs.server.common.InconsistentFSStateException: Directory /tmp/hadoop-root/dfs/name is in an inconsistent state: storage directory does not exist or is not accessible. 구퍼 2013.03.11 14781
737 drop table로 삭제했으나 tablet server에는 여전히 존재하는 테이블 삭제방법 총관리자 2021.07.09 7554
736 insert hbase by hive ... error occured after 5 hours..HMaster가 뜨지 않는 장애에 대한 복구 방법 총관리자 2014.04.29 7129
735 Resource temporarily unavailable(자원이 일시적으로 사용 불가능함) 오류조치 총관리자 2015.11.19 6857
734 HBase shell로 작업하기 구퍼 2013.03.15 5834
733 dr.who로 공격들어오는 경우 조치방법 file 총관리자 2018.06.09 5603
732 하둡 분산 파일 시스템을 기반으로 색인하고 검색하기 구퍼 2013.03.15 5573
731 [Decommission]시 시간이 많이 걸리면서(수일) Decommission이 완료되지 않는 경우 조치 총관리자 2018.01.03 5323
730 Ubuntu 16.04LTS 설치후 초기에 주어야 하는 작업(php, apache, mariadb설치및 OS보안설정등) file 총관리자 2017.05.23 5270
729 hive 2.0.1 설치및 mariadb로 metastore 설정 총관리자 2016.06.03 5184
728 Hive Query Examples from test code (2 of 2) 총관리자 2014.03.26 5012
727 Spark에서 Serializable관련 오류및 조치사항 총관리자 2017.04.21 4901
726 [gson]mongodb의 api를 이용하여 데이타를 가져올때 "com.google.gson.stream.MalformedJsonException: Unterminated object at line..." 오류발생시 조치사항 총관리자 2017.12.11 4415
725 import 혹은 export할때 hive파일의 default 구분자는 --input-fields-terminated-by "x01"와 같이 지정해야함 총관리자 2014.05.20 4245
724 checking for termcap functions library... configure: error: No curses/termcap library found 구퍼 2013.03.08 4120
723 sqoop작업시 hdfs의 개수보다 더많은 값이 중복되어 oracle에 입력되는 경우가 있음 총관리자 2014.09.02 4093
722 다수의 로그 에이전트로 부터 로그를 받아 각각의 파일로 저장하는 방법(interceptor및 multiplexing) 총관리자 2014.04.04 4089
721 .git폴더를 삭제하고 다시 git에 추가하고 서버에 반영하는 방법 총관리자 2017.06.19 4077

A personal place to organize information learned during the development of such Hadoop, Hive, Hbase, Semantic IoT, etc.
We are open to the required minutes. Please send inquiries to gooper@gooper.com.

위로