<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/data/DeviceData.java<|end_filename|>
package org.uclab.mm.icl.data;

/*
Copyright [2016] [<NAME>, Kang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * This interface defines the structure of the Sensordata classes, which represents the raw data sent from each devices.
 * @author Nailbrainz
 *
 */
public interface DeviceData {
	
	/**
	 * Getter for the userID of DataType
	 * @return user Id
	 */
	public abstract Long getUserID();
	
	/**
	 * Getter for the userID of DataType 
	 * @param userID will be set into the DataType instance
	 */
	public abstract void setUserID(long userID);
	
	/**
	 * Getter for the getTimeStamp of DataType
	 * @return timeStamp encoded in the data instance
	 */
	public abstract String getTimeStamp();
	
	/**
	 * Getter for the timeStamp of DataType 
	 * @param timeStamp will be set into the DataType instance
	 */
	public abstract void setTimeStamp(String timeStamp);
	
	/**
	 * This function transforms the data sent from each devices, into ICL usable format.
	 * The method of decoding is dependent on each child class
	 * @param input Encoded data sent from device
	 */
	public abstract void setData(Object input);
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/Achievements.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author <NAME>
 */
@Entity
public class Achievements implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private Long achievementID;
    private Long userID;
    private String achievementValue;
    private String achievementDescription;
    private String achievementDate;
    private String supportingLink;
    private int achievementStatusID;
    
    private String achievementStatusDescription;
    
    private String requestType;
    private String startDate;
    private String endDate;
    
    
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Achievements)) {
            return false;
        }
        Achievements other = (Achievements) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.sc.Achievements[ id=" + id + " ]";
    }

    /**
     * @return the achievementID
     */
    public Long getAchievementID() {
        return achievementID;
    }

    /**
     * @param achievementID the achievementID to set
     */
    public void setAchievementID(Long achievementID) {
        this.achievementID = achievementID;
    }

    /**
     * @return the userID
     */
    public Long getUserID() {
        return userID;
    }

    /**
     * @param userID the userID to set
     */
    public void setUserID(Long userID) {
        this.userID = userID;
    }

    /**
     * @return the achievementValue
     */
    public String getAchievementValue() {
        return achievementValue;
    }

    /**
     * @param achievementValue the achievementValue to set
     */
    public void setAchievementValue(String achievementValue) {
        this.achievementValue = achievementValue;
    }

    /**
     * @return the achievementDescription
     */
    public String getAchievementDescription() {
        return achievementDescription;
    }

    /**
     * @param achievementDescription the achievementDescription to set
     */
    public void setAchievementDescription(String achievementDescription) {
        this.achievementDescription = achievementDescription;
    }

    /**
     * @return the achievementDate
     */
    public String getAchievementDate() {
        return achievementDate;
    }

    /**
     * @param achievementDate the achievementDate to set
     */
    public void setAchievementDate(String achievementDate) {
        this.achievementDate = achievementDate;
    }

    /**
     * @return the supportingLink
     */
    public String getSupportingLink() {
        return supportingLink;
    }

    /**
     * @param supportingLink the supportingLink to set
     */
    public void setSupportingLink(String supportingLink) {
        this.supportingLink = supportingLink;
    }

    /**
     * @return the achievementStatusID
     */
    public int getAchievementStatusID() {
        return achievementStatusID;
    }

    /**
     * @param achievementStatusID the achievementStatusID to set
     */
    public void setAchievementStatusID(int achievementStatusID) {
        this.achievementStatusID = achievementStatusID;
    }

    /**
     * @return the achievementStatusDescription
     */
    public String getAchievementStatusDescription() {
        return achievementStatusDescription;
    }

    /**
     * @param achievementStatusDescription the achievementStatusDescription to set
     */
    public void setAchievementStatusDescription(String achievementStatusDescription) {
        this.achievementStatusDescription = achievementStatusDescription;
    }

    /**
     * @return the requestType
     */
    public String getRequestType() {
        return requestType;
    }

    /**
     * @param requestType the requestType to set
     */
    public void setRequestType(String requestType) {
        this.requestType = requestType;
    }

    /**
     * @return the startDate
     */
    public String getStartDate() {
        return startDate;
    }

    /**
     * @param startDate the startDate to set
     */
    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }

    /**
     * @return the endDate
     */
    public String getEndDate() {
        return endDate;
    }

    /**
     * @param endDate the endDate to set
     */
    public void setEndDate(String endDate) {
        this.endDate = endDate;
    }
    
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/AER/vui/InputAdapter.java<|end_filename|>
/*
Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.AER.vui;

public class InputAdapter {
	private String userId;
	private String deviceId;
	private String timestamp;
	private double[] samples;
	
	public String getUserId() {
		return userId;
	}
	
	public String getDeviceId() {
		return deviceId;
	}
	
	public String getTimestamp() {
		return timestamp;
	}
	
	public double[] getSamples() {
		return samples;
	}
	
	public void parseRawData() {
		
	}
}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/framework/RecInterpreter/Explanation/URLBuilder.java<|end_filename|>
/* Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.scl.framework.RecInterpreter.Explanation;
import java.util.HashMap;
import java.util.concurrent.ThreadLocalRandom;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class URLBuilder {
  private static Logger LOG = LogManager.getRootLogger();
  
  HashMap<String, String> mapExpURL = new HashMap<>();
  public String recURLBuilder(String rec) throws Exception {

    ExpURLMapper mapperExpURL = new ExpURLMapper();
    mapExpURL = mapperExpURL.mapExpURL();
    String retrievedURLList;

    retrievedURLList = mapExpURL.containsKey(rec) ? mapExpURL.get(rec): mapExpURL.get(null);
    String[] retrievedURLArr = null;
    String selectedURL = null;

    if (retrievedURLList == null)
      LOG.debug("Recommendation NOT FOUND in the URL repository");
    else {
      retrievedURLArr = retrievedURLList.split(",");
      selectedURL = retrievedURLArr[(ThreadLocalRandom.current().nextInt(0,retrievedURLArr.length))];
    }
    return (selectedURL);
  }
}


<|start_filename|>data-curation-layer/active-data-reader/src/main/java/org/uclab/mm/dcl/adr/connect/GenerateSchema.java<|end_filename|>
/*
 * Copyright (C) 2016 <NAME>.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.mm.dcl.adr.connect;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class GenerateSchema {
	private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
	 
	  /**
  	 * The main method.
  	 *
  	 * @param args the arguments
  	 * @throws SQLException the SQL exception
  	 */
  	public static void main(String[] args) throws SQLException {
	    try {
	      Class.forName(driverName);
	    } catch (ClassNotFoundException e) {
	      // TODO Auto-generated catch block
	      e.printStackTrace();
	      System.exit(1);
	    }
	    Connection con = DriverManager.getConnection("jdbc:hive2://172.16.58.3:10000/test1", "hive", "hive");
	    Statement stmt = con.createStatement();
	    String tableName = "getlocation";
	    stmt.executeQuery("drop table " + tableName);
	    ResultSet res = stmt.executeQuery("create table " + tableName + " (key int, value string)");
	    // show tables
	    String sql = "show tables '" + tableName + "'";
	    System.out.println("Running: " + sql);
	    res = stmt.executeQuery(sql);
	    if (res.next()) {
	      System.out.println(res.getString(1));
	    }
	    // describe table
	    sql = "describe " + tableName;
	    System.out.println("Running: " + sql);
	    res = stmt.executeQuery(sql);
	    while (res.next()) {
	      System.out.println(res.getString(1) + "\t" + res.getString(2));
	    }
	 
	    // load data into table
	    // NOTE: filepath has to be local to the hive server
	    // NOTE: /tmp/a.txt is a ctrl-A separated file with two fields per line
	    String filepath = "/tmp/a.txt";
	    sql = "load data local inpath '" + filepath + "' into table " + tableName;
	    System.out.println("Running: " + sql);
	    res = stmt.executeQuery(sql);
	 
	    // select * query
	    sql = "select * from " + tableName;
	    System.out.println("Running: " + sql);
	    res = stmt.executeQuery(sql);
	    while (res.next()) {
	      System.out.println(String.valueOf(res.getInt(1)) + "\t" + res.getString(2));
	    }
	 
	    // regular hive query
	    sql = "select count(1) from " + tableName;
	    System.out.println("Running: " + sql);
	    res = stmt.executeQuery(sql);
	    while (res.next()) {
	      System.out.println(res.getString(1));
	    }
	  }

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/ic/Device.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.ic;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 *
 * @author Taqdir
 */
@Entity
public class Device implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    
    private Long deviceId;
    private String deviceName;
    private int deviceTypeId;
    private String deviceModel;
    //private GregorianCalendar registrationDate; // updated
    private String registrationDate;
    
    

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Device)) {
            return false;
        }
        Device other = (Device) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.ic.Device[ id=" + id + " ]";
    }

    /**
     * @return the deviceId
     */
    public Long getDeviceId() {
        return deviceId;
    }

    /**
     * @param deviceId the deviceId to set
     */
    public void setDeviceId(Long deviceId) {
        this.deviceId = deviceId;
    }

    /**
     * @return the deviceName
     */
    public String getDeviceName() {
        return deviceName;
    }

    /**
     * @param deviceName the deviceName to set
     */
    public void setDeviceName(String deviceName) {
        this.deviceName = deviceName;
    }

    /**
     * @return the deviceTypeId
     */
    public int getDeviceTypeId() {
        return deviceTypeId;
    }

    /**
     * @param deviceTypeId the deviceTypeId to set
     */
    public void setDeviceTypeId(int deviceTypeId) {
        this.deviceTypeId = deviceTypeId;
    }

    /**
     * @return the deviceModel
     */
    public String getDeviceModel() {
        return deviceModel;
    }

    /**
     * @param deviceModel the deviceModel to set
     */
    public void setDeviceModel(String deviceModel) {
        this.deviceModel = deviceModel;
    }

    /**
     * @return the registrationDate
     * updated to string
     */
    public String getRegistrationDate() {
        return registrationDate;
    }

    /**
     * @param registrationDate the registrationDate to set
     * updated to string
     */
    public void setRegistrationDate(String registrationDate) {
        this.registrationDate = registrationDate;
    }
    
}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/interpreterdatamodel/CurrentContext.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.interpreterdatamodel;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;

/**
 * @version MM v2.5
 * @author Afzal
 *
 */
// @JsonIgnoreProperties(ignoreUnknown = true)
public class CurrentContext implements Serializable {

  @JsonProperty("id")
  private Long id;

  @JsonProperty("userID")
  private Long userID;

  @JsonProperty("startTime")
  private String startTime;

  @JsonProperty("endTime")
  private String endTime;

  @JsonProperty("objListUserDetectedLocation")
  private Set<CurrentLocation> objListUserDetectedLocation = new HashSet<CurrentLocation>();

  @JsonProperty("objListUserRecognizedEmotion")
  private List<CurrentEmotion> objListUserRecognizedEmotion = new ArrayList<CurrentEmotion>();

  @JsonProperty("objListUserRecognizedHLC")
  private List<CurrentHLC> objListUserRecognizedHLC = new ArrayList<CurrentHLC>();

  @JsonProperty("objListUserRecognizedActivity")
  private List<RecognizedActivity> objListUserRecognizedActivity = new ArrayList<RecognizedActivity>();

  private List<CurrentWeather> currentWeather = new ArrayList<CurrentWeather>();

  /**
   * @return the objListUserDetectedLocation
   */
  public Set<CurrentLocation> getCurrentLocation() {
    return objListUserDetectedLocation;
  }

  /**
   * @param currentLocation
   *          the objListUserDetectedLocation to set
   */
  public void setCurrentLocation(Set<CurrentLocation> currentLocation) {
    this.objListUserDetectedLocation = currentLocation;
  }

  /**
   * @return the objListUserRecognizedEmotion
   */
  public List<CurrentEmotion> getCurrentEmotion() {
    return objListUserRecognizedEmotion;
  }

  /**
   * @param currentEmotion
   *          the objListUserRecognizedEmotion to set
   */
  public void setCurrentEmotion(List<CurrentEmotion> currentEmotion) {
    this.objListUserRecognizedEmotion = currentEmotion;
  }

  /**
   * @return the objListUserRecognizedHLC
   */
  public List<CurrentHLC> getCurrentHLC() {
    return objListUserRecognizedHLC;
  }

  /**
   * @param currentHLC
   *          the objListUserRecognizedHLC to set
   */
  public void setCurrentHLC(List<CurrentHLC> currentHLC) {
    this.objListUserRecognizedHLC = currentHLC;
  }

  /**
   * @return the objListUserRecognizedActivity
   */
  public List<RecognizedActivity> getRecActivity() {
    return objListUserRecognizedActivity;
  }

  /**
   * @param recActivity
   *          the objListUserRecognizedActivity to set
   */
  public void setRecActivity(List<RecognizedActivity> recActivity) {
    this.objListUserRecognizedActivity = recActivity;
  }

  /**
   * @return the currentWeather
   */
  @JsonIgnore
  public List<CurrentWeather> getCurrentWeather() {
    return currentWeather;
  }

  /**
   * @param currentWeather
   *          the currentWeather to set
   */
  public void setCurrentWeather(List<CurrentWeather> currentWeather) {
    this.currentWeather = currentWeather;
  }

  /**
   * @return the id
   */
  public Long getId() {
    return id;
  }

  /**
   * @param id
   *          the id to set
   */
  public void setId(Long id) {
    this.id = id;
  }

  /**
   * @return the userID
   */
  public Long getUserID() {
    return userID;
  }

  /**
   * @param userID
   *          the userID to set
   */
  public void setUserID(Long userID) {
    this.userID = userID;
  }

  /**
   * @return the startTime
   */
  public String getStartTime() {
    return startTime;
  }

  /**
   * @param startTime
   *          the startTime to set
   */
  public void setStartTime(String startTime) {
    this.startTime = startTime;
  }

  /**
   * @return the endTime
   */
  public String getEndTime() {
    return endTime;
  }

  /**
   * @param endTime
   *          the endTime to set
   */
  public void setEndTime(String endTime) {
    this.endTime = endTime;
  }

}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/framework/recbuilder/RecBuilder.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.uclab.scl.framework.recbuilder;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.uclab.scl.communication.ConditionsValueService;
import org.uclab.scl.communication.RulesService;
import org.uclab.scl.datamodel.FiredRule;
import org.uclab.scl.datamodel.RecommendationIngredients;
import org.uclab.scl.datamodel.SituationEvent;
import org.uclab.scl.datamodel.Situations;
import org.uclab.scl.framework.AbstractRecBuilder;
import org.uclab.scl.framework.AbstractRecBuilderPacket;

public class RecBuilder extends AbstractRecBuilder {
  private static Logger LOG = LogManager.getRootLogger();
  
  private AbstractPatternMatcher patternMatcher;
  private AbstractConflictResolver conflictResolver;
  private RulesService ruleService;
  
  /**
   * Instantiates RecommendationBuilder by using patternMatcher & conflictResolver
   * 
   * <p>
   * @param patternMatcher
   * @param conflictResolver
   */
  public RecBuilder(AbstractPatternMatcher patternMatcher, AbstractConflictResolver conflictResolver){
    this.patternMatcher = patternMatcher;
    this.conflictResolver = conflictResolver;
  }
  /**
   * generates recommendation based on the ISCLDataPacket
   * <p> 
   * 
   * @param ISCLDataPacket
   * @return
   */
  @Override
  public void buildRecommendation(AbstractRecBuilderPacket abstractRecBuilderPacket) {
    LOG.debug("building recommendation...");
    RecBuilderPacket recBuilderPacket = (RecBuilderPacket) abstractRecBuilderPacket;
    RecommendationIngredients recIngredients = new RecommendationIngredients();
    recIngredients = recBuilderPacket.getRecommendationInput();
    SituationEvent situationEvent = recIngredients.getsNotification().getSituationEvent();

    Situations situation = new Situations(situationEvent.getSituationID());
    situation.setListSConditions(situationEvent.getListSConditions());

    List<FiredRule> resolvedRules = getFinalResolvedRules(situation, recIngredients.getJSONKeyValue());
    recBuilderPacket.setRecommendationOutput(resolvedRules);
  }
  
  /**
   * returns the final resolved rules after resolving conflict
   * <p>
   * 
   * @param situation
   * @param conditionValueJSON
   * @return
   */
  public List<FiredRule> getFinalResolvedRules(Situations situation, String conditionValueJSON) {
 
    LOG.debug("Firing rules...");
     List<FiredRule> finalResolvedRules = null;
    try{
      List<Map<String, Object>> rules = getRuleService().setSituationsData(situation).connect().getResponse().parse();
      Map<String, Object> conditionsValue = ConditionsValueService.parse(conditionValueJSON, 1);
      List<FiredRule> firedRules = patternMatcher.fireRule(conditionsValue, rules);
      LOG.debug("Resolving conflict...");
      finalResolvedRules = conflictResolver.resolveConflict(firedRules);
    }catch(Exception e){
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      e.printStackTrace(pw);
      LOG.error(sw.toString());
    }
    return finalResolvedRules;
  }
  
  /**
   * sets the rule service
   * 
   * @param ruleService
   * @return
   */
  public void setRulesService(RulesService ruleService){
    this.ruleService = ruleService;
  }
  
  /**
   * returns the rule service instance
   * 
   * @return
   */
  public RulesService getRuleService(){
    if(ruleService == null)
      ruleService = new RulesService();
    
    return ruleService;
  }
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/data/KinectData.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Kang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.data;

import java.io.Serializable;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;



/**
 * Kinect data class
 * @author Nailbrainz
 * 
 */
public class KinectData implements DeviceData, Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	String timeStamp;
	ArrayList<double[]> ary = new ArrayList<double[]>();
	
	long userID;
	
	/**
	 * Returns the timestamp included in the Kinect data
	 * @return Time stamp of kinect data
	 */
	public String getTimeStamp() {
		return timeStamp;
	}
	
	/**
	 * Set the timestamp to kinect data
	 * @param timeStamp timestamp to set on KinectData
	 */
	public void setTimeStamp(String timeStamp) {
		this.timeStamp = timeStamp;
	}
	
	/**
	 * 
	 * @return returns Kinect data array
	 */
	public ArrayList<double[]> getAry() {
		return ary;
	}
	
	/**
	 * 
	 * @param ary kinect data 
	 */
	public void setAry(ArrayList<double[]> ary) {
		this.ary = ary;
	}
	
	/**
	 * 
	 * @return corresponding user ID of KinectData
	 */
	public Long getUserID() {
		return userID;
	}
	
	
	/**
	 * 
	 * @param userID user ID to be set on the KinectData
	 */
	public void setUserID(long userID) {
		this.userID = userID;
	}

	/**
	 * This function decodes the encoded data sent from kienct, into SensoryData class
	 * @param input Encoded data sent from the kienct
	 */
	@Override
	public void setData(Object input) {
		// TODO Auto-generated method stub
		ArrayList<double[]> ary = parseJsonInput(input.toString());
		
		
		for(int j = 0; j<ary.size(); j++){
			this.getAry().add(ary.get(j));
		}
	}
	
	
	/**
	 * This function parses the json string which is sent from kinect, into array of double[]
	 * @param str Json string, which have 25 Body skeleton data, sent from Kinect
	 * @return double[], skeleton data sent from Kinect
	 */
	ArrayList<double[]> parseJsonInput(String str){
    	JSONArray ary = new JSONArray(str);
    	ArrayList<double[]> ret = new ArrayList<double[]>();
		//System.out.println("~~~~~~~~~~~~~~~~~~");
		for(int i = 0; i<ary.length(); i++){
			JSONObject prev = new JSONObject(ary.get(i).toString());
			
			double[] data = new double[75];
			
			JSONArray prevJAry = prev.getJSONArray("points");
			for(int j = 0; j<prevJAry.length(); j++){
				JSONObject item = prevJAry.getJSONObject(j);
				data[j*3] = item.getDouble("X");
				data[j*3+1] = item.getDouble("Y");
				data[j*3+2] = item.getDouble("Z");
			}
			if(i == 0){
				userID = prev.getLong("user_id");
				timeStamp = prev.getString("timestamp_kinect");
			}
			ret.add(data);
		}
		return ret;
    }

	
}


<|start_filename|>knowledge-curation-layer/i-kat/src/main/java/org/uclab/mm/kcl/edkat/dao/ConclusionDAO.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.kcl.edkat.dao;

import java.util.List;

import org.uclab.mm.kcl.edkat.datamodel.Conclusion;





/**
* This is Data Access Object interface for the conclusion this DAO provides interfaces to 
* create, update, retrieve of conclusions of a specific rule
 * @author  <NAME>
 * @version 1.0
 * @since   2015-08-16
 * */

public interface ConclusionDAO {

	
	/**
	 * This interface function is for add new Conclusion
	 * @param objConclusion
	 * @return object of Conclusion
	*/
	public Conclusion addConclusion(Conclusion objConclusion);
	
	/**
	 *  This interface function is for update the existing Conclusion
	 *  @param objConclusion
	 *  @return object of Conclusion
	*/  
	public Conclusion updateConclusion(Conclusion objConclusion);
	
	/**
	 * This function get all conclusions of the rules
	 * @return List of Conclusion
	*/
	public List<Conclusion> listConclusion();
	
	/**
	 * This function get a specific conclusion by conclusion id (primary key)
	 * @param id
	 * @return Object of Conclusion
	*/
	public Conclusion getConclusionById(int id);
	
	/**
	 * This function delete a specific conclusion by conclusion id (primary key)
	 * @param id
	 * 
	*/
    public void removeConclusion(int id);
    
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/OntologyTools/LowLevelContext.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.OntologyTools;
import java.util.Iterator;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
import com.hp.hpl.jena.vocabulary.OWL2;
import com.hp.hpl.jena.vocabulary.RDFS.Nodes;
/**
 * Low Level Context is the class encapsulating the OntModel associated to a Low
 * Level Context Instance. This is an instance of the Low Level Context class in
 * the Context Ontology which represents the Mining Minds Context Model. This
 * class provides supporting methods to facilitate the access to Low Level
 * Context.
 * 
 * @author <NAME> and <NAME>
 * @version 2.5
 * @since 2015-10-28
 */
public class LowLevelContext extends Context {
	/**
	 * Name of the LLC category, e.g., Activity, Location or Emotion.
	 */
	private String llcCategoryName;
	/**
	 * Constructor of a new Low Level Context instance.
	 * 
	 * @param llcModel
	 *            OntModel associated to the Low Level Context instance.
	 */
	public LowLevelContext(OntModel llcModel) {
		super(llcModel);
	}
	/**
	 * Constructor of a new Low Level Context instance.
	 * 
	 * @param llcModel
	 *            OntModel associated to the Low Level Context instance.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 */
	public LowLevelContext(OntModel llcModel, ContextOntology ont) {
		super(llcModel);
		OntModel llcInst = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, llcModel);
		llcInst.addSubModel(ont.getCtxModel());
		ExtendedIterator<Individual> it = llcInst.listIndividuals();
		while (it.hasNext()) {    
			Individual inst = (Individual) it.next();
			ExtendedIterator<Resource> iter = inst.listRDFTypes(true);
			while (iter.hasNext()) {
				Resource res = iter.next();
				String uri = res.getURI();
				if (uri != null && !uri.equals(OWL2.NamedIndividual.getURI())) {
					if (!uri.equals(HLCA.userClassName)) {
						super.ctxInstanceName = inst.getURI();
						super.ctxTypeName = uri;
						StmtIterator stmtIt = res.listProperties();
						while (stmtIt.hasNext()) {
							Triple t = stmtIt.nextStatement().asTriple();
							if (t.getPredicate().equals(Nodes.subClassOf))
								this.llcCategoryName = t.getObject().getURI();    
						}
					}
				}
			}
		}
	}
	/**
	 * Method to get the name of the LLC category, e.g., Activity, Location, food or
	 * Emotion.
	 * 
	 * @return Name of the LLC category.
	 */
	public String getLlcCategoryName() {
		return llcCategoryName;
	}
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/UserGoal.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.sc;

import java.io.Serializable;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author Taqdir
 */
@Entity
public class UserGoal implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    
    private Long userGoalId;
    private Long userId;
    private int weightStatusId;
    private Long dailyCaloriesInTake;
    private float idealWeight;
    private String goalDescription;
    private Long totalCaloriesToBurn;
    private int burnedCalories;
    //private GregorianCalendar date;
    private String date;
    private int dailyBurnedCal;
    private int weklyBurnedCal;
    private int monthlyBurnedCal;
    private int quarterlyBurnedCal;
    private float bMI;
    
    private String requestType;
    private String startDate;
    private String endDate;
    
    
        

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof UserGoal)) {
            return false;
        }
        UserGoal other = (UserGoal) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.sc.UserGoal[ id=" + id + " ]";
    }

    /**
     * @return the userGoalId
     */
    public Long getUserGoalId() {
        return userGoalId;
    }

    /**
     * @param userGoalId the userGoalId to set
     */
    public void setUserGoalId(Long userGoalId) {
        this.userGoalId = userGoalId;
    }

    /**
     * @return the userId
     */
    public Long getUserId() {
        return userId;
    }

    /**
     * @param userId the userId to set
     */
    public void setUserId(Long userId) {
        this.userId = userId;
    }

    /**
     * @return the weightStatusId
     */
    public int getWeightStatusId() {
        return weightStatusId;
    }

    /**
     * @param weightStatusId the weightStatusId to set
     */
    public void setWeightStatusId(int weightStatusId) {
        this.weightStatusId = weightStatusId;
    }

    /**
     * @return the dailyCaloriesInTake
     */
    public Long getDailyCaloriesInTake() {
        return dailyCaloriesInTake;
    }

    /**
     * @param dailyCaloriesInTake the dailyCaloriesInTake to set
     */
    public void setDailyCaloriesInTake(Long dailyCaloriesInTake) {
        this.dailyCaloriesInTake = dailyCaloriesInTake;
    }

    /**
     * @return the idealWeight
     */
    public float getIdealWeight() {
        return idealWeight;
    }

    /**
     * @param idealWeight the idealWeight to set
     */
    public void setIdealWeight(float idealWeight) {
        this.idealWeight = idealWeight;
    }

    /**
     * @return the goalDescription
     */
    public String getGoalDescription() {
        return goalDescription;
    }

    /**
     * @param goalDescription the goalDescription to set
     */
    public void setGoalDescription(String goalDescription) {
        this.goalDescription = goalDescription;
    }

    /**
     * @return the totalCaloriesToBurn
     */
    public Long getTotalCaloriesToBurn() {
        return totalCaloriesToBurn;
    }

    /**
     * @param totalCaloriesToBurn the totalCaloriesToBurn to set
     */
    public void setTotalCaloriesToBurn(Long totalCaloriesToBurn) {
        this.totalCaloriesToBurn = totalCaloriesToBurn;
    }

    /**
     * @return the date updated
     */
    public String getDate() {
        return date;
    }

    /**
     * @param date the date to set
     */
    public void setDate(String date) {
        this.date = date;
    }

    /**
     * @return the dailyBurnedCal
     */
    public int getDailyBurnedCal() {
        return dailyBurnedCal;
    }

    /**
     * @param dailyBurnedCal the dailyBurnedCal to set
     */
    public void setDailyBurnedCal(int dailyBurnedCal) {
        this.dailyBurnedCal = dailyBurnedCal;
    }

    /**
     * @return the weklyBurnedCal
     */
    public int getWeklyBurnedCal() {
        return weklyBurnedCal;
    }

    /**
     * @param weklyBurnedCal the weklyBurnedCal to set
     */
    public void setWeklyBurnedCal(int weklyBurnedCal) {
        this.weklyBurnedCal = weklyBurnedCal;
    }

    /**
     * @return the monthlyBurnedCal
     */
    public int getMonthlyBurnedCal() {
        return monthlyBurnedCal;
    }

    /**
     * @param monthlyBurnedCal the monthlyBurnedCal to set
     */
    public void setMonthlyBurnedCal(int monthlyBurnedCal) {
        this.monthlyBurnedCal = monthlyBurnedCal;
    }

    /**
     * @return the quarterlyBurnedCal
     */
    public int getQuarterlyBurnedCal() {
        return quarterlyBurnedCal;
    }

    /**
     * @param quarterlyBurnedCal the quarterlyBurnedCal to set
     */
    public void setQuarterlyBurnedCal(int quarterlyBurnedCal) {
        this.quarterlyBurnedCal = quarterlyBurnedCal;
    }

    /**
     * @return the burnedCalories
     */
    public int getBurnedCalories() {
        return burnedCalories;
    }

    /**
     * @param burnedCalories the burnedCalories to set
     */
    public void setBurnedCalories(int burnedCalories) {
        this.burnedCalories = burnedCalories;
    }

    /**
     * @return the bMI
     */
    public float getbMI() {
        return bMI;
    }

    /**
     * @param bMI the bMI to set
     */
    public void setbMI(float bMI) {
        this.bMI = bMI;
    }

    /**
     * @return the requestType
     */
    public String getRequestType() {
        return requestType;
    }

    /**
     * @param requestType the requestType to set
     */
    public void setRequestType(String requestType) {
        this.requestType = requestType;
    }

    /**
     * @return the startDate
     */
    public String getStartDate() {
        return startDate;
    }

    /**
     * @param startDate the startDate to set
     */
    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }

    /**
     * @return the endDate
     */
    public String getEndDate() {
        return endDate;
    }

    /**
     * @param endDate the endDate to set
     */
    public void setEndDate(String endDate) {
        this.endDate = endDate;
    }
    
}


<|start_filename|>knowledge-curation-layer/i-kat/src/main/java/org/uclab/mm/kcl/edkat/datamodel/Rule.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.kcl.edkat.datamodel;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.JoinColumn;

/**
 * Entity bean with JPA annotations
 * Hibernate provides JPA implementation
 * @author <NAME>
 *
 */

@Entity
@Table(name="tblRules")
public class Rule implements Serializable {

	@Id
    @Column(name="RuleID")
    @GeneratedValue(strategy=GenerationType.AUTO)
	private int RuleID;
	
	@Column(name="RuleTitle")
	private String ruleTitle;
	
	@Column(name="Institution")
	private String institution;
	
	@Column(name="RuleDescription")
	private String ruleDescription;
	
	@Column(name="RuleCondition")
	private String ruleCondition;
	
	@Column(name="RuleConclusion")
	private String ruleConclusion;
	
	@Column(name="RuleCreatedDate")
	private Date ruleCreatedDate;
	
	@Column(name="RuleCreatedBy")
	private Integer ruleCreatedBy;
	
	@Column(name="SpecialistName")
	private String specialistName;
	
	@Column(name="RuleUpdatedBy")
	private Integer ruleUpdatedBy;
	
	@Column(name="RuleLastUpdatedDate")
	private Date ruleLastUpdatedDate;
	
	@Column(name="RuleTypeID")
	private Integer ruleTypeID;
	
	@Column(name="SourceClassName")
	private String sourceClassName;
	
	@Column(name="SituationID")
	private int situationID;
	
	@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
	@JoinColumn(name="RuleID")
	private List<Conclusion> conclusionList = new ArrayList<Conclusion>();
	 
	@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name = "tblRulesConditions", 
             joinColumns = { @JoinColumn(name = "RuleID") }, 
             inverseJoinColumns = { @JoinColumn(name = "ConditionID") })
    private List<Condition> conditionList = new ArrayList<Condition>();
	
	public Rule(){}
	
	public int getSituationID() {
		return situationID;
	}

	public void setSituationID(int situationID) {
		this.situationID = situationID;
	}

	public int getRuleID() {
		return RuleID;
	}

	public List<Conclusion> getConclusionList() {
		return conclusionList;
	}

	public void setConclusionList(List<Conclusion> conclusionList) {
		this.conclusionList = conclusionList;
	}

    public void setRuleID(int ruleID) {
		RuleID = ruleID;
	}

	public String getRuleTitle() {
		return ruleTitle;
	}

	public void setRuleTitle(String ruleTitle) {
		this.ruleTitle = ruleTitle;
	}

	public String getInstitution() {
		return institution;
	}

	public void setInstitution(String institution) {
		this.institution = institution;
	}

	public String getRuleDescription() {
		return ruleDescription;
	}

	public void setRuleDescription(String ruleDescription) {
		this.ruleDescription = ruleDescription;
	}

	public String getRuleCondition() {
		return ruleCondition;
	}

	public void setRuleCondition(String ruleCondition) {
		this.ruleCondition = ruleCondition;
	}

	public String getRuleConclusion() {
		return ruleConclusion;
	}

	public void setRuleConclusion(String ruleConclusion) {
		this.ruleConclusion = ruleConclusion;
	}

	public Date getRuleCreatedDate() {
		return ruleCreatedDate;
	}

	public void setRuleCreatedDate(Date ruleCreatedDate) {
		this.ruleCreatedDate = ruleCreatedDate;
	}

	public Integer getRuleCreatedBy() {
		return ruleCreatedBy;
	}

	public void setRuleCreatedBy(Integer ruleCreatedBy) {
		this.ruleCreatedBy = ruleCreatedBy;
	}

	public String getSpecialistName() {
		return specialistName;
	}

	public void setSpecialistName(String specialistName) {
		this.specialistName = specialistName;
	}

	public Integer getRuleUpdatedBy() {
		return ruleUpdatedBy;
	}

	public void setRuleUpdatedBy(Integer ruleUpdatedBy) {
		this.ruleUpdatedBy = ruleUpdatedBy;
	}

	public Date getRuleLastUpdatedDate() {
		return ruleLastUpdatedDate;
	}

	public void setRuleLastUpdatedDate(Date ruleLastUpdatedDate) {
		this.ruleLastUpdatedDate = ruleLastUpdatedDate;
	}

	public Integer getRuleTypeID() {
		return ruleTypeID;
	}

	public void setRuleTypeID(Integer ruleTypeID) {
		this.ruleTypeID = ruleTypeID;
	}

	public String getSourceClassName() {
		return sourceClassName;
	}

	public void setSourceClassName(String sourceClassName) {
		this.sourceClassName = sourceClassName;
	}
	
	public List<Condition> getConditionList() {
		return conditionList;
	}

	public void setConditionList(List<Condition> conditionList) {
		this.conditionList = conditionList;
	}

		
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/ActivityPlan.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.sc;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author Taqdir
 */
@Entity
public class ActivityPlan implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private Long activityPlanId;
    private Long userGoalId;
    private String planDescription;
    private String explanation; 

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof ActivityPlan)) {
            return false;
        }
        ActivityPlan other = (ActivityPlan) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.sc.ActivityPlan[ id=" + id + " ]";
    }

    /**
     * @return the activityPlanId
     */
    public Long getActivityPlanId() {
        return activityPlanId;
    }

    /**
     * @param activityPlanId the activityPlanId to set
     */
    public void setActivityPlanId(Long activityPlanId) {
        this.activityPlanId = activityPlanId;
    }

    /**
     * @return the userGoalId
     */
    public Long getUserGoalId() {
        return userGoalId;
    }

    /**
     * @param userGoalId the userGoalId to set
     */
    public void setUserGoalId(Long userGoalId) {
        this.userGoalId = userGoalId;
    }

    /**
     * @return the planDescription
     */
    public String getPlanDescription() {
        return planDescription;
    }

    /**
     * @param planDescription the planDescription to set
     */
    public void setPlanDescription(String planDescription) {
        this.planDescription = planDescription;
    }

    /**
     * @return the explanation
     */
    public String getExplanation() {
        return explanation;
    }

    /**
     * @param explanation the explanation to set
     */
    public void setExplanation(String explanation) {
        this.explanation = explanation;
    }
    
}


<|start_filename|>knowledge-curation-layer/i-kat/src/test/java/org/uclab/mm/kcl/edkat/service/testcases/ConclusionServiceImplTest.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.kcl.edkat.service.testcases;

import static org.junit.Assert.*;

import javax.transaction.Transactional;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.uclab.mm.kcl.edkat.dao.ConclusionDAO;
import org.uclab.mm.kcl.edkat.datamodel.Conclusion;

/**
 * This is a class for testing the insertion, fetching, and update of Conclusion of a rule 
 * @author <NAME>
 *
 */
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class ConclusionServiceImplTest {

	@Autowired
	private ConclusionDAO conclusionDAO;
	
	/**
	 * This is function for testing the insertion, fetching, and update of Conclusion of a rule  
	 */
	@Test
	@Transactional
	@Rollback(true)
	public void test() {
		Conclusion objOuterConclusion = new Conclusion();
		Conclusion objInnerConclusion = new Conclusion();
		
		/* Setting the Conclusion Object*/
		objOuterConclusion.setConclusionKey("unit test 4");
		objOuterConclusion.setConclusionValue("unit Test Value 4");
		objOuterConclusion.setRuleID(30110);
		objOuterConclusion.setConclusionOperator("=");
		
		/* Testing of Insertion*/
		objInnerConclusion = conclusionDAO.addConclusion(objOuterConclusion);
		
		/* Testing of fetching the new added Conclusion*/
		objInnerConclusion = conclusionDAO.getConclusionById(objInnerConclusion.getConclusionID());
		assertEquals(objOuterConclusion.getConclusionKey(), objInnerConclusion.getConclusionKey());
		
		objInnerConclusion.setConclusionKey("unit test 4 updated");
		objInnerConclusion.setConclusionValue("unit Test Value 4 updated");
		
		/* Testing of updating*/
		Conclusion objInnerConclusionUpdated = new Conclusion();
		objInnerConclusionUpdated = conclusionDAO.updateConclusion(objInnerConclusion);
		
		assertEquals(objInnerConclusion.getConclusionKey(), objInnerConclusionUpdated.getConclusionKey());
	}

}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/utils/ArffWriter.java<|end_filename|>
package org.uclab.mm.icl.utils;

/*
Copyright [2016] [Vui]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Vector;

public class ArffWriter {
	static String PATH = "";
	File file;
	FileWriter fw;

	public ArffWriter(String path, String filename ,String relation, String[] labels, int featureNum,
			String[] featureName) {
		PATH = path;
		file = new File(PATH);
		file.mkdirs();
		file = new File(PATH + "/"+filename+".arff");
	
		try {
			file.createNewFile();
			fw = new FileWriter(file);
			initWrite(relation, labels, featureNum, featureName);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void initWrite(String relation, String[] labels, int featureNum, String[] featureName) {
		String init = "@relation " + relation+"\r\n";
		try {
			fw.write(init);
			if (featureName == null) {
				for (int i = 0; i < featureNum; i++) {
					fw.write("@attribute " + "f" + i + " real\r\n");
				}
			}else{
				for( int i=0; i<featureName.length; i++){
					fw.write("@attribute " + featureName[i] + " real\r\n");
				}
			}
			fw.write("@attribute class {");
			for(int i = 0;i< labels.length; i++){
				
				if(i == labels.length-1){
					fw.write(labels[i]+"}\r\n");
				}else{
					fw.write(labels[i]+", ");
				}
			}
			fw.write("@data\r\n");
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/*
	 * public WriteFile() { try { file = convertIsToFile(is); } catch
	 * (IOException e) { // TODO Auto-generated catch block e.printStackTrace();
	 * } }
	 */

	

	public void write(double[] features, String label) {
		try {
			FileWriter fw;
			fw = new FileWriter(file, true);

			for (int i = 0; i < features.length; i++) {
				fw.write(features[i] + "\t ");
			}
			fw.write("'" + label + "'\r\n");

			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/ContextOntologyManager/ContextOntologyManager.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.ContextOntologyManager;
import org.mindswap.pellet.jena.PelletReasonerFactory;
import org.apache.log4j.Logger;

import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.ModelFactory;

import mm.icl.hlc.OntologyTools.ContextOntology;
import mm.icl.hlc.OntologyTools.InferredContextOntology;
/**
 * Context Ontology Manager : Component of HLCA which manages the interactions
 * with the Context Ontology Storage where Context Ontology and Context
 * Instances are persisted.
 *
 * @author <NAME> and <NAME>
 * @version 2.5
 * @since 2015-10-28
 */
public class ContextOntologyManager {

	private static Logger logger = Logger.getLogger(ContextOntologyManager.class);
	/**
	 * Context Ontology which represents the Mining Minds Context Model.
	 */
	private ContextOntology ont;
	/**
	 * Inferred version of the Context Ontology which represents the Mining
	 * Minds Context Model.
	 */
	private InferredContextOntology infOnt;
	/**
	 * Constructor of a new Context Ontology Manager.
	 * 
	 * @param directory
	 *            Path to the directory where the Context Ontology Storage is
	 *            deployed.
	 */
	private ContextHandler contextHandler = ContextHandler.getContextHandler();
	public ContextOntologyManager(String directory) {
		OntologyModelManager.initialize(directory);
		OntModel ontModel = OntologyModelManager.retrieveContextOntology();
		try{
		if (ontModel != null) {
			OntModel infOntModel = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC, ontModel);
			this.ont = new ContextOntology(ontModel);
			this.infOnt = new InferredContextOntology(infOntModel);
			contextHandler.initialize(directory, this.ont);
		}
		}
		catch (Exception e) {
			logger.error("Error while initializing Context Ontology.  Message: " + e.getMessage());
			e.printStackTrace();
		}
		
	}
	/**
	 * Constructor of a new Context Ontology Manager.
	 * 
	 * @param directory
	 *            Path to the directory where the Context Ontology Storage is
	 *            deployed.
	 * @param ontModel
	 *            OntModel representation of the Context Ontology.
	 */
	public ContextOntologyManager(String directory, OntModel ontModel) {
			this(directory);

	try{		
		if (this.ont == null) { 
			OntModel infOntModel = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC, ontModel);
			ContextOntology ont = new ContextOntology(ontModel);
			InferredContextOntology infOnt = new InferredContextOntology(infOntModel);
			if (infOnt.isValid()) {
				OntologyModelManager.loadContextOntology(ont);
				this.ont = ont;
				this.infOnt = infOnt;
				contextHandler.initialize(directory, this.ont);
			}
		}
	}
	catch (Exception e) {
							logger.error("There is a Context Model stored in DB. Ignoring the provided OntModel and "
									+ "using the available one to initialize the Context Ontology Manager." + e.getMessage());
							e.printStackTrace();
						}
	}
	
	/**
	 * Method to inquire whether the Context Ontology Manager has been correctly
	 * initialized.
	 * 
	 * @return true if the Context Ontology Manager has been correctly
	 *         initialized, and false otherwise.
	 */
	public boolean correctInitialization() {
		return (this.ont != null && this.infOnt != null);
	}
	/**
	 * Method to retrieve the Context Ontology which has been persisted in the
	 * Context Ontology Storage.
	 * 
	 * @return Context Ontology which was persisted in the Context Ontology
	 *         Storage.
	 */
	public ContextOntology getContextOntology() {
		return ont;
	}
	/**
	 * Method to retrieve the inferred version of the Context Ontology which has
	 * been persistedd in the Context Ontology Storage.
	 * 
	 * @return Inferred version of the Context Ontology which was persisted in
	 *         the Context Ontology Storage.
	 */
	public InferredContextOntology getInferredContextOntology() {
		return infOnt;
	}
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/ICLServerThread.java<|end_filename|>
/*
Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioFormat.Encoding;
import org.apache.log4j.Logger;
import org.uclab.mm.icl.data.SmartphoneData;
import org.uclab.mm.icl.llc.AER.vui.WavFile;
import org.uclab.mm.icl.llc.LLCManager.User;
import org.uclab.mm.icl.llc.config.DeviceType;
import org.uclab.mm.icl.utils.FileUtil;
import org.uclab.mm.icl.utils.TimeChecker;
import org.uclab.mm.icl.utils.TimeUtil;


/**
 * This class is socket version of ICL. This class is multithreaded, and it generates new thread for each new socket connection.
 * @author Nailbrainz
 *
 */
public class ICLServerThread extends Thread {
	private static List<ICLServerThread> threads = new ArrayList<ICLServerThread>();
	Socket clientSocket = null;
	static String answer = "";
	private int payloadSize = 0;
	private RandomAccessFile randomAccessWriter;
	AudioFormat af = new AudioFormat(Encoding.PCM_SIGNED, 44100, 16, 1, 2, 44100, false);
	LLCServer icl;
	ServerSocket ss;
	private final static Logger logger = Logger.getLogger(ICLServerThread.class);
	

	
	/**
	 * Unique constructor of ICL socket version
	 * @param ss server socket
	 * @param socket client socket
	 * @param icl icl server instance
	 */
	public ICLServerThread(ServerSocket ss, Socket socket, LLCServer icl) {
		super();
		this.ss = ss;
		this.clientSocket = socket;
		threads.add(this);
		this.icl = icl;
		for (int i = 0; i < threads.size() - 1; i++) {
			if (socket.getInetAddress().equals(threads.get(i).clientSocket.getInetAddress())) {
				System.out.println(threads.get(i).clientSocket.getInetAddress() + "Duplicated Access");
				System.out.println(threads.get(i).getName() + "Delete Thread");
				threads.remove(i);
			} else {
				System.out.println(threads.get(i).clientSocket.getInetAddress() + "Access");
			}
		}
		for (int i = 0; i < threads.size(); i++) {
			System.out.println(threads.get(i).getName() + "Activated Thread");
		}
	}

	//running part of ICLServerThread. Waits for the socket message and convey the sensor data to user objects
	public void run(){
		boolean running = true;
		InputStream objectInBytes = null;
		ObjectInputStream readingObjects = null;
		SmartphoneData sd = null;
		try {
			//System.out.println("waiting for objects");
			objectInBytes = clientSocket.getInputStream();
			readingObjects = new ObjectInputStream(objectInBytes);
			sd = new SmartphoneData();
		} catch (IOException ex) {
			System.out.println("err at objectinputstream on server " + ex.toString());
			ex.printStackTrace();
		}
		while (running) {
			try {
				sd = (SmartphoneData) readingObjects.readObject();
				if (!sd.getIsDemo()) {
					System.out.println("Data of user  " + sd.getUserID() + " rvcd at " + sd.getTimeStamp());
					try {
						System.out.println("smartphone Accelerometer data = " + sd.getAcc_sm()[0][130]);
					} catch (Exception e) {
						e.printStackTrace();
					}
					System.out.println("gps =  " + sd.getLat() + "," + sd.getLongi());
					if (sd.getAudioSensoryData() == null)
						System.out.println("voice null");
					else
						System.out.println("voice size =  " + sd.getAudioSensoryData().length);
					// ObjectSizer of = new ObjectSizer();
					// System.out.println("Object size = " + of.getObjectSize(sd));
					/*
					 * FileOutputStream fout = new FileOutputStream("D:\\packet.dat");
					 * ObjectOutputStream oos = new ObjectOutputStream(fout); oos.writeObject(sd);
					 * oos.close();
					 */
					logger.info(sd.getLat() + "," + sd.getLongi());
					TimeChecker.time = System.nanoTime();
					/*
					 * if(sd.getEmoImage() != null){ 
					 * 	System.err.print("!!!!!!!!!!!!!!!!!!!!!!!!!!! emo image not null!!");
					 * 	FileOutputStream out; TimeUtil ti = new TimeUtil();
					 * 	out = new FileOutputStream("D:/emoPic/"+ti.getFileName()+".jpg"); 
					 * 	out.write(sd.getEmoImage()); out.close(); }else{
					 * 	System.err.print("!!!!!!!!!!!!!!!!!!!!!!!!!!! emo image  null!!!!!!!!!!!!!!!!!!!!!!!!");
					 * }
					 */
					icl.RouteData(DeviceType.SmartPhone, sd);

				} else {
					User usr = icl.getUserDemo(sd.getUserID());
					if (usr != null) {
						usr.fillBufferDemo(sd.getTimeStamp(), sd.getImage(), sd.getFoodTag());
					}
					break;
				}

			} catch (IOException e) {
				logger.error("io related error at reading data class (smartphone) from socket inputstream");
				logger.error(e);
				try {
					clientSocket.close();
				} catch (IOException e1) {
					logger.error("error at closing socket from smartphone");
					logger.error(e);
					// TODO Auto-generated catch block
				}
				threads.remove(this);
				return;
			} catch (ClassNotFoundException e) {
				logger.error("error at reading data class (smartphone) from socket inputstream");
				logger.error("serializable data class does not matched. Make sure to use right class and "
						+ "right sererialization number");
				logger.error(e);
			} 
		}
	}

	/**
	 * Sends the socket message
	 * 
	 * @param talker ICLServerThread to send message
	 * @param message message to be send
	 */
	public void sendMessage(ICLServerThread talker, String message) {
		try {
			OutputStream out = clientSocket.getOutputStream();
			byte[] buffer = message.getBytes("UTF-8");
			out.write(buffer);
			out.flush();
		} catch (IOException ioe) {
		}
	}

	/**
	 * Initialize the class required for the file writing of Vui's module
	 * 
	 * @param path path to create file
	 * @throws IOException IOException of the file exception
	 */
	public void prepare(String path) throws IOException {

		randomAccessWriter = new RandomAccessFile(path, "rw");
		randomAccessWriter.setLength(0);
		randomAccessWriter.writeBytes("RIFF");
		// Final file size not known yet, write 0
		randomAccessWriter.writeInt(0);
		randomAccessWriter.writeBytes("WAVE");
		randomAccessWriter.writeBytes("fmt ");
		// Sub-chunk size, 16 for PCM
		randomAccessWriter.writeInt(Integer.reverseBytes(16));
		// AudioFormat, 1 for PCM
		randomAccessWriter.writeShort(Short.reverseBytes((short) 1));
		// Number of channels, 1 for mono, 2 for stereo
		randomAccessWriter.writeShort(Short.reverseBytes((short) af.getChannels()));
		// Sample rate
		randomAccessWriter.writeInt(Integer.reverseBytes((int) af.getSampleRate()));
		// Byte rate,
		// SampleRate*NumberOfChannels*BitsPerSample/8
		randomAccessWriter.writeInt(
				Integer.reverseBytes((int) (af.getSampleRate() * af.getSampleSizeInBits() * af.getChannels() / 8)));
		// Block align, NumberOfChannels*BitsPerSample/8
		randomAccessWriter.writeShort(Short.reverseBytes((short) (af.getChannels() * af.getSampleSizeInBits() / 8)));
		// Bits per sample
		randomAccessWriter.writeShort(Short.reverseBytes((short) af.getSampleSizeInBits()));
		randomAccessWriter.writeBytes("data");
		// Data chunk size not known yet, write 0
		randomAccessWriter.writeInt(0);
		// buffer = new byte[framePeriod * bSamples / 8 * channel];

	}

	
	/**
	 *  This function writes voice wav data into uri which is set in randomAccessWriter instance
	 * @throws IOException when randomaccesswriter fails, this exception could occur
	 */
	public void stop_writing() throws IOException {
		// randomAccessWriter.write(buffer);
		randomAccessWriter.seek(4); // Write size to RIFF header
		randomAccessWriter.writeInt(Integer.reverseBytes(36 + payloadSize));

		randomAccessWriter.seek(40); // Write size to Subchunk2Size
										// field
		randomAccessWriter.writeInt(Integer.reverseBytes(payloadSize));
		randomAccessWriter.close();

	}
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/llm/dataadapter/LifelogMonitorActivityAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.llm.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.llm.LifelogMonitorActivity;

/**
 *
 * @author <NAME>
 */
public class LifelogMonitorActivityAdapter implements DataAccessInterface {

    private Connection objConn;
    
    public LifelogMonitorActivityAdapter()
    {
        
    }
    
    @Override
    public <T> List<String> Save(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public <T> List<String> Update(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public List<LifelogMonitorActivity> RetriveData(Object objLifelogMonitorActivity) {
        LifelogMonitorActivity objOuterLifelogMonitorActivity = new LifelogMonitorActivity();
        List<LifelogMonitorActivity> objListInnerLifelogMonitorActivity = new ArrayList<LifelogMonitorActivity>();
        objOuterLifelogMonitorActivity =  (LifelogMonitorActivity) objLifelogMonitorActivity;
        
        try
        {
            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_MonitorLifeLogByActivities(?, ?, ?, ?)}");
            objCallableStatement.setLong("UserID", objOuterLifelogMonitorActivity.getUserID());
            
            if(objOuterLifelogMonitorActivity.getEndTime() != null)
            {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
                Date dtDate = sdf.parse(objOuterLifelogMonitorActivity.getEndTime());

                Timestamp tsDate = new Timestamp(dtDate.getYear(),dtDate.getMonth(), dtDate.getDate(), dtDate.getHours(), dtDate.getMinutes(), dtDate.getSeconds(), 00);
                objCallableStatement.setTimestamp("EndTime", tsDate);
            }
            objCallableStatement.setInt("TimeInterval", objOuterLifelogMonitorActivity.getTimeInterval());
            objCallableStatement.setInt("Threshold", objOuterLifelogMonitorActivity.getThrashold());
            
            ResultSet objResultSet = objCallableStatement.executeQuery();

            //ResultSet resultSet = statement.executeQuery("SELECT Name FROM ComputerStatus");
            while(objResultSet.next())
            {
                LifelogMonitorActivity objInnerLifelogMonitorActivity = new LifelogMonitorActivity();
                objInnerLifelogMonitorActivity.setUserID(objResultSet.getLong("UserID"));
                objInnerLifelogMonitorActivity.setActivityID(objResultSet.getInt("ActivityID"));
                objInnerLifelogMonitorActivity.setActivityDescription(objResultSet.getString("ActivityDescription"));
                objInnerLifelogMonitorActivity.setTotalTime(objResultSet.getInt("TotalTime"));
                
                objListInnerLifelogMonitorActivity.add(objInnerLifelogMonitorActivity);
            }
            objConn.close();
        }
        catch(SQLException ex)
        {
             ex.printStackTrace();
             System.err.println("Problem with sql server");
        }
        catch (Exception e)
        {
             e.printStackTrace();
             System.err.println("Problem in registration user!");
        }   
        return objListInnerLifelogMonitorActivity;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void ConfigureAdapter(Object objConf) {
        try{
        objConn = (Connection)objConf;
        }
        catch(Exception ex)
        {}
    }
    
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/ic/UserGPSData.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.ic;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;


/**
 *
 * @author Taqdir
 */
@Entity
public class UserGPSData implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private Long userGPSDataId;
    private Long userDeviceId;
   
    private List<Float> latitude = new ArrayList<Float>();
    private List<Float> longitude = new ArrayList<Float>();
    private List<Float> speed = new ArrayList<Float>();
    private String timeStamp;
    
    

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof UserGPSData)) {
            return false;
        }
        UserGPSData other = (UserGPSData) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.ic.UserGPSData[ id=" + id + " ]";
    }

    /**
     * @return the userGPSDataId
     */
    public Long getUserGPSDataId() {
        return userGPSDataId;
    }

    /**
     * @param userGPSDataId the userGPSDataId to set
     */
    public void setUserGPSDataId(Long userGPSDataId) {
        this.userGPSDataId = userGPSDataId;
    }

    /**
     * @return the userDeviceId
     */
    public Long getUserDeviceId() {
        return userDeviceId;
    }

    /**
     * @param userDeviceId the userDeviceId to set
     */
    public void setUserDeviceId(Long userDeviceId) {
        this.userDeviceId = userDeviceId;
    }

    /**
     * @return the timeStamp
     */
    public String getTimeStamp() {
        return timeStamp;
    }

    /**
     * @param timeStamp the timeStamp to set
     */
    public void setTimeStamp(String timeStamp) {
        this.timeStamp = timeStamp;
    }

    /**
     * @return the latitude
     */
    public List<Float> getLatitude() {
        return latitude;
    }

    /**
     * @param latitude the latitude to set
     */
    public void setLatitude(List<Float> latitude) {
        this.latitude = latitude;
    }

    /**
     * @return the longitude
     */
    public List<Float> getLongitude() {
        return longitude;
    }

    /**
     * @param longitude the longitude to set
     */
    public void setLongitude(List<Float> longitude) {
        this.longitude = longitude;
    }

    /**
     * @return the speed
     */
    public List<Float> getSpeed() {
        return speed;
    }

    /**
     * @param speed the speed to set
     */
    public void setSpeed(List<Float> speed) {
        this.speed = speed;
    }
    
    public double[] getRep(){
    	List<Float> lat = getLatitude();
    	List<Float> lon = getLongitude();
    	double[] ret = new double[3];
    	ret[0] = ret[1] = 0;
    	
    	for(int i = 0; i<lat.size(); i++){
    		if(!(lat.get(i) == 0 && lon.get(i) == 0)){
    			ret[0] = lat.get(i).doubleValue();
    			ret[1] = lon.get(i).doubleValue();
    			ret[2] = speed.get(i).doubleValue();
    			return ret;
    		}
    	}
    	return ret;
    }
    
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sl/dataadapter/UserAccelerometerDataVisulizationAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sl.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.ic.UserAccelerometerData;
import org.uclab.mm.datamodel.sl.UserAccelerometerDataVisulization;

/**
 * This is UserAccelerometerDataVisulizationAdapter class which implements the Data Access Interface for CRUD operations
 * @author dcadmin
 */
public class UserAccelerometerDataVisulizationAdapter implements DataAccessInterface {
    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(UserAccelerometerDataVisulizationAdapter.class);
    public UserAccelerometerDataVisulizationAdapter()
    {
        
    }

    
    /**
     * This is implementation function for saving UserAccelerometerDataVisulization. 
     *Not Implemented
     */
    @Override
    public <T> List<String> Save(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet."); 
    }

    /**
     * This is implementation function for Update UserAccelerometerDataVisulization. 
     *Not Implemented
     */
    @Override
    public <T> List<String> Update(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet."); 
    }
    
    /**
     * This is implementation function for retrieving UserAccelerometerDataVisulization. 
     * @param objUserAccelerometerData
    * @return List of UserAccelerometerDataVisulization
     */
    @Override
    public List<UserAccelerometerDataVisulization> RetriveData(Object objUserAccelerometerData) {
        UserAccelerometerDataVisulization objOuterUserAccelerometerData = new UserAccelerometerDataVisulization();
        List<UserAccelerometerDataVisulization> objListInnerUserAccelerometerData = new ArrayList<UserAccelerometerDataVisulization>();
        objOuterUserAccelerometerData =  (UserAccelerometerDataVisulization) objUserAccelerometerData;
        
        try
        {
            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UserAccelerometerDataForVisualization(?, ?)}");
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
            
            Date dtStartTimeStamp = sdf.parse(objOuterUserAccelerometerData.getTimeStampStart());
            Timestamp tsStartTimeStamp = new Timestamp(dtStartTimeStamp.getYear(),dtStartTimeStamp.getMonth(), dtStartTimeStamp.getDate(), dtStartTimeStamp.getHours(), dtStartTimeStamp.getMinutes(), dtStartTimeStamp.getSeconds(), 00);
            objCallableStatement.setTimestamp("StartTimeStamp", tsStartTimeStamp);
                
            Date dtEndTimeStamp = sdf.parse(objOuterUserAccelerometerData.getTimeStampEnd());
            Timestamp tsEndTimeStamp = new Timestamp(dtEndTimeStamp.getYear(),dtEndTimeStamp.getMonth(), dtEndTimeStamp.getDate(), dtEndTimeStamp.getHours(), dtEndTimeStamp.getMinutes(), dtEndTimeStamp.getSeconds(), 00);
            objCallableStatement.setTimestamp("EndTimeStamp", tsEndTimeStamp);

            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                UserAccelerometerDataVisulization objInnerUserAccelerometerData = new UserAccelerometerDataVisulization();
                objInnerUserAccelerometerData.setUserAccelerometerDataId(objResultSet.getLong("UserAccelerometerDataID"));
                objInnerUserAccelerometerData.setUserDeviceId(objResultSet.getLong("UserDeviceID"));
                objInnerUserAccelerometerData.setxCoordinate(objResultSet.getFloat("XCoordinate"));
                objInnerUserAccelerometerData.setyCoordinate(objResultSet.getFloat("YCoordinate"));
                objInnerUserAccelerometerData.setzCoordinate(objResultSet.getFloat("ZCoordinate"));
                
                Timestamp tstimestamp = objResultSet.getTimestamp("timestamp"); //updated
                objInnerUserAccelerometerData.setTimeStamp(tstimestamp.toString());
                objListInnerUserAccelerometerData.add(objInnerUserAccelerometerData);
            }
            objConn.close();
            logger.info("User Accelerometer Data Visulization loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading User Accelerometer Data Visulization");
        }   
        return objListInnerUserAccelerometerData;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/test/TestRetrieveContextInstance.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.test;

import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.query.ReadWrite;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.tdb.TDB;
import com.hp.hpl.jena.tdb.TDBFactory;



public class TestRetrieveContextInstance {

static final String directory = "E:\\ICL_LOG\\TDB";///"D:\\HLCA" ;  
	
static final String ctxName = 
			"http://www.miningminds.re.kr/icl/context/context-v2-5.owl#hlc_0901959045_0000000000000000013"; 
		
		
	public static void main(String[] args) {
			
			Dataset dataset = TDBFactory.createDataset(directory);
			TDB.getContext().set(TDB.symUnionDefaultGraph, true);
		
			dataset.begin(ReadWrite.READ);

			Model inst = dataset.getNamedModel(ctxName);
			dataset.end();
			
			if (!inst.isEmpty()){
				OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, inst);
				ontModel.write(System.out, "RDF/XML");            ///Turtle RDF/XML RDF/XML-ABBREV N-TRIPLE
			}
	}
}


<|start_filename|>knowledge-curation-layer/DDKAT/src/main/java/org/uclab/mm/kcl/ddkat/modeltranslator/DTtoRuleTranslator.java<|end_filename|>
/**
 * Copyright [2017] [<NAME>, <NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.mm.kcl.ddkat.modeltranslator;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.uclab.mm.kcl.ddkat.productionmodel.Conclusion;
import org.uclab.mm.kcl.ddkat.productionmodel.Condition;
import org.uclab.mm.kcl.ddkat.productionmodel.Rule;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

//TODO: Auto-generated Javadoc
/**
* This class translates the decision tree into rules.
*/
public class DTtoRuleTranslator {
	
	/** base directory to store resource data files */
	private static final String BASE_DIR = System.getProperty("user.home") + "/DDKAT/resources/";
	
    public List<Rule> translateModel() throws Exception {
 	
       BufferedReader brTest = new BufferedReader(new FileReader(BASE_DIR + "selectedalgorithmFile.txt"));
       brTest.readLine();
       brTest.close();
       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
       DocumentBuilder builder = factory.newDocumentBuilder();
       Document source = builder.parse(new File(BASE_DIR + "treemodelFile.xml"));
       Node rootNode = source.getDocumentElement();
       Node currentNode=rootNode.getFirstChild();
            
       List<Rule> ruleList = new ArrayList<Rule>();
       int ruleID = 0;
         
       while (currentNode!=null) {
         // print node information
           if(currentNode.getNodeName().equals("Test")){
        	// print node information  
           }

         if ( currentNode.hasChildNodes()) {
           currentNode = currentNode.getFirstChild();
         }
         else {
             // leaf
             if(currentNode.getNodeName().equals("Output")){
            	 
            	 ruleID++;
            	 Rule rule = new Rule();
            	 rule.setRuleID(ruleID);
            	 
            	 List<Condition> conditionList = new ArrayList<Condition>();
            	 List<Conclusion> conclusionList = new ArrayList<Conclusion>();
            	 
                 int conclusionID = 1;
                 String decisionattribute = "TestResult";
                 String conclusionValue = currentNode.getAttributes().getNamedItem("decision").getNodeValue();
                 
                 Conclusion conclusion = new Conclusion();
                 conclusion.setConclusionID(conclusionID);
                 conclusion.setConclusionKey(decisionattribute);
                 conclusion.setConclusionOperator("=");
                 conclusion.setConclusionValue(conclusionValue);
                 conclusionList.add(conclusion);
                 rule.setConclusionList(conclusionList);
                 
                 int pathnodes_counter = 0;
                 String conditionAttribute = " ";
                 String conditionOperator = " ";
                 String conditionValue = " ";
                 Node pathNode = currentNode;

                 while(pathNode.getParentNode().getNodeName().equals("Test")){
                     pathnodes_counter++;
                     pathNode = pathNode.getParentNode();
                     }

                 pathNode = currentNode;
                 String ruleConditionsArr[][] = new String[pathnodes_counter][3];
                 int arrIndex = pathnodes_counter-1;

                 while(pathNode.getParentNode().getNodeName().equals("Test")){
                     conditionAttribute = pathNode.getParentNode().getAttributes().getNamedItem("attribute").getNodeValue();
                     conditionOperator = pathNode.getParentNode().getAttributes().getNamedItem("operator").getNodeValue();
                     conditionValue = pathNode.getParentNode().getAttributes().getNamedItem("value").getNodeValue();
                     ruleConditionsArr[arrIndex][0] = conditionAttribute;
                     ruleConditionsArr[arrIndex][1] = conditionOperator;
                     ruleConditionsArr[arrIndex][2] = conditionValue;
                     arrIndex--;
                     pathNode = pathNode.getParentNode();
                     }

                 for(int conditionID=0; conditionID<pathnodes_counter; conditionID++){
                     Condition condition = new Condition();
                     condition.setConditionID(conditionID+1);
                     condition.setConditionKey(ruleConditionsArr[conditionID][0]);
                     condition.setConditionValueOperator(ruleConditionsArr[conditionID][1]);
                     condition.setConditionValue(ruleConditionsArr[conditionID][2]);
                     conditionList.add(condition);
                     }
                 
                 rule.setConditionList(conditionList);
                 ruleList.add(rule);
             } 
             
             // find the parent level
             while (currentNode.getNextSibling()==null && currentNode != rootNode){
            	 // use child-parent link to get to the parent level
            	 currentNode=currentNode.getParentNode();
             	 }

             currentNode = currentNode.getNextSibling();
         }
       }  
       
       return ruleList;
   }
    
}



<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/objectmodel/FoodLog.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */
package org.uclab.mm.dcl.llm.objectmodel;

/**
 *
 * @author Rizvi
 */
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author bilal
 */
@Entity
public class FoodLog implements Serializable{

  private static final long serialVersionUID = 1L;
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  private Long foodLogID;
  private Long userId;
  private String foodName;
  private String eatingTime;
  private String startTime;
  private String endTime;
  private String requestType;

  
  public Long getId(){
    return id;
  }

  public void setId(Long id){
    this.id = id;
  }

  @Override
  public int hashCode(){
    int hash = 0;
    hash += (id != null ? id.hashCode() : 0);
    return hash;
  }

  @Override
  public boolean equals(Object object){
    // TODO: Warning - this method won't work in the case the id fields are not set
    if (!(object instanceof FoodLog)){
      return false;
    }
    FoodLog other = (FoodLog) object;
    if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))){
      return false;
    }
    return true;
  }

  @Override
  public String toString(){
    return "org.uclab.mm.datamodel.ic.FoodLog[ id=" + id + " ]";
  }

  /**
   * @return the foodLogID
   */
  public Long getFoodLogID(){
    return foodLogID;
  }

  /**
   * @param foodLogID the foodLogID to set
   */
  public void setFoodLogID(Long foodLogID){
    this.foodLogID = foodLogID;
  }

  /**
   * @return the userId
   */
  public Long getUserId(){
    return userId;
  }

  /**
   * @param userId the userId to set
   */
  public void setUserId(Long userId){
    this.userId = userId;
  }

  /**
   * @return the foodName
   */
  public String getFoodName(){
    return foodName;
  }

  /**
   * @param foodName the foodName to set
   */
  public void setFoodName(String foodName){
    this.foodName = foodName;
  }

  /**
   * @return the eatingTime
   */
  public String getEatingTime(){
    return eatingTime;
  }

  /**
   * @param eatingTime the eatingTime to set
   */
  public void setEatingTime(String eatingTime){
    this.eatingTime = eatingTime;
  }

  /**
   * @return the startTime
   */
  public String getStartTime(){
    return startTime;
  }

  /**
   * @param startTime the startTime to set
   */
  public void setStartTime(String startTime){
    this.startTime = startTime;
  }

  /**
   * @return the endTime
   */
  public String getEndTime(){
    return endTime;
  }

  /**
   * @param endTime the endTime to set
   */
  public void setEndTime(String endTime){
    this.endTime = endTime;
  }

  /**
   * @return the requestType
   */
  public String getRequestType(){
    return requestType;
  }

  /**
   * @param requestType the requestType to set
   */
  public void setRequestType(String requestType){
    this.requestType = requestType;
  }

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/dc/UserAddress.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.dc;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author Taqdir
 */
@Entity
public class UserAddress implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private Long userAddressId;
    private Long userId;
    private int addressTypeId;
    private String homeNumber;
    private int cityId;
    private int countryId;
    

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof UserAddress)) {
            return false;
        }
        UserAddress other = (UserAddress) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.dc.UserAddress[ id=" + id + " ]";
    }

    /**
     * @return the userAddressId
     */
    public Long getUserAddressId() {
        return userAddressId;
    }

    /**
     * @param userAddressId the userAddressId to set
     */
    public void setUserAddressId(Long userAddressId) {
        this.userAddressId = userAddressId;
    }

    /**
     * @return the userId
     */
    public Long getUserId() {
        return userId;
    }

    /**
     * @param userId the userId to set
     */
    public void setUserId(Long userId) {
        this.userId = userId;
    }

    /**
     * @return the addressTypeId
     */
    public int getAddressTypeId() {
        return addressTypeId;
    }

    /**
     * @param addressTypeId the addressTypeId to set
     */
    public void setAddressTypeId(int addressTypeId) {
        this.addressTypeId = addressTypeId;
    }

     /**
     * @return the homeNumber
     */
    public String getHomeNumber() {
        return homeNumber;
    }

    /**
     * @param homeNumber the homeNumber to set
     */
    public void setHomeNumber(String homeNumber) {
        this.homeNumber = homeNumber;
    }

    /**
     * @return the cityId
     */
    public int getCityId() {
        return cityId;
    }

    /**
     * @param cityId the cityId to set
     */
    public void setCityId(int cityId) {
        this.cityId = cityId;
    }

    /**
     * @return the countryId
     */
    public int getCountryId() {
        return countryId;
    }

    /**
     * @param countryId the countryId to set
     */
    public void setCountryId(int countryId) {
        this.countryId = countryId;
    }
    
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/data/SmartphoneData.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Kang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

This source code includes CDDL-licensed com.sun.jersey library
*/
package org.uclab.mm.icl.data;

import java.io.IOException;
import java.io.Serializable;
import java.util.zip.DataFormatException;
import org.json.JSONArray;
import org.json.JSONObject;
import org.uclab.mm.icl.utils.ByteCompression;

import com.sun.jersey.core.util.Base64;



/**
 * This class represents the data sent from the smartphone + wearable devices, including inertial, voice and image data.
 * @author Nailbrainz
 */
public class SmartphoneData implements DeviceData, Serializable {
    private static final long serialVersionUID = 1L;
    private boolean isFromDemo = false;
    Long userID;

    byte[] emoImage;
    byte[] voiceData;
    byte[] image;
    double[] samples;  //you can neglect. It's for VUI's module only

    double[][] acc_sm = new double[3][150];
    double[][] gy_sm = new double[3][150];
    double[][] mag_sm = new double[3][150];

    double[][] acc_wm = new double[3][150];
    double[][] gy_wm = new double[3][150];
    double[][] mag_wm = new double[3][150];
    double[] ecg_wm = new double[150];


    public double longi, lat, spd;

    public String timeStamp;


    String foodTag;


    public void setIsDemo(boolean isDemo){
        this.isFromDemo = isDemo;
    }

    public boolean getIsDemo(){
        return isFromDemo;
    }



    public byte[] getImage() {
        return image;
    }

    public String getFoodTag() {
        return foodTag;
    }
    public void setImage(byte[] image) {
        this.image = image;
    }

    public void setFoodTag(String foodTag) {
        this.foodTag = foodTag;
    }


    /**
     *
     * @return user ID who generated this sensor data
     */
    public Long getUserID() {
        return userID;
    }


    /**
     *
     * @param userID user ID who generated this sensor data
     */
    public void setUserID(Long userID) {
        this.userID = userID;
    }


    public SmartphoneData(){
        //testing dummy
    }




    /**
     * Set audiosensory data
     * @param data audiosensory data to set
     */
    public void setAudioSensoryData(byte[] data){
        this.voiceData = data;
    }
    
    /**
     * set samples
     * @param samples samples data to set
     */
    public void setSamples(double[] samples){
        this.samples = samples;
    }

    public byte[] getAudioSensoryData(){
        return voiceData;
    }
    public double[] getSamples(){
        return samples;
    }




    public double getLongi() {
        return longi;
    }

    public void setLongi(double longi) {
        this.longi = longi;
    }

    public double getLat() {
        return lat;
    }

    public void setLat(double lat) {
        this.lat = lat;
    }

    public double getSpd() {
        return spd;
    }

    public void setSpd(double spd) {
        this.spd = spd;
    }

    public String getTimeStamp() {
        return timeStamp;
    }

    public void setTimeStamp(String timeStamp) {
        this.timeStamp = timeStamp;
    }

    public double[][] getAcc_sm() {
        return acc_sm;
    }

    public void setAcc_sm(double[][] acc_sm) {
        this.acc_sm = acc_sm;
    }

    public double[][] getGy_sm() {
        return gy_sm;
    }

    public void setGy_sm(double[][] gy_sm) {
        this.gy_sm = gy_sm;
    }

    public double[][] getMag_sm() {
        return mag_sm;
    }

    public void setMag_sm(double[][] mag_sm) {
        this.mag_sm = mag_sm;
    }

    public double[][] getAcc_wm() {
        return acc_wm;
    }

    public void setAcc_wm(double[][] acc_wm) {
        this.acc_wm = acc_wm;
    }

    public double[][] getGy_wm() {
        return gy_wm;
    }

    public void setGy_wm(double[][] gy_wm) {
        this.gy_wm = gy_wm;
    }

    public double[][] getMag_wm() {
        return mag_wm;
    }

    public void setMag_wm(double[][] mag_wm) {
        this.mag_wm = mag_wm;
    }

    public double[] getEcg_wm() {
        return ecg_wm;
    }

    public void setEcg_wm(double[] ecg_wm) {
        this.ecg_wm = ecg_wm;
    }

    public byte[] getEmoImage(){return emoImage;}

    public void setEmoImage(byte[] image){
        this.emoImage = image;
    }

	@Override
	public void setData(Object input) {
		// TODO Auto-generated method stub
		JSONObject json1 = (new JSONObject((String)input)).getJSONObject("data");
		JSONObject obj = null;
		 byte[] bm = Base64.decode((new JSONObject((String)input)).getString("byte"));
         try {
			bm = ByteCompression.decompress(bm);
			String rett =  new String(bm);
			//System.out.println(rett);
			obj = new JSONObject(rett);
			//System.out.println(json1);
			if(rett.equals(json1.toString()))System.err.println("Sry Saqib!!!");
		} catch (IOException | DataFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
		
		//json1 = json at smartphone
		this.setUserID(json1.getLong("user_id"));
		this.setTimeStamp(json1.getString("timestamp_android"));
		if(json1.has("array")){
			JSONArray sary = json1.getJSONArray("array");
			JSONArray comp = obj.getJSONArray("array");
			for(int i = 0; i<150; i++){
				
                JSONObject sitem = sary.getJSONObject(i);
                JSONObject itemC = comp.getJSONObject(i);
                acc_sm[0][i] = sitem.getDouble("accX");acc_sm[1][i] = sitem.getDouble("accY");acc_sm[2][i] = sitem.getDouble("accZ");
                gy_sm[0][i] = sitem.getDouble("gyroX");gy_sm[1][i] = sitem.getDouble("gyroY");gy_sm[2][i] = sitem.getDouble("gyroZ");
                
            }
		}
		if(json1.has("arrayW")){
			JSONArray wary = json1.getJSONArray("arrayW");

			
			for(int i = 0; i<150; i++){
                JSONObject witem = wary.getJSONObject(i);
                
                acc_wm[0][i] = witem.getDouble("accX");acc_wm[1][i] = witem.getDouble("accY");acc_wm[2][i] = witem.getDouble("accZ");
                gy_wm[0][i] = witem.getDouble("gyroX");gy_wm[1][i] = witem.getDouble("gyroY");gy_wm[2][i] = witem.getDouble("gyroZ");
            }
		}
		if(json1.has("longitude")){
			this.setLat(json1.getDouble("longitude"));
			this.setLongi(json1.getDouble("latitude"));
		}
		if(json1.has("voice")){
			this.setAudioSensoryData(Base64.decode(json1.getString("voice")));
		}
	}

	@Override
	public void setUserID(long userID) {
		this.userID = userID;
		// TODO Auto-generated method stub
		
	}

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sl/ActiveSession.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.sl;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author Taqdir
 */
@Entity
public class ActiveSession implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private Long ActiveSessionID;
    private Long UserID;
    private String HashCode;
    private int Status;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof ActiveSession)) {
            return false;
        }
        ActiveSession other = (ActiveSession) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.sl.NewEntity[ id=" + id + " ]";
    }

    /**
     * @return the ActiveSessionID
     */
    public Long getActiveSessionID() {
        return ActiveSessionID;
    }

    /**
     * @param ActiveSessionID the ActiveSessionID to set
     */
    public void setActiveSessionID(Long ActiveSessionID) {
        this.ActiveSessionID = ActiveSessionID;
    }

    /**
     * @return the UserID
     */
    public Long getUserID() {
        return UserID;
    }

    /**
     * @param UserID the UserID to set
     */
    public void setUserID(Long UserID) {
        this.UserID = UserID;
    }

    /**
     * @return the HashCode
     */
    public String getHashCode() {
        return HashCode;
    }

    /**
     * @param HashCode the HashCode to set
     */
    public void setHashCode(String HashCode) {
        this.HashCode = HashCode;
    }

    /**
     * @return the Status
     */
    public int getStatus() {
        return Status;
    }

    /**
     * @param Status the Status to set
     */
    public void setStatus(int Status) {
        this.Status = Status;
    }
    
}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/framework/RecInterpreter/Explanation/ExpURLMapper.java<|end_filename|>
/* Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.scl.framework.RecInterpreter.Explanation;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;
public class ExpURLMapper {
  static HashMap<String, String> mapExp_URL = new HashMap<>();

  private static final String urlPath = "URL.txt";
  private static Scanner scanFile;

  public ExpURLMapper() {
    try {
      scanFile = new Scanner(this.getClass().getClassLoader().getResourceAsStream(urlPath));
    } catch (Exception exp) {
      System.out.println(exp.getMessage());
    }
  }

  public HashMap mapExpURL() throws FileNotFoundException {
    String readFile = null;
    String key = null;
    String value = "";
    int test = 0;
    
    while (scanFile.hasNextLine()) {
      readFile = scanFile.nextLine();
      String array[] = readFile.split(",");
      key = array[0];
      while (test < array.length) {
        if (test == 0) {
          test += 1;
        } else if (test == 1) {
          value = array[test];
          test += 1;
        } else {
          value = value + "," + array[test];
          test += 1;
        }
        mapExp_URL.put(key, value);
      } // inner-while
      test = 0;
      key = null;
      value = "";
    } // outer-while
    scanFile.close();
    return mapExp_URL;
  }
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/AER/vui/AudioEmotionRecognizerV.java<|end_filename|>
/*
Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.AER.vui;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioFormat.Encoding;
import org.apache.log4j.Logger;
import org.uclab.mm.icl.data.DeviceData;
import org.uclab.mm.icl.data.SmartphoneData;
import org.uclab.mm.icl.llc.LLCManager.ContextLabel;
import org.uclab.mm.icl.llc.LLCManager.LLCUnifier;
import org.uclab.mm.icl.llc.LLCManager.MajorityVoting;
import org.uclab.mm.icl.llc.LLCRecognizer.LLCRecognizer;
import org.uclab.mm.icl.llc.config.ContextType;
import org.uclab.mm.icl.llc.config.DeviceType;
import org.uclab.mm.icl.llc.config.RecognizerType;
import org.uclab.mm.icl.utils.FileUtil;
import org.uclab.mm.icl.utils.TimeChecker;
import org.uclab.mm.icl.utils.TimeUtil;

import mm.icl.llc.MachineLearningTools.Classifications.WekaClassification;
import mm.icl.llc.MachineLearningTools.FeatureExtractions.TemporalFeatureExtraction;

/**
 *
 * @author lebavui
 */


/**
 * Data class for emotion recognizers
 * @author Nailbrainz
 *
 */
class EmotionData{
	public byte[] getData() {
		return data;
	}
	public String getTimeStamp() {
		return timeStamp;
	}
	byte[] data;
	String timeStamp;

	EmotionData(){}; //prohibited
	public EmotionData(byte[] data, String timeStamp){
		this.data = data;
		this.timeStamp = timeStamp;
	}
};

public class AudioEmotionRecognizerV extends LLCRecognizer<EmotionData>{
	public static String[] emoLabel = { "Anger", "Happiness", "Sadness", "NoEmotion" };
	private static final double SILENCE_THRESHOLD = 0.01; 
	
	private static final String DEFAULT_MODEL_FILE = FileUtil.getRootPath()+"//vuimodel/smo3emotions_new.model";
	
	long userID;
	String timeStamp;
	
	private String modelFile;
	
	private final static Logger logger = Logger.getLogger(AudioEmotionRecognizerV.class);
	
	//data from llcrawdatabuffer
	
	public AudioEmotionRecognizerV(long userID) {
		super(userID);
		modelFile = DEFAULT_MODEL_FILE;
	}
	
	public void setModelFile(String modelFile) {
		this.modelFile = modelFile;
	}
	
	@Override
    public ContextLabel recognize(EmotionData input, String timeStamp) {
    	System.err.println("Emo vui working");
    	try {
    		double[] samples = this.setAudioDataFromByteArray(input.getData());
    		
	    	double rmsEnergy = TemporalFeatureExtraction.computeRMSE(samples);
			if (rmsEnergy < SILENCE_THRESHOLD) {
				ContextLabel classifiedEmotion = new ContextLabel(userID, "NoEmotion", timeStamp, ContextType.Emotion);
				return classifiedEmotion;
			} else {
				AERFeatureExtraction fe = new AERFeatureExtraction();
				fe.setSamplingRate(44100);
				double[] features = fe.extractFeature(samples);
				
				WekaClassification classifier = new WekaClassification();
				classifier.loadModel(modelFile);
				int labelIndex = classifier.classify(features);
				
				ContextLabel classifiedEmotion = new ContextLabel(userID, emoLabel[labelIndex], timeStamp, ContextType.Emotion);
				long localTime = TimeChecker.time;
				if(verbose)logger.info("EmoVui " + (TimeUtil.getCurTime() - localTime));
				return classifiedEmotion;
			}
    	} catch (Exception ex) {
    		System.out.println(ex.toString() + "at emoV");
    		ex.printStackTrace();
    	}
    	return null;
    }

	@Override
	public RecognizerType getType() {
		// TODO Auto-generated method stub
		return RecognizerType.ER;
	}
	
	RandomAccessFile rndF;
	public RandomAccessFile getrndFile(){
		return rndF;
	}
	public void stop_writing(int payloadSize) throws IOException {
		//randomAccessWriter.write(buffer);
		rndF.seek(4); // Write size to RIFF header
		rndF.writeInt(Integer.reverseBytes(36 + payloadSize));

		rndF.seek(40); // Write size to Subchunk2Size
										// field
		rndF.writeInt(Integer.reverseBytes(payloadSize));
		rndF.close();

	}
	public void prepare(String path) throws IOException {
		AudioFormat af =new AudioFormat(Encoding.PCM_SIGNED, 44100, 16, 1, 2, 44100, false);
		rndF = new RandomAccessFile(path, "rw");
		rndF.setLength(0);
		rndF.writeBytes("RIFF");
		// Final file size not known yet, write 0
		rndF.writeInt(0);
		rndF.writeBytes("WAVE");
		rndF.writeBytes("fmt ");
		// Sub-chunk size, 16 for PCM
		rndF.writeInt(Integer.reverseBytes(16));
		// AudioFormat, 1 for PCM
		rndF.writeShort(Short.reverseBytes((short) 1));
		// Number of channels, 1 for mono, 2 for stereo
		rndF.writeShort(Short.reverseBytes((short) af.getChannels()));
		// Sample rate
		rndF.writeInt(Integer.reverseBytes((int) af.getSampleRate()));
		// Byte rate,
		// SampleRate*NumberOfChannels*BitsPerSample/8
		rndF.writeInt(Integer.reverseBytes((int) (af.getSampleRate() * af.getSampleSizeInBits()
				* af.getChannels() / 8)));
		// Block align, NumberOfChannels*BitsPerSample/8
		rndF.writeShort(Short.reverseBytes((short) (af.getChannels()
				* af.getSampleSizeInBits() / 8)));
		// Bits per sample
		rndF.writeShort(Short.reverseBytes((short) af.getSampleSizeInBits()));
		rndF.writeBytes("data");
		// Data chunk size not known yet, write 0
		rndF.writeInt(0);
		//buffer = new byte[framePeriod * bSamples / 8 * channel];
	}
	public double[] setAudioDataFromByteArray(byte[] data) {
		if (data.length <= 44)
    		return new double[0];
    	
    	int length = (data.length - 44) / 2;
    	double[] samples = new double[length];
    	for (int i = 0; i < length; i++)
    		samples[i] = ((data[44 + i * 2] & 0xFF) + data[44 + i * 2 + 1] * 256) / 32768.0;
    	return samples;
	}


	@Override
	public void ConsumeData(DeviceType it, DeviceData obj) {
		// TODO Auto-generated method stub
		if(it.equals(DeviceType.SmartPhone)){
			SmartphoneData data = (SmartphoneData) obj;
			timeStamp = data.getTimeStamp();
			userID = data.getUserID();
			//emoJHinput = silentRemover.preprocessing(data); //Audio Input Stream for removing silent
	    	if(data.getAudioSensoryData() != null){
	    		EmotionData ed = new EmotionData(data.getAudioSensoryData(), data.getTimeStamp());
	    		setData(ed);
	    	}
			
		}
	}
	
	
	/*
	@Override
	public Runnable getRunnable(String timeStamp, LLCUnifier unifier) {
		// TODO Auto-generated method stub
		return new EmoVUIRunnable(unifier, this);
	}
	
	class EmoVUIRunnable implements Runnable{
		LLCUnifier unifier;
		AudioEmotionRecognizerV cla;
		private RandomAccessFile randomAccessWriter;
		
		public RandomAccessFile getRandomAccessWriter(){
			return randomAccessWriter;
		}
		AudioFormat af =new AudioFormat(Encoding.PCM_SIGNED, 44100, 16, 1, 2, 44100, false);
		private int payloadSize = 0;
		
		public EmoVUIRunnable(LLCUnifier unifier, AudioEmotionRecognizerV cla){
			this.unifier = unifier;
			this.cla = cla;
		}
		
		public double[] setAudioDataFromByteArray(byte[] data) {
			if (data.length <= 44)
	    		return new double[0];
	    	
	    	int length = (data.length - 44) / 2;
	    	double[] samples = new double[length];
	    	for (int i = 0; i < length; i++)
	    		samples[i] = ((data[44 + i * 2] & 0xFF) + data[44 + i * 2 + 1] * 256) / 32768.0;
	    	return samples;
		}
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			if(cla.isThreasholdReached()){
				
				File file1 = new File("D:/Audio.wav");
				try {
					file1.createNewFile();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				try {
					prepare("D:/Audio.wav");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				payloadSize = input.getAudiodata().length;
				try {
					randomAccessWriter.write(input.getAudiodata());
					stop_writing();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				SmartphoneData sd = new SmartphoneData();
				
				sd.setSamples(setAudioDataFromByteArray(audiodata));
				ContextLabel result = null;
				try{
					result = cla.recognize(sd, timeStamp);
				}catch(Exception e){
					e.printStackTrace();
					System.out.println(e.toString());
				}
				audiodata = null;
				unifier.push(result, RecognizerType.ER);
				if(verbose)logger.info(userID + "\t" + result.getLabel() + "\t" + timeStamp);
			}else{
				if(verbose)logger.info(userID + "\t" + "NoEmotion" + "\t" + timeStamp);
				unifier.push(new ContextLabel(userID, "NoEmotion", timeStamp, ContextType.Emotion), RecognizerType.ER);
				
			}
				
				
			
		}
		public void prepare(String path) throws IOException {

			randomAccessWriter = new RandomAccessFile(path, "rw");
			randomAccessWriter.setLength(0);
			randomAccessWriter.writeBytes("RIFF");
			// Final file size not known yet, write 0
			randomAccessWriter.writeInt(0);
			randomAccessWriter.writeBytes("WAVE");
			randomAccessWriter.writeBytes("fmt ");
			// Sub-chunk size, 16 for PCM
			randomAccessWriter.writeInt(Integer.reverseBytes(16));
			// AudioFormat, 1 for PCM
			randomAccessWriter.writeShort(Short.reverseBytes((short) 1));
			// Number of channels, 1 for mono, 2 for stereo
			randomAccessWriter.writeShort(Short.reverseBytes((short) af.getChannels()));
			// Sample rate
			randomAccessWriter.writeInt(Integer.reverseBytes((int) af.getSampleRate()));
			// Byte rate,
			// SampleRate*NumberOfChannels*BitsPerSample/8
			randomAccessWriter.writeInt(Integer.reverseBytes((int) (af.getSampleRate() * af.getSampleSizeInBits()
					* af.getChannels() / 8)));
			// Block align, NumberOfChannels*BitsPerSample/8
			randomAccessWriter.writeShort(Short.reverseBytes((short) (af.getChannels()
					* af.getSampleSizeInBits() / 8)));
			// Bits per sample
			randomAccessWriter.writeShort(Short.reverseBytes((short) af.getSampleSizeInBits()));
			randomAccessWriter.writeBytes("data");
			// Data chunk size not known yet, write 0
			randomAccessWriter.writeInt(0);
			//buffer = new byte[framePeriod * bSamples / 8 * channel];

		}

		public void stop_writing() throws IOException {
			//randomAccessWriter.write(buffer);
			randomAccessWriter.seek(4); // Write size to RIFF header
			randomAccessWriter.writeInt(Integer.reverseBytes(36 + payloadSize));

			randomAccessWriter.seek(40); // Write size to Subchunk2Size
											// field
			randomAccessWriter.writeInt(Integer.reverseBytes(payloadSize));
			randomAccessWriter.close();

		}
	}*/

}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/test/java/org/uclab/scl/framework/recinterpreter/ContextSelectorTest.java<|end_filename|>
package org.uclab.scl.framework.recinterpreter;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.uclab.scl.framework.RecInterpreter.PARecommender.ContextSelector;
import static org.junit.Assert.*;

public class ContextSelectorTest {
	private static ContextSelector contextSelector;
	
	@BeforeClass
	public static void setup(){
		contextSelector = new ContextSelector();
	}
	
	@AfterClass
	public static void windeup(){
		
	}
	
	
	
	
	@Test
	public void selectContextTestHomeCase(){
		String receivedContext = "Home,Inactivity,Sunny,Neutral,No";
		
		boolean expected = true;
		boolean actual = contextSelector.selectContext(receivedContext);
		
		assertEquals(expected, actual);
	}
	
	@Test
	public void selectContextTestOfficeCase(){
		String receivedContext = "Office,OfficeWork,Sunny,Neutral,No";
		
		boolean expected = true;
		boolean actual = contextSelector.selectContext(receivedContext);
		
		assertEquals(expected, actual);
	}
	
	@Test
	public void selectContextTestMealCase(){
		String receivedContext = "Home,HavingMeal,Sunny,Neutral,No";
		
		boolean expected = false;
		boolean actual = contextSelector.selectContext(receivedContext);		
		assertEquals(expected, actual);
	}
	
	@Test
	public void selectContextTestOfficeLocationUnavailableCase(){
		String receivedContext = "UnidentifiedLocation,HavingMeal,Sunny,Neutral,No";
		
		boolean expected = false;
		boolean actual = contextSelector.selectContext(receivedContext);
		
		assertEquals(expected, actual);
	}
	
	@Test
	public void selectContextTestOfficeContextUnavailabeCase(){
		String receivedContext = "UnidentifiedLocation,UnidentifiedHLC,UnidentifiedWeather,UnidentifiedEmotion,No";
		
		boolean expected = true;
		boolean actual = contextSelector.selectContext(receivedContext);
		
		assertEquals(expected, actual);
	}	
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/ic/dataadapter/UserRecognizedActivityLogAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.ic.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.ic.UserRecognizedActivity;
import org.uclab.mm.datamodel.ic.UserRecognizedActivityLog;

/**
 * This is UserRecognizedActivityLogAdapter class which implements the Data Access Interface for CRUD operations
 * @author dcadmin
 */
public class UserRecognizedActivityLogAdapter implements DataAccessInterface{
    
    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(UserRecognizedActivityLogAdapter.class);
    public UserRecognizedActivityLogAdapter()
    {
        
    }

    /**
     * This is implementation function for saving UserRecognizedActivityLog. 
     * @param objUserRecognizedActivityLog
   * @return List of String
     */
    @Override
    public List<String> Save(Object objUserRecognizedActivityLog) {
        UserRecognizedActivityLog objInnerUserRecognizedActivityLog = new UserRecognizedActivityLog();
        objInnerUserRecognizedActivityLog =  (UserRecognizedActivityLog) objUserRecognizedActivityLog;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_UserRecognizedActivityLog(?, ?, ?, ?, ?)}");
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
            Date dtStartDate = sdf.parse(objInnerUserRecognizedActivityLog.getStartTime());
            Timestamp tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);
            
            Date dtEndDate = sdf.parse(objInnerUserRecognizedActivityLog.getEndTime());
            Timestamp tsEndDate = new Timestamp(dtEndDate.getYear(),dtEndDate.getMonth(), dtEndDate.getDate(), dtEndDate.getHours(), dtEndDate.getMinutes(),dtEndDate.getSeconds(),0);
            
            objCallableStatement.setLong("UserID", objInnerUserRecognizedActivityLog.getUserId());
            objCallableStatement.setInt("ActivityID", objInnerUserRecognizedActivityLog.getActivityId());
            objCallableStatement.setTimestamp("StartTime", tsStartDate);
            objCallableStatement.setTimestamp("EndTime", tsEndDate);
                                   
            objCallableStatement.registerOutParameter("UserRecognizedActivityLogID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intUserRecognizedActivityLogID = objCallableStatement.getLong("UserRecognizedActivityLogID");
            objDbResponse.add(String.valueOf(intUserRecognizedActivityLogID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("user recognized activities Log saved successfully, User Details="+objUserRecognizedActivityLog);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding user recognized activities Log");
        	objDbResponse.add("Error in adding user recognized activities Log");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for Updating UserRecognizedActivityLog. 
     * Not Implemented
     */
    @Override
    public <T> List<String> Update(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet."); 
    }

    /**
     * This is implementation function for retrieving UserRecognizedActivityLog. 
     * @param objUserRecognizedActivityLog
     * @return List of UserRecognizedActivityLog
     */
    @Override
    public List<UserRecognizedActivityLog> RetriveData(Object objUserRecognizedActivityLog) {
        UserRecognizedActivityLog objOuterUserRecognizedActivityLog = new UserRecognizedActivityLog();
        List<UserRecognizedActivityLog> objListInnerUserRecognizedActivityLog = new ArrayList<UserRecognizedActivityLog>();
        objOuterUserRecognizedActivityLog =  (UserRecognizedActivityLog) objUserRecognizedActivityLog;
        
        try
        {
            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UserRecognizedActivityLogByUserID(?, ?, ?)}");
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
            Date dtStartDate = sdf.parse(objOuterUserRecognizedActivityLog.getStartTime());
            Timestamp tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);
            
            Date dtEndDate =sdf.parse( objOuterUserRecognizedActivityLog.getEndTime()); //.getTime();
            Timestamp tsEndDate = new Timestamp(dtEndDate.getYear(),dtEndDate.getMonth(), dtEndDate.getDate(), dtEndDate.getHours(), dtEndDate.getMinutes(),dtEndDate.getSeconds(),0);
                        
            objCallableStatement.setLong("UserID", objOuterUserRecognizedActivityLog.getUserId());
            objCallableStatement.setTimestamp("StartTime", tsStartDate);
            objCallableStatement.setTimestamp("EndTime", tsEndDate);
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                UserRecognizedActivityLog objInnerUserRecognizedActivityLog = new UserRecognizedActivityLog();
                objInnerUserRecognizedActivityLog.setUserRecognizedActivityLogId(objResultSet.getLong("UserRecognizedActivityLogID"));
                objInnerUserRecognizedActivityLog.setUserId(objResultSet.getLong("UserID"));
                objInnerUserRecognizedActivityLog.setActivityId(objResultSet.getInt("ActivityID"));
                objInnerUserRecognizedActivityLog.setActivityDescription(objResultSet.getString("ActivityDescription"));
                
                tsStartDate = objResultSet.getTimestamp("StartTime"); //updated
                objInnerUserRecognizedActivityLog.setStartTime(tsStartDate.toString());
                
                tsEndDate = objResultSet.getTimestamp("EndTime"); // updated
                objInnerUserRecognizedActivityLog.setEndTime(tsEndDate.toString());
                
                objListInnerUserRecognizedActivityLog.add(objInnerUserRecognizedActivityLog);
            }
            objConn.close();
            logger.info("users recognized activities log laoded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading users recognized activities log");
        }   
        return objListInnerUserRecognizedActivityLog;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet."); 
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/dc/Users.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.dc;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 *
 * @author Taqdir
 */
@Entity
public class Users implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id = null;
    private Long userID;
    private String firstName;
    private String lastName;
    private String middleName;
    private int genderId;
    //private GregorianCalendar dateOfBirth; updated
    private String dateOfBirth;
    private String contactNumber;
    private String emailAddress;
    private int martialStatusId;
    private int activityLevelId;
    private String activityLevelDescription;
    private int occupationId;
    private String password;
    private String requestType;
    
    private int userTypeID ;
    private String userTypeDescription;
    private String genderDescription;
    private String maritalStatusDescription;
    private String occupationDescription;
    

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Users)) {
            return false;
        }
        Users other = (Users) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.dc.Users[ id=" + id + " ]";
    }

    /**
     * @return the userID
     */
    public Long getUserID() {
        return userID;
    }

    /**
     * @param userID the userID to set
     */
    public void setUserID(Long userID) {
        this.userID = userID;
    }

    /**
     * @return the firstName
     */
    public String getFirstName() {
        return firstName;
    }

    /**
     * @param firstName the firstName to set
     */
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    /**
     * @return the lastName
     */
    public String getLastName() {
        return lastName;
    }

    /**
     * @param lastName the lastName to set
     */
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    /**
     * @return the middleName
     */
    public String getMiddleName() {
        return middleName;
    }

    /**
     * @param middleName the middleName to set
     */
    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }

    /**
     * @return the genderId
     */
    public int getGenderId() {
        return genderId;
    }

    /**
     * @param genderId the genderId to set
     */
    public void setGenderId(int genderId) {
        this.genderId = genderId;
    }

    /**
     * @return the dateOfBirth updated
     */
    public String getDateOfBirth() {
        return dateOfBirth;
    }

    /**
     * @param dateOfBirth the dateOfBirth to set
     */
    public void setDateOfBirth(String dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    /**
     * @return the contactNumber
     */
    public String getContactNumber() {
        return contactNumber;
    }

    /**
     * @param contactNumber the contactNumber to set
     */
    public void setContactNumber(String contactNumber) {
        this.contactNumber = contactNumber;
    }

    /**
     * @return the emailAddress
     */
    public String getEmailAddress() {
        return emailAddress;
    }

    /**
     * @param emailAddress the emailAddress to set
     */
    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }

    /**
     * @return the martialStatusId
     */
    public int getMartialStatusId() {
        return martialStatusId;
    }

    /**
     * @param martialStatusId the martialStatusId to set
     */
    public void setMartialStatusId(int martialStatusId) {
        this.martialStatusId = martialStatusId;
    }

    /**
     * @return the activityLevelId
     */
    public int getActivityLevelId() {
        return activityLevelId;
    }

    /**
     * @param activityLevelId the activityLevelId to set
     */
    public void setActivityLevelId(int activityLevelId) {
        this.activityLevelId = activityLevelId;
    }

    /**
     * @return the occupationId
     */
    public int getOccupationId() {
        return occupationId;
    }

    /**
     * @param occupationId the occupationId to set
     */
    public void setOccupationId(int occupationId) {
        this.occupationId = occupationId;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * @return the requestType
     */
    public String getRequestType() {
        return requestType;
    }

    /**
     * @param requestType the requestType to set
     */
    public void setRequestType(String requestType) {
        this.requestType = requestType;
    }

    /**
     * @return the activityLevelDescription
     */
    public String getActivityLevelDescription() {
        return activityLevelDescription;
    }

    /**
     * @param activityLevelDescription the activityLevelDescription to set
     */
    public void setActivityLevelDescription(String activityLevelDescription) {
        this.activityLevelDescription = activityLevelDescription;
    }

    /**
     * @return the userTypeID
     */
    public int getUserTypeID() {
        return userTypeID;
    }

    /**
     * @param userTypeID the userTypeID to set
     */
    public void setUserTypeID(int userTypeID) {
        this.userTypeID = userTypeID;
    }

    /**
     * @return the userTypeDescription
     */
    public String getUserTypeDescription() {
        return userTypeDescription;
    }

    /**
     * @param userTypeDescription the userTypeDescription to set
     */
    public void setUserTypeDescription(String userTypeDescription) {
        this.userTypeDescription = userTypeDescription;
    }

    /**
     * @return the genderDescription
     */
    public String getGenderDescription() {
        return genderDescription;
    }

    /**
     * @param genderDescription the genderDescription to set
     */
    public void setGenderDescription(String genderDescription) {
        this.genderDescription = genderDescription;
    }

    /**
     * @return the maritalStatusDescription
     */
    public String getMaritalStatusDescription() {
        return maritalStatusDescription;
    }

    /**
     * @param maritalStatusDescription the maritalStatusDescription to set
     */
    public void setMaritalStatusDescription(String maritalStatusDescription) {
        this.maritalStatusDescription = maritalStatusDescription;
    }

    /**
     * @return the occupationDescription
     */
    public String getOccupationDescription() {
        return occupationDescription;
    }

    /**
     * @param occupationDescription the occupationDescription to set
     */
    public void setOccupationDescription(String occupationDescription) {
        this.occupationDescription = occupationDescription;
    }

    
}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/Utilities/RiskFactorFinderUtility.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.Utilities;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.uclab.scl.datamodel.RiskFactors;

/**
 * 
 * @author User
 */
public class RiskFactorFinderUtility {

  private List<String> riskFactors;
  
  private RiskFactorFinderUtility(){}
  public static RiskFactorFinderUtility getRiskFactorFinderUtility(){
    return RiskFactorFinderUtilityHolder.INSTANCE;
  }
  /**
   * @return the riskFactors
   */
  public Map<String, String> getRiskFactors(List<RiskFactors> rf) {

    Map<String, String> riskDictionary = new HashMap<String, String>();

    Iterator<RiskFactors> itr = rf.iterator();

    while (itr.hasNext()) {

      switch (itr.next().getRiskFactorId()) {
      case 1:

        riskDictionary.put("Diabetes", "Yes");
        // riskFactors.add("Diabetes");
        break;

      case 2:

        riskDictionary.put("Cardiovascular", "Yes");
        // riskFactors.add("Cardiovascular");
        break;

      case 3:

        riskDictionary.put("Hypertension", "Yes");
        // riskFactors.add("Hypertension");
        break;

      case 4:

        riskDictionary.put("Pregnant", "Yes");
        // riskFactors.add("Pregnant");
        break;

      case 5:
        riskDictionary.put("Normal", "Yes");
        // riskFactors.add("Normal");
        break;

      case 6:

        riskDictionary.put("None", "Yes");
        // riskFactors.add("Normal");
        break;
      case 7:
        riskDictionary.put("Back Pain", "Yes");
        break;

      // default:
      //
      // riskDictionary.put("None", "Yes");
      // riskFactors.add("None");
      // break;
      }

    }

    return riskDictionary;
  }

  /**
   * @param riskFactors
   *          the riskFactors to set
   */
  public void setRiskFactors(List<String> riskFactors) {
    this.riskFactors = riskFactors;
  }
  
  private static class RiskFactorFinderUtilityHolder{
    private static final RiskFactorFinderUtility INSTANCE = new RiskFactorFinderUtility();
  }
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/UserPreferredActivities.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author Taqdir
 */
@Entity
public class UserPreferredActivities implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private Long userPreferredActivityId;
    private Long userId;
    private int activityId;
    private int preferenceLevelId;
    
    

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof UserPreferredActivities)) {
            return false;
        }
        UserPreferredActivities other = (UserPreferredActivities) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.sc.UserPreferredActivities[ id=" + id + " ]";
    }

    /**
     * @return the userPreferredActivityId
     */
    public Long getUserPreferredActivityId() {
        return userPreferredActivityId;
    }

    /**
     * @param userPreferredActivityId the userPreferredActivityId to set
     */
    public void setUserPreferredActivityId(Long userPreferredActivityId) {
        this.userPreferredActivityId = userPreferredActivityId;
    }

    /**
     * @return the userId
     */
    public Long getUserId() {
        return userId;
    }

    /**
     * @param userId the userId to set
     */
    public void setUserId(Long userId) {
        this.userId = userId;
    }

    /**
     * @return the activityId
     */
    public int getActivityId() {
        return activityId;
    }

    /**
     * @param activityId the activityId to set
     */
    public void setActivityId(int activityId) {
        this.activityId = activityId;
    }

    /**
     * @return the preferenceLevelId
     */
    public int getPreferenceLevelId() {
        return preferenceLevelId;
    }

    /**
     * @param preferenceLevelId the preferenceLevelId to set
     */
    public void setPreferenceLevelId(int preferenceLevelId) {
        this.preferenceLevelId = preferenceLevelId;
    }
    
}


<|start_filename|>knowledge-curation-layer/DDKAT/src/main/java/org/uclab/mm/kcl/ddkat/datapreprocessor/DataDiscretizer.java<|end_filename|>
/**
 * Copyright [2017] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.mm.kcl.ddkat.datapreprocessor;

import java.io.File;
import java.util.ArrayList;

import weka.filters.Filter;
import weka.filters.unsupervised.attribute.Discretize;
import weka.core.Instances;
import weka.core.converters.ArffSaver;
import weka.core.converters.CSVLoader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// TODO: Auto-generated Javadoc
/**
 * This class discretizes the data using equal-width binning approach and then stores the discretized data.
 */
public class DataDiscretizer {
	
	/** The confirmation message. */
	private ArrayList<String> confirmationMessage;
	
	/** The Constant log. */
	private static final Logger log = LoggerFactory.getLogger(DataDiscretizer.class);
	
	/** base directory to store resource data files */
	private static final String BASE_DIR = System.getProperty("user.home") + "/DDKAT/resources/";
		
	/**
	 * Constructor to instantiate a new DataDiscretizer object.
	 *
	 * @throws Exception the exception
	 */
	public DataDiscretizer() throws Exception {
		
		discretizeData();
	}
	
	/**
	 * Method to discretize the input data using equal-width binning approach.
	 *
	 * @throws Exception the exception
	 */
	public void discretizeData() throws Exception {
				
		this.confirmationMessage = new ArrayList<String>();
		
		Instances inputData, outputData;
		String inputFile = BASE_DIR + "OriginalDataSet.csv";
				
		// load CSV file
		CSVLoader fileLoader=new CSVLoader();
		fileLoader.setSource(new File(inputFile));
	    inputData = fileLoader.getDataSet();
       		
		Discretize discrete = new Discretize();
        discrete.setInputFormat(inputData);
        outputData = Filter.useFilter(inputData, discrete);
        
        saveDiscretizedData(inputFile, outputData);
        
 	}
	
	/**
	 * Method to store the discretized data.
	 *
	 * @param filePath the file path
	 * @param outputData the output data
	 * @throws Exception the exception
	 */
	public void saveDiscretizedData(String filePath, Instances outputData) throws Exception {
 
        // save ARFF file
        String outputFile = filePath.substring(0,filePath.lastIndexOf('/'));
        outputFile = outputFile + "/ProcessedDataSet.arff";
        log.info("Output file : "+outputFile);
        
        ArffSaver saver = new ArffSaver();
        saver.setInstances(outputData);
        saver.setFile(new File(outputFile));
        saver.writeBatch();
                           
        String confirmationMessageStr = "Data is successfully discretized and is stored at : "+outputFile;
        log.info(confirmationMessageStr);
        this.confirmationMessage.add(confirmationMessageStr);                        
	}
	
	/**
	 * Method to get the confirmation message of data discretization.
	 *
	 * @return the confirmation message
	 */
	public ArrayList<String> getConfirmationMessage() {
		return confirmationMessage;
	}

	/**
	 * Method to set the confirmation message of data discretization.
	 *
	 * @param confirmationMessage the new confirmation message
	 */
	public void setConfirmationMessage(ArrayList<String> confirmationMessage) {
		this.confirmationMessage = confirmationMessage;
	}

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/dataadapter/RecommendationExplanationAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.sc.Recommendation;
import org.uclab.mm.datamodel.sc.RecommendationExplanation;

/**
 * This is RecommendationExplanationAdapter class which implements the Data Access Interface for CRUD operations
 * @author <NAME>
 */
public class RecommendationExplanationAdapter implements DataAccessInterface {

    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(RecommendationExplanationAdapter.class);
    public RecommendationExplanationAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving RecommendationExplanation. 
     * @param objRecommendationExplanation
     * @return List of String
     */
    @Override
    public List<String> Save(Object objRecommendationExplanation) {
        RecommendationExplanation objInnerRecommendationExplanation = new RecommendationExplanation();
        objInnerRecommendationExplanation =  (RecommendationExplanation) objRecommendationExplanation;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_RecommendationExplanation(?, ?, ?, ?)}");
            
            objCallableStatement.setLong("RecommendationID", objInnerRecommendationExplanation.getRecommendationID());
            objCallableStatement.setString("FactExplanation", objInnerRecommendationExplanation.getFactExplanation());
            objCallableStatement.setInt("FactCategoryID", objInnerRecommendationExplanation.getFactCategoryID());
            
            objCallableStatement.registerOutParameter("RecommendationExplanationID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intRecommendationExplanationID = objCallableStatement.getLong("RecommendationExplanationID");
            objDbResponse.add(String.valueOf(intRecommendationExplanationID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("RecommendationExplanation saved successfully, RecommendationExplanation Details="+objRecommendationExplanation);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding RecommendationExplanation");
        	objDbResponse.add("Error in adding RecommendationExplanation");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for updating RecommendationExplanation. 
     * @param objRecommendationExplanation
     * @return List of String
     */
    @Override
    public List<String> Update(Object objRecommendationExplanation) {
        RecommendationExplanation objInnerRecommendationExplanation = new RecommendationExplanation();
        objInnerRecommendationExplanation =  (RecommendationExplanation) objRecommendationExplanation;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_RecommendationExplanation(?, ?, ?, ?)}");
            
            objCallableStatement.setLong("RecommendationExplanationID", objInnerRecommendationExplanation.getRecommendationExplanationID());
            objCallableStatement.setLong("RecommendationID", objInnerRecommendationExplanation.getRecommendationID());
            objCallableStatement.setString("FactExplanation", objInnerRecommendationExplanation.getFactExplanation());
            objCallableStatement.setInt("FactCategoryID", objInnerRecommendationExplanation.getFactCategoryID());
            
            objCallableStatement.execute();
            
            Long intRecommendationExplanationID = objInnerRecommendationExplanation.getRecommendationExplanationID();
            objDbResponse.add(String.valueOf(intRecommendationExplanationID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("RecommendationExplanation updated successfully, RecommendationExplanation Details="+objRecommendationExplanation);
        }
        catch (Exception e)
        {
        	logger.info("Error in updating RecommendationExplanation");
        	objDbResponse.add("Error in updating RecommendationExplanation");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for retrieving RecommendationExplanation. 
     * @param objRecommendationExplanation
     * @return List of RecommendationExplanation
     */
    @Override
    public List<RecommendationExplanation> RetriveData(Object objRecommendationExplanation) {
        
        RecommendationExplanation objOuterRecommendationExplanation = new RecommendationExplanation();
        List<RecommendationExplanation> objListInnerRecommendationExplanation = new ArrayList<RecommendationExplanation>();
        objOuterRecommendationExplanation =  (RecommendationExplanation) objRecommendationExplanation;
        
        try
        {
            CallableStatement objCallableStatement = null;
            objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_RecommendationExplanationByRecommendationID(?)}");
                
            objCallableStatement.setLong("RecommendationID", objOuterRecommendationExplanation.getRecommendationID());
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                RecommendationExplanation objInnerRecommendationExplanation = new RecommendationExplanation();
                
                objInnerRecommendationExplanation.setRecommendationExplanationID(objResultSet.getLong("RecommendationExplanationID"));
                objInnerRecommendationExplanation.setRecommendationID(objResultSet.getLong("RecommendationID"));
                objInnerRecommendationExplanation.setFactExplanation(objResultSet.getString("FactExplanation"));
                objInnerRecommendationExplanation.setFactCategoryID(objResultSet.getInt("FactCategoryID"));
                objInnerRecommendationExplanation.setFactCategoryDescription(objResultSet.getString("FactCategoryDescription"));
                
                objListInnerRecommendationExplanation.add(objInnerRecommendationExplanation);
            }
            objConn.close();
            logger.info("Recommendation Explanation loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading Recommendation Explanation");
        }   
        return objListInnerRecommendationExplanation;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet."); 
    }

    /**
     * This is implementation function for connection database.
     * @param objConf 
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/objectmodel/SituationEvent.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */
package org.uclab.mm.dcl.llm.objectmodel;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * This class is used to define the object that comprises of data model list.
 * A list may contain multiple data model
 * @author Rizvi
 */
@XmlRootElement()
public class SituationEvent implements Serializable{

  private String SituationID;
  private List<SituationConditions> ListSConditions = new ArrayList<SituationConditions>();

  /**
   * This method is used to return the particular unique id of situation associated with block of condition and constraint.
   * @return the SituationID
   */
  public String getSituationID(){
    return SituationID;
  }

  /**
   * This method is used to set the particular unique id of situation associated with block of condition and constraint provided in .
   * @param SituationID the SituationID to set
   */
  public void setSituationID(String SituationID){
    this.SituationID = SituationID;
  }

  /**
   * The method is used to set the conditions in a object that consist of list of conditions.
   * @return the ListSConditions
   */
  public List<SituationConditions> getListSConditions(){
    return ListSConditions;
  }

  /**
   * The method is used to return the conditions in a object that consist of list of conditions.
   * @param ListSConditions the ListSConditions to set
   */
  public void setListSConditions(List<SituationConditions> ListSConditions){
    this.ListSConditions = ListSConditions;
  }

}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/AR/iar/AR_makeARFF.java<|end_filename|>
/**
Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */

package org.uclab.mm.icl.llc.AR.iar;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.uclab.mm.icl.utils.FileUtil;

public class AR_makeARFF {

	String device_header = "@relation sm_acc_gyro\n" + "@attribute accX_average REAL\n"
			+ "@attribute accY_average REAL\n" + "@attribute accZ_average REAL\n" + "@attribute accX_max REAL\n"
			+ "@attribute accY_max REAL\n" + "@attribute accZ_max REAL\n" + "@attribute accX_min REAL\n"
			+ "@attribute accY_min REAL\n" + "@attribute accZ_min REAL\n" + "@attribute accX_deviation REAL\n"
			+ "@attribute accY_deviation REAL\n" + "@attribute accZ_deviation REAL\n"
			+ "@attribute accX_crossing REAL\n" + "@attribute accY_crossing REAL\n"
			+ "@attribute accZ_crossing REAL\n" + "@attribute accX_quartile REAL\n"
			+ "@attribute accY_quartile REAL\n" + "@attribute accZ_quartile REAL\n"
			+ "@attribute accX_meanabs REAL\n" + "@attribute accY_meanabs REAL\n" + "@attribute accZ_meanabs REAL\n"
			+ "@attribute gyroX_average REAL\n" + "@attribute gyroY_average REAL\n"
			+ "@attribute gyroZ_average REAL\n" + "@attribute gyroX_max REAL\n" + "@attribute gyroY_max REAL\n"
			+ "@attribute gyroZ_max REAL\n" + "@attribute gyroX_min REAL\n" + "@attribute gyroY_min REAL\n"
			+ "@attribute gyroZ_min REAL\n" + "@attribute gyroX_deviation REAL\n"
			+ "@attribute gyroY_deviation REAL\n" + "@attribute gyroZ_deviation REAL\n"
			+ "@attribute gyroX_crossing REAL\n" + "@attribute gyroY_crossing REAL\n"
			+ "@attribute gyroZ_crossing REAL\n" + "@attribute gyroX_quartile REAL\n"
			+ "@attribute gyroY_quartile REAL\n" + "@attribute gyroZ_quartile REAL\n"
			+ "@attribute gyroX_meanabs REAL\n" + "@attribute gyroY_meanabs REAL\n"
			+ "@attribute gyroZ_meanabs REAL\n"
			+ "@attribute action {Eating,Running,Sitting,Standing,Walking,Stretching,Sweeping,LyingDown}\n"
			+ "@data\n";
	String integrated_header = "@relation integrated30_w3\n" + "@attribute range_wgyroz REAL\n"
			+ "@attribute max_saccy REAL\n" + "@attribute range_saccz REAL\n" + "@attribute std_saccy REAL\n"
			+ "@attribute std_saccz REAL\n" + "@attribute quartile_saccy REAL\n"
			+ "@attribute quartile_saccz REAL\n" + "@attribute meanabs_saccy REAL\n"
			+ "@attribute meanabs_saccz REAL\n" + "@attribute medianabs_saccy REAL\n"
			+ "@attribute medianabs_saccz REAL\n" + "@attribute std_sgyrox REAL\n"
			+ "@attribute meanabs_sgyrox REAL\n" + "@attribute max_waccx REAL\n" + "@attribute std_wgyroz REAL\n"
			+ "@attribute meanabs_wgyroz REAL\n" + "@attribute average_saccz REAL\n"
			+ "@attribute median_saccz REAL\n" + "@attribute range_saccy REAL\n"
			+ "@attribute trimmean_saccz REAL\n" + "@attribute std_saccx REAL\n" + "@attribute meanabs_saccx REAL\n"
			+ "@attribute medianabs_saccx REAL\n" + "@attribute min_sgyrox REAL\n" + "@attribute min_sgyroy REAL\n"
			+ "@attribute range_sgyrox REAL\n" + "@attribute range_sgyroy REAL\n"
			+ "@attribute geomean_sgyrox REAL\n" + "@attribute quartile)sgyrox REAL\n"
			+ "@attribute medianabs_sgyrox REAL\n" + "@attribute a1 REAL\n" + "@attribute a2 REAL\n"
			+ "@attribute a3 REAL\n" + "@attribute a4 REAL\n" + "@attribute a5 REAL\n" + "@attribute a6 REAL\n"
			+ "@attribute a7 REAL\n" + "@attribute a8 REAL\n" + "@attribute a9 REAL\n" + "@attribute a10 REAL\n"
			+ "@attribute a11 REAL\n" + "@attribute a12 REAL\n" + "@attribute a13 REAL\n" + "@attribute a14 REAL\n"
			+ "@attribute a15 REAL\n" + "@attribute a16 REAL\n" + "@attribute a17 REAL\n" + "@attribute a18 REAL\n"
			+ "@attribute a19 REAL\n"
			+ "@attribute action {Eating,Running,Sitting,Standing,Walking,Stretching,Sweeping,LyingDown}\n"
			+ "@data\n";
	
	public AR_makeARFF(	double[][] acc_wm, double[][] gy_wm, double[][] acc_sm, double[][] gy_sm) throws IOException {
		double[] sm_result = AR_FeatureExtractor.MiningMindsV2_150923_basic42(acc_sm[0], acc_sm[1], acc_sm[2],
				gy_sm[0], gy_sm[1], gy_sm[2]);
		double[] wm_result = AR_FeatureExtractor.MiningMindsV2_150923_basic42(acc_sm[0], acc_sm[1], acc_sm[2],
				gy_sm[0], gy_sm[1], gy_sm[2]);
		double[] in_result = AR_FeatureExtractor.MiningMindsV2_151005_integrated50(acc_sm[0], acc_sm[1], acc_sm[2],
				acc_wm[0], acc_wm[1], acc_wm[2], gy_sm[0], gy_sm[1], gy_sm[2], gy_wm[0], gy_wm[1], gy_wm[2]);

		// Make smartphone feature list ARFF file
		BufferedWriter bw = new BufferedWriter(new FileWriter(new File(FileUtil.getRootPath() + "ar/" + "/sm.txt")));
		bw.write(device_header);
		for (int j = 0; j < sm_result.length; j++) {
			bw.write(sm_result[j] + ",");
		}
		bw.write("Sweeping"); // Temporarily saving arbitrary label to comply the ARFF form
		bw.close();

		// Make wearable feature list ARFF file
		bw = new BufferedWriter(new FileWriter(new File(FileUtil.getRootPath() + "/ar/" + "/wm.txt")));
		bw.write(device_header);
		for (int j = 0; j < wm_result.length; j++) {
			bw.write(wm_result[j] + ",");
		}
		bw.write("Sweeping"); // Temporarily saving arbitrary label to comply the ARFF form
		bw.close();

		// Make integrated feature list ARFF file
		bw = new BufferedWriter(new FileWriter(new File(FileUtil.getRootPath() + "/ar/" + "/integrated.txt")));
		bw.write(integrated_header);
		for (int j = 0; j < in_result.length; j++) {
			bw.write(in_result[j] + ",");
		}
		bw.write("Sweeping"); // Temporarily saving arbitrary label to comply the ARFF form
		bw.close();
	}
}


<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/monitoring/RestServiceNotification.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */
package org.uclab.mm.dcl.llm.monitoring;

import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import org.uclab.mm.dcl.llm.objectmodel.SCLResponse;
import org.uclab.mm.dcl.llm.objectmodel.SituationNotification;

/**
 *This class is concrete implementation of ServiceNotificationChannel Interface.
 * @author Rizvi
 */
public class RestServiceNotification implements ServiceNotificationChannel{
/**
 *  This method is used to send notification to the SCL through PushPARecommendation by consuming the web service.
 * @param objSituationNotification
 * @param serviceName 
 * 
 */
  @Override
  public void notifyToRestService(SituationNotification objSituationNotification, String serviceName){
    try{
      ClientConfig config = new DefaultClientConfig();
      config.getClasses().add(JacksonJsonProvider.class);
      Client client = Client.create(config);
      final String baseURI = serviceName;
      //final String baseURI = "http://192.168.3.11:8080/SCLMiningMind2.5/webresources/SCLService/PushPARecommendation";
      WebResource srv = client.resource(UriBuilder.fromUri(baseURI).build());
      ClientResponse ServerResponse = srv.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, objSituationNotification);
      SCLResponse objResult = ServerResponse.getEntity(SCLResponse.class); // make comment by bilal for sake of code testing
      if (objResult.getResult().size() > 0){
        if (objResult.getResult().get(0).toString().contains("Err")){
          System.out.println(objResult.getResult().get(0).toString());
        } else{
          for (String result : objResult.getResult()){
            System.out.println(result);
          }
        }
      }
    } catch (Exception exp){
      String error = exp.getMessage();
      System.err.println(error + ": ");
      exp.printStackTrace();
    }

  }

}


<|start_filename|>knowledge-curation-layer/i-kat/src/test/java/org/uclab/mm/kcl/edkat/service/testcases/ConditionServiceImplTest.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.kcl.edkat.service.testcases;

import static org.junit.Assert.*;

import javax.transaction.Transactional;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.uclab.mm.kcl.edkat.dao.ConditionDAO;
import org.uclab.mm.kcl.edkat.datamodel.Condition;
import org.junit.runner.RunWith;
import org.junit.Test;

/**
 * This is a class for testing the insertion, fetching, and update of Condition of a rule 
 * @author <NAME>
 *
 */

@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class ConditionServiceImplTest {

	@Autowired
	private ConditionDAO conditionDAO;
	
	/**
	 * This is function for testing the insertion, fetching, and update of Condition of a rule  
	 */
	
	@Test
	@Transactional
	@Rollback(true)
	public void test() {
		Condition objOuterCondition = new Condition();
		Condition objInnerCondition = new Condition();
		
		/* Setting the Condition Object*/
		objOuterCondition.setConditionKey("unit test 4");
		objOuterCondition.setConditionValue("unit Test Value 4");
		objOuterCondition.setConditionType("int");
		objOuterCondition.setConditionValueOperator("=");
		
		/* Testing of Insertion*/
		objInnerCondition = conditionDAO.addCondition(objOuterCondition);
		
		/* Testing of fetching the new added condition*/
		objInnerCondition = conditionDAO.getConditionById(objInnerCondition.getConditionID());
		assertEquals(objOuterCondition.getConditionKey(), objInnerCondition.getConditionKey());
		
		objInnerCondition.setConditionKey("unit test 4 updated");
		objInnerCondition.setConditionValue("unit Test Value 4 updated");
		
		/* Testing of updating*/
		Condition objInnerConditionUpdated = new Condition();
		objInnerConditionUpdated = conditionDAO.updateCondition(objInnerCondition);
		
		assertEquals(objInnerCondition.getConditionKey(), objInnerConditionUpdated.getConditionKey());
		
	}

}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/AER/jh/AERPreprocessing.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Bang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.AER.jh;

import java.io.IOException;
import java.util.Vector;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;

import org.uclab.mm.icl.data.SmartphoneData;
import org.uclab.mm.icl.llc.MachineLearningTools.Preprocessing;
import org.uclab.mm.icl.llc.MachineLearningTools.SilentRemoverPreprocessing;


public class AERPreprocessing extends
		Preprocessing<SmartphoneData, AudioInputStream> {
	SilentRemoverPreprocessing srp;

	public AERPreprocessing(AudioFormat.Encoding encoding, float sampleRate,
			int sampleSizeInBits, int channels, int frameSize, float frameRate,
			boolean bigEndian,int thresold) {
		 srp = new SilentRemoverPreprocessing(encoding, sampleRate,
					 sampleSizeInBits,  channels,  frameSize,  frameRate,
					 bigEndian, thresold);
	}
	
	@Override
	public AudioInputStream preprocessing(SmartphoneData input) {
		// TODO Auto-generated method stub
		AudioInputStream ais =srp.preprocessing(input); 
		return ais;
	}

	

}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/config/DeviceType.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Kang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.mm.icl.llc.config;

import org.uclab.mm.icl.data.DeviceData;
import org.uclab.mm.icl.data.KinectData;
import org.uclab.mm.icl.data.SmartphoneData;


/**
 * This enum class represents the data sent from a device
 * @author Nailbrainz
 *
 */
public enum DeviceType {
	SmartPhone(1), Kinect(2);
    private int value;
    
    /**
     * Unique constructor of the data type.
     * @param _value
     */
    private DeviceType(int _value){
        value = _value;
    }
    
    /**
     * This function parses JSON input string into corresponding data type, which inherits org.uclab.mm.icl.data.Data class
     * @param obj JSON string to parse
     * @return returns the corresponding parsed data
     */
    public DeviceData parseDeviceData(Object obj){
    	switch(value){
    	case 0: //this should not be happen
    		return null;
    	case 1: //smartphone
    		SmartphoneData sd = new SmartphoneData();
    		sd.setData(obj);
    		return sd;
    	case 2: //Kinect
    		KinectData kd = new KinectData();
    		kd.setData(obj);
    		return kd;
    	}
    	return null;
    }
    
    public int getValue(){
    	return value;
    }
}


<|start_filename|>supporting-layer/descriptive-analytics/src/assets/js/feedback_facts.js<|end_filename|>
AmCharts.makeChart("feedback_facts_chartdiv",
				{
					"type": "serial",
					"pathToImages": "http://cdn.amcharts.com/lib/3/images/",
					"categoryField": "category",
					"rotate": true,
					"startDuration": 1,
					"addClassNames": true,
					"classNamePrefix": "feedbackfact",
					"categoryAxis": {
						"gridPosition": "start"
					},
					"trendLines": [],
					"graphs": [
						{
							"balloonText": "[[title]] of [[category]]:[[value]]",
							"fillAlphas": 1,
							"id": "AmGraph-1",
							"title": "Negative",
							"type": "column",
							"valueField": "Negative"
						},
						{
							"balloonText": "[[title]] of [[category]]:[[value]]",
							"fillAlphas": 1,
							"id": "AmGraph-2",
							"title": "Positive",
							"type": "column",
							"valueField": "Positive"
						}
					],
					"guides": [],
					"valueAxes": [
						{
							"id": "activities_feedback",
							"stackType": "regular",
							"title": ""
						}
					],
					"allLabels": [],
					"balloon": {},
					"legend": {
						"useGraphSettings": true
					},
					
					"dataProvider": [
						{
							"category": "Facts",
							"Negative": 10,
							"Positive": 20,
						}
					]
				}
			);

<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/framework/recbuilder/ConflictResolver.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.framework.recbuilder;

import java.util.ArrayList;
import java.util.List;
import org.uclab.scl.datamodel.FiredRule;

/**
 * ConflictResolver
 * A default implementation for the org.uclab.scl.framework.recbuilder.AbstractConflictResolver
 * <p>
 * This implementation uses maximum specificity strategy to resolve conflict among multiple rules.
 *  
 * @author Sadiq
 * @version 2.5
 * @since july 2014
 *
 */

public class ConflictResolver extends AbstractConflictResolver{
  
  /**
   * Resolves conflict by using maximum specificity technique and returns the final resolved rule/s
   * 
   * @param firedRules
   * @return finalResolvedRules
   */
  @Override
  public List<FiredRule> resolveConflict(List<FiredRule> firedRules) {
    if (firedRules == null || firedRules.size() < 2) {
      return firedRules;
    }
    List<FiredRule> resolvedRules = new ArrayList<FiredRule>();
    int max = 0;
    for (FiredRule rule : firedRules) {
      int numConditions = rule.getConditionsKey();

      if (max == numConditions) {
        resolvedRules.add(rule);
      } else if (numConditions > max) {
        resolvedRules.clear();
        resolvedRules.add(rule);
        max = numConditions;
      }
    }
    return resolvedRules;
  }
}


<|start_filename|>knowledge-curation-layer/i-kat/src/main/java/org/uclab/mm/kcl/edkat/service/ConditionServiceImpl.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.kcl.edkat.service;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import org.springframework.transaction.annotation.Transactional;
import org.uclab.mm.kcl.edkat.dao.ConditionDAO;
import org.uclab.mm.kcl.edkat.dao.RuleDAOImpl;
import org.uclab.mm.kcl.edkat.datamodel.Condition;

/**
* This is service implementation for the Condition it provides implementation to 
* create, update, retrieve of condition of a specific rule
 * @author  <NAME>
 * @version 1.0
 * @since   2015-08-16
 * */

public class ConditionServiceImpl implements ConditionService {

	private ConditionDAO conditionDAO;
	/**
	 * This creation of static object of logger for Condition 
	*/
	private static final Logger logger = LoggerFactory.getLogger(RuleDAOImpl.class);
	
	
	/**
	 * getter of ConditionDAO
	*/
	public ConditionDAO getConditionDAO() {
		return conditionDAO;
	}

	/**
	 * setter of ConditionDAO
	*/
	public void setConditionDAO(ConditionDAO conditionDAO) {
		this.conditionDAO = conditionDAO;
	}

	/**
	 * This function is for add new condition
	 * @param objCondition
	 * @return object of Condition
	*/
	@Transactional
	public Condition addCondition(Condition objCondition) {
		try
		{
			Condition objInnerCondition = new Condition();
			objInnerCondition = this.conditionDAO.addCondition(objCondition);
	        logger.info("Condition saved successfully, Condition Details="+objInnerCondition);
	        return objInnerCondition;
		}
		catch(Exception ex)
		{
			logger.info("Error occured in saving new condition, Error Details="+ex.getMessage());
			return objCondition;
		}
	}

	/**
	 *  This function is for update the existing condition
	 * @param objCondition
	 * @return object of Condition
	*/
	@Transactional
	public Condition updateCondition(Condition objCondition) {
		
		try
		{
			Condition objInnerCondition = new Condition();
			objInnerCondition = this.conditionDAO.updateCondition(objCondition);
	        logger.info("Condition updated successfully, Condition Details="+objCondition);
	        return objInnerCondition;
		}
		catch(Exception ex)
		{
			logger.info("Error occured in updating existing condition, Error Details="+ex.getMessage());
			return objCondition;
		}
	}

	/**
	 * This function get all condition of the rules
	 * @return List of Condition
	*/
	public List<Condition> listCondition() {
		
		try
		{
	        List<Condition> conditionList = this.conditionDAO.listCondition();
	        return conditionList;
		}
		catch(Exception ex)
		{
			logger.info("Error occured in retrieving condition list, Error Details="+ex.getMessage());
			return null;
		}
	}

	/**
	 * This function get a specific condition by condition id (primary key)
	 * @param id
	 * @return Condition
	*/
	public Condition getConditionById(int id) {
		return this.conditionDAO.getConditionById(id);
	}
	
	/**
	 * This function delete a specific condition by condition id (primary key)
	 * @param id
	*/
	public void removeCondition(int id) {
		this.conditionDAO.removeCondition(id);
	}

	/**
	 * This function delete a all condition of the rules by key string
	 * @param objCondition
	 * @return Condition
	*/
	public Condition getConditionByFields(Condition objCondition) {
		return this.conditionDAO.getConditionByFields(objCondition);
	}

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/dc/dataadapter/UserRiskFactorsAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.dc.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.dc.UserRiskFactors;
import org.uclab.mm.datamodel.dc.Users;

/**
 * This is UserRiskFactorsAdapter class which implements the Data Access Interface for CRUD operations
 * @author Taqdir
 */
public class UserRiskFactorsAdapter implements DataAccessInterface {

    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(UserRiskFactorsAdapter.class);
    public UserRiskFactorsAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving UserRiskFactors. 
     * @param objUserRiskFactors
     * @return List of String
     */
    @Override
    public List<String> Save(Object objUserRiskFactors) {
        UserRiskFactors objInnerUserRiskFactors = new UserRiskFactors();
        objInnerUserRiskFactors =  (UserRiskFactors) objUserRiskFactors;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_UserRiskFactors(?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserID", objInnerUserRiskFactors.getUserId());
            objCallableStatement.setInt("RiskFactorID", objInnerUserRiskFactors.getRiskFactorId());
            objCallableStatement.setInt("StatusID", objInnerUserRiskFactors.getStatusId());
            
            objCallableStatement.registerOutParameter("UserRiskFactorID", Types.BIGINT);
            objCallableStatement.execute();
            
            int intUserRiskFactorID = objCallableStatement.getInt("UserRiskFactorID");
            objDbResponse.add(String.valueOf(intUserRiskFactorID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Risk factor saved successfully, User Details=" + objUserRiskFactors);
        }
        catch (Exception e)
        {
        	logger.info("Error in saving risk factor");
        	objDbResponse.add("Error in saving risk factor");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for updating UserRiskFactors. 
     * @param objUserRiskFactors
     * @return List of String
     */
    @Override
    public List<String> Update(Object objUserRiskFactors) {
        UserRiskFactors objInnerUserRiskFactors = new UserRiskFactors();
        objInnerUserRiskFactors =  (UserRiskFactors) objUserRiskFactors;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_UserRiskFactors(?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserRiskFactorID", objInnerUserRiskFactors.getUserRiskFactorId());
            objCallableStatement.setLong("UserID", objInnerUserRiskFactors.getUserId());
            objCallableStatement.setInt("RiskFactorID", objInnerUserRiskFactors.getRiskFactorId());
            objCallableStatement.setInt("StatusID", objInnerUserRiskFactors.getStatusId());
            
            objCallableStatement.execute();
            
            objDbResponse.add(String.valueOf(objInnerUserRiskFactors.getUserRiskFactorId()));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Risk factor saved successfully, User Details="+objUserRiskFactors);
        }
        catch (Exception e)
        {
        	logger.info("Error in updating risk factor");
        	objDbResponse.add("Error in updating risk factor");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for retrieving UserRiskFactors.
     * @param objUserRiskFactors
     * @return List of UserRiskFactors 
     */
    @Override
    public List<UserRiskFactors> RetriveData(Object objUserRiskFactors) {
        UserRiskFactors objOuterUserRiskFactors = new UserRiskFactors();
        List<UserRiskFactors> objListInnerUserRiskFactors = new ArrayList<UserRiskFactors>();
        objOuterUserRiskFactors =  (UserRiskFactors) objUserRiskFactors;
        
        try
        {
            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UserRiskFactorsByUserID(?)}");
            objCallableStatement.setLong("UserID", objOuterUserRiskFactors.getUserId());
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                UserRiskFactors objInnerUserRiskFactors = new UserRiskFactors();
                objInnerUserRiskFactors.setUserRiskFactorId(objResultSet.getLong("UserRiskFactorID"));
                objInnerUserRiskFactors.setUserId(objResultSet.getLong("UserID"));
                objInnerUserRiskFactors.setRiskFactorId(objResultSet.getInt("RiskFactorID"));
                objInnerUserRiskFactors.setStatusId(objResultSet.getInt("StatusID"));
                
                objListInnerUserRiskFactors.add(objInnerUserRiskFactors);
            }
            objConn.close();
            logger.info("Risk factor loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in getting risk factor");
        }   
        return objListInnerUserRiskFactors;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet."); 
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/outputModel/InterpretationModel/InterpretedRecommendations.java<|end_filename|>
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.uclab.scl.outputModel.InterpretationModel;

import java.util.List;

/**
 * 
 * @author User
 */
public class InterpretedRecommendations {

  private String recActivity;
  private String actDuration;
  private String recDescription;
  private String recURL;
  private String currentContext;

  private String foodItemList;
  private String foodDescription;

  /**
   * @return the recActivity
   */
  public String getRecActivity() {
    return recActivity;
  }

  /**
   * @param recActivity
   *          the recActivity to set
   */
  public void setRecActivity(String recActivity) {
    this.recActivity = recActivity;
  }

  /**
   * @return the actDuration
   */
  public String getActDuration() {
    return actDuration;
  }

  /**
   * @param actDuration
   *          the actDuration to set
   */
  public void setActDuration(String actDuration) {
    this.actDuration = actDuration;
  }

  /**
   * @return the recDescription
   */
  public String getRecDescription() {
    return recDescription;
  }

  /**
   * @param recDescription
   *          the recDescription to set
   */
  public void setRecDescription(String recDescription) {
    this.recDescription = recDescription;
  }

  /**
   * @return the recURL
   */
  public String getRecURL() {
    return recURL;
  }

  /**
   * @param recURL
   *          the recURL to set
   */
  public void setRecURL(String recURL) {
    this.recURL = recURL;
  }

  /**
   * @return the currentContext
   */
  public String getCurrentContext() {
    return currentContext;
  }

  /**
   * @param currentContext
   *          the currentContext to set
   */
  public void setCurrentContext(String currentContext) {
    this.currentContext = currentContext;
  }

  /**
   * @return the foodItemList
   */
  public String getFoodItemList() {
    return foodItemList;
  }

  /**
   * @param foodItemList
   *          the foodItemList to set
   */
  public void setFoodItemList(String foodItemList) {
    this.foodItemList = foodItemList;
  }

  /**
   * @return the foodDescription
   */
  public String getFoodDescription() {
    return foodDescription;
  }

  /**
   * @param foodDescription
   *          the foodDescription to set
   */
  public void setFoodDescription(String foodDescription) {
    this.foodDescription = foodDescription;
  }

}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/framework/RecInterpreter/PARecommender/PreferenceTesting.java<|end_filename|>
/* Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.scl.framework.RecInterpreter.PARecommender;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.uclab.scl.datamodel.contextMapper.PreferenceMapper;

public class PreferenceTesting {
  private static Logger LOG = LogManager.getRootLogger();
  static HashMap<String, String> mapPreference = new HashMap<>();
  
  /**
   * Preference testing for the case of a single received recommendation and alternatively more than one applications are applicable 
   * 
   * @param matResultVector
   * @param userid
   * @param context
   * @return
   * @throws Exception
   */
  public static int[] mainPrefTest(int[] matResultVector, String userid, String context) throws Exception {
    int[] ARP = PreferenceTesting.preferenceEvaluation(matResultVector,userid, context);
    int[] prefAggregate = new int[matResultVector.length];
    for (int i = 0; i < matResultVector.length; i++) {
      if ((matResultVector[i] == 1) && (ARP[i] == 1))
        prefAggregate[i] = 1;
      else
        prefAggregate[i] = 0;
    }
    return (prefAggregate);
  }
  
  /**
   * Main Preference evaluation logic for the case of a single received recommendation and alternatively more than one applications are applicable 
   * 
   * @param matResultVector
   * @param userid
   * @param context
   * @return
   * @throws Exception
   */
  @SuppressWarnings("unchecked")
  public static int[] preferenceEvaluation(int[] matResultVector, String userid, String context)
      throws Exception {
    // Check Context with Preference
    PreferenceMapper mapPref = new PreferenceMapper();

    mapPreference = mapPref.preferMapper();

    String getPref = mapPreference.containsKey(userid) ? mapPreference.get(userid) : mapPreference.get(null);
    if (getPref == null) {
      LOG.debug("Preference NOT FOUND in the repository");
      LOG.debug("Default case applied");
      getPref = mapPreference.get("dc");
    }
    
    //converting string array into int array
    String[] prefer1 = getPref.split(",");
    int[] prefer = new int[prefer1.length];
    for (int i = 0; i < prefer1.length; i++) {
      String numberAsString = prefer1[i];
      prefer[i] = Integer.parseInt(numberAsString);
    }

    for (int i = 0; i < matResultVector.length; i++)
      if ((matResultVector[i] == 1) && (prefer[i]) == 1) {
        matResultVector[i] = 1;
      } else {
        matResultVector[i] = 0;
      }
    return (matResultVector);
  } // testPreference
}



<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/objectmodel/SCLResponse.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */
package org.uclab.mm.dcl.llm.objectmodel;

import java.util.ArrayList;
import java.util.List;
//import org.codehaus.jackson.annotate.JsonTypeInfo;
//import org.codehaus.jackson.annotate.JsonTypeInfo.As;
//import org.codehaus.jackson.annotate.JsonTypeInfo.Id;

/**
 *
 * @author User
 */
//@JsonTypeInfo(use=Id.NAME, include=As.WRAPPER_OBJECT)
public class SCLResponse{

  List<String> result;

  public SCLResponse(){
    this.result = new ArrayList<>();
  }

  public List<String> getResult(){
    return result;
  }

  public void setResult(List<String> result){
    this.result = result;
  }

}


<|start_filename|>knowledge-curation-layer/i-kat/src/main/java/org/uclab/mm/kcl/edkat/dao/RuleDAOImpl.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.kcl.edkat.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.uclab.mm.kcl.edkat.datamodel.Conclusion;
import org.uclab.mm.kcl.edkat.datamodel.Rule;

/**
* This is Data Access Object implementation class for the rule this DAO implements to 
* create, update, retrieve of rule with conditions, conclusions, and situations
 * @author  <NAME>
 * @version 1.0
 * @since   2015-08-16
 * */

@Repository
public class RuleDAOImpl implements RuleDAO {

	/**
	 * This creation of static object of logger for Rule 
	*/
	private static final Logger logger = LoggerFactory.getLogger(RuleDAOImpl.class);
	
	/**
	 * This creation of Session for factory  
	*/
	 private SessionFactory sessionFactory;
     
    public void setSessionFactory(SessionFactory sf){
        this.sessionFactory = sf;
    }
	    
    /**
	 * This function is the implementation for add new rule
	 * @param objRule
	 * @return Object of Rule
	*/
	public Rule addRule(Rule objRule) {
		try
		{
			Session session = this.sessionFactory.openSession();
	        Transaction tx = session.beginTransaction();
	        objRule = (Rule) session.merge(objRule);
	        tx.commit();
	        session.close();
	        logger.info("Rule saved successfully, Rule Details="+objRule);
	        return objRule;
		}
		catch(Exception ex)
		{
			logger.info("Error occured in saving new rule, Error Details="+ex.getMessage());
			return objRule;
		}
		
	}

	/**
	 * This function is the implementation for update existing rule
	 * @param objRule
	 * @return Object of Rule
	*/
	public Rule updateRule(Rule objRule) {
		try
		{
			Session session = this.sessionFactory.openSession();
	        Transaction tx = session.beginTransaction();
	        session.update(objRule); // Replaced with updated rule
	        tx.commit();
	        session.close();
	        logger.info("Rule updated successfully, Rule Details="+objRule);
	        return objRule;
		}
		catch(Exception ex)
		{
			logger.info("Error occured in updating rule, Error Details="+ex.getMessage());
			return objRule;
		}
		
	}
	
	/**
	 * This function is the implementation for deleting conclusion before deleting rules
	 * @param objRule
	 * @param objConclusion
	*/
	public void removeConclusion(Rule objRule, Conclusion objConclusion)
	{
		try
		{
			Session session = this.sessionFactory.openSession();
	        Transaction tx = session.beginTransaction();
	        objRule.getConclusionList().remove(objConclusion);
	        session.delete(objConclusion);
	        tx.commit();
	        logger.info("Conclusion deleted successfully, Rule Details="+objRule);
	        session.close();
		}
		catch(Exception ex)
		{
			logger.info("Error occured in deleting conclusion, Error Details="+ex.getMessage());
		}
		
	}

	/**
	 * This function is the implementation for retrieving all rules in form of list
	 * @return List of Rules
	*/
	@SuppressWarnings("unchecked")
	public List<Rule> listRule() {
		try
		{
			Session session = this.sessionFactory.openSession();
	        @SuppressWarnings("unchecked")
	        List<Rule> rulesList = session.createQuery("from Rule").list();
	        for(Rule objRule : rulesList){
	            logger.info("Rule List::"+objRule);
	        }
	        session.close();
	        return rulesList;
		}
		catch(Exception ex)
		{
			logger.info("Error occured in retieving rules list, Error Details="+ex.getMessage());
			return null;
		}
		
	}

	/**
	 * This function is the implementation for retrieving a single rule by id
	 * @param id
	 * @return Object of Rule
	*/
	public Rule getRuleById(int id) {
		try
		{
			Session session = this.sessionFactory.openSession();      
	        Rule objRule = (Rule) session.createQuery("from Rule r left outer join fetch r.conclusionList where r.RuleID=" + id).uniqueResult();
	        logger.info("Rule loaded successfully, Rule details="+objRule);
	        session.close();
	        return objRule;
		}
		catch(Exception  ex )
		{
			logger.info("Error occurred in rule loading "+ ex.getMessage());
			return null;
		}
	}

	/**
	 * This function is the implementation for deleting existing selected rule
	 * @param id
	*/
	public void removeRule(int id) {
		try
		{
			 Session session = this.sessionFactory.openSession();
			 Rule objRule = (Rule) session.load(Rule.class, new Integer(id));
		        if(null != objRule){
		            session.delete(objRule);
		        }
		        session.close();
		        logger.info("Rule deleted successfully, Rule details="+objRule);
		}
		catch(Exception  ex )
		{
			logger.info("Error occurred in rule deleting "+ ex.getMessage());
		}
		
	}

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/test/java/org/uclab/mm/datamodel/ic/dataadapter/testcases/UserRecognizedEmotionAdapterTest.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.ic.dataadapter.testcases;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.uclab.mm.datamodel.AbstractDataBridge;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.DatabaseStorage;
import org.uclab.mm.datamodel.ic.UserRecognizedEmotion;
import org.uclab.mm.datamodel.ic.dataadapter.UserRecognizedEmotionAdapter;

/**
 * This is a class for testing the insertion, fetching, and update of UserRecognizedEmotion
 * @author <NAME>
 *
 */
public class UserRecognizedEmotionAdapterTest {

	/**
	 * This is function for testing the insertion, fetching, and update of UserRecognizedEmotion 
	 */
	@Test
	public void test() {
		
		/* Preparing input object for insertion*/
		UserRecognizedEmotion objOuterUserRecognizedEmotion = new UserRecognizedEmotion();
		UserRecognizedEmotion objInnerUserRecognizedEmotion = new UserRecognizedEmotion();
		List<UserRecognizedEmotion> objListUserRecognizedEmotion = new  ArrayList<UserRecognizedEmotion>();
		
		objOuterUserRecognizedEmotion.setUserId(2L);
		objOuterUserRecognizedEmotion.setEmotionLabel("Happiness");
		objOuterUserRecognizedEmotion.setStartTime("2016 12 12 02:45:05");
	
		/* Testing of insertion function*/
		 DataAccessInterface objDAInterface = new UserRecognizedEmotionAdapter();
         AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
         List<String> lstResponse = objADBridge.SaveUserRecognizedEmotion(objOuterUserRecognizedEmotion);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerUserRecognizedEmotion.setUserId(2L);
        	 objInnerUserRecognizedEmotion.setRequestType("LatestByUser");
        	 DataAccessInterface objDAInterfaceRetrieval = new UserRecognizedEmotionAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListUserRecognizedEmotion = objADBridgeRetrieval.RetriveUserRecognizedEmotion(objInnerUserRecognizedEmotion);
        	 objInnerUserRecognizedEmotion = objListUserRecognizedEmotion.get(0);
         }
         
         assertEquals(objOuterUserRecognizedEmotion.getEmotionLabel(), objInnerUserRecognizedEmotion.getEmotionLabel());
	}

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/test/java/org/uclab/mm/datamodel/sl/dataadapter/testcases/ActivityFeedbackAdapterTest.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sl.dataadapter.testcases;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.uclab.mm.datamodel.AbstractDataBridge;
import org.uclab.mm.datamodel.DataAccessInterface;

import org.uclab.mm.datamodel.DatabaseStorage;
import org.uclab.mm.datamodel.sl.ActivityFeedback;
import org.uclab.mm.datamodel.sl.dataadapter.ActivityFeedbackAdapter;
/**
 * This is a class for testing the insertion, fetching, and update of ActivityFeedback
 * @author <NAME>
 *
 */
public class ActivityFeedbackAdapterTest {

	/**
	 * This is function for testing the insertion, fetching, and update of ActivityFeedback 
	 */
	@Test
	public void test() {
		/* Preparing input object for insertion*/
		ActivityFeedback objOuterActivityFeedback = new ActivityFeedback();
		ActivityFeedback objInnerActivityFeedback = new ActivityFeedback();
		List<ActivityFeedback> objListActivityFeedback = new  ArrayList<ActivityFeedback>();
		
		objOuterActivityFeedback.setUserID(2L);
		objOuterActivityFeedback.setRecognizedActivityID(98866L);
		objOuterActivityFeedback.setRate(3);
		objOuterActivityFeedback.setReason("I like it, unit testing");
		objOuterActivityFeedback.setFeedbackDate("2016 12 12 02:30:01");
	
		/* Testing of insertion function*/
		 DataAccessInterface objDAInterface = new ActivityFeedbackAdapter();
         AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
         List<String> lstResponse = objADBridge.SaveActivityFeedback(objOuterActivityFeedback);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerActivityFeedback.setUserID(2L);
        	 objInnerActivityFeedback.setRequestType("ByUserID");
        	 DataAccessInterface objDAInterfaceRetrieval = new ActivityFeedbackAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListActivityFeedback = objADBridgeRetrieval.RetriveActivityFeedback(objInnerActivityFeedback);
        	 objInnerActivityFeedback = objListActivityFeedback.get(0);
         }
         
         assertEquals(objOuterActivityFeedback.getReason(), objInnerActivityFeedback.getReason());
         
         /* Testing of Update function*/
         objInnerActivityFeedback.setReason("I like it, unit testing updated");
         objInnerActivityFeedback.setFeedbackDate("2016 12 12 02:30:01");
         DataAccessInterface objDAInterfaceUpdate = new ActivityFeedbackAdapter();
         AbstractDataBridge objADBridgeUpdate = new DatabaseStorage(objDAInterfaceUpdate);
         lstResponse = objADBridgeUpdate.UpdateActivityFeedback(objInnerActivityFeedback);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerActivityFeedback.setUserID(2L);
        	 objInnerActivityFeedback.setRequestType("ByUserID");
        	 DataAccessInterface objDAInterfaceRetrieval = new ActivityFeedbackAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListActivityFeedback = objADBridgeRetrieval.RetriveActivityFeedback(objInnerActivityFeedback);
        	 objInnerActivityFeedback = objListActivityFeedback.get(0);
         }
         
         assertEquals(objInnerActivityFeedback.getReason(), "I like it, unit testing updated");
	}

}


<|start_filename|>data-curation-layer/data-persistence/sendHDFS.js.html<|end_filename|>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JSDoc: Source: sendHDFS.js</title>

    <script src="scripts/prettify/prettify.js"> </script>
    <script src="scripts/prettify/lang-css.js"> </script>
    <!--[if lt IE 9]>
      <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>

<body>

<div id="main">

    <h1 class="page-title">Source: sendHDFS.js</h1>

    



    
    <section>
        <article>
            <pre class="prettyprint source linenums"><code>
/**
 * @author <NAME>
 * @since 2016.11.21
 * @version 0.1

 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at

 *   http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


/**
 * @description Send the data to HDFS using by HTTP.
 * @description "webhdfs-client.js" file has information about HDFS(host, user, port...).
 * @module sendHDFS
 * @param {number} - metadata for HDFS file name.
 */

var config = require('./config.json');
var localFilePath = config.filePath_local;
var HDFSFilePath = config.filePath_HDFS;

exports.wc = function(cnt){

var hdfs = require('../webhdfs-client');
var fs = require('fs');

var filepath =  + cnt;
var localFileStream = fs.createReadStream('./temp.txt');
var remoteFileStream = hdfs.createWriteStream('/kjh/'+cnt);
console.log("File write in " + filepath);

// Pipe data to HDFS
localFileStream.pipe(remoteFileStream);

// Handle errors
remoteFileStream.on('error', function onError (err) {
});
console.log("data is stored in HDFS");

};

</code></pre>
        </article>
    </section>




</div>

<nav>
    <h2><a href="index.html">Home</a></h2><h3>Modules</h3><ul><li><a href="module-sendHDFS.html">sendHDFS</a></li></ul>
</nav>

<br class="clear">

<footer>
    Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.4.3</a> on Sat Dec 24 2016 10:13:40 GMT+0900 (KST)
</footer>

<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/outputModel/InterpretationModel/PhyActivityExplaination.java<|end_filename|>
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.uclab.scl.outputModel.InterpretationModel;

/**
 * 
 * @author User
 */
public class PhyActivityExplaination {

  private String factCategoryDescription;

  private long recommendationExplanationID;

  private String factExplanation;

  private String recommendationID;

  private int factCategoryID;

  public String getFactCategoryDescription() {
    return factCategoryDescription;
  }

  public void setFactCategoryDescription(String factCategoryDescription) {
    this.factCategoryDescription = factCategoryDescription;
  }

  public long getRecommendationExplanationID() {
    return recommendationExplanationID;
  }

  public void setRecommendationExplanationID(long recommendationExplanationID) {
    this.recommendationExplanationID = recommendationExplanationID;
  }

  public String getFactExplanation() {
    return factExplanation;
  }

  public void setFactExplanation(String factExplanation) {
    this.factExplanation = factExplanation;
  }

  public String getRecommendationID() {
    return recommendationID;
  }

  public void setRecommendationID(String recommendationID) {
    this.recommendationID = recommendationID;
  }

  public int getFactCategoryID() {
    return factCategoryID;
  }

  public void setFactCategoryID(int factCategoryID) {
    this.factCategoryID = factCategoryID;
  }

  @Override
  public String toString() {
    return "ClassPojo [factCategoryDescription = " + factCategoryDescription
        + ", recommendationExplanationID = " + recommendationExplanationID
        + ", factExplanation = " + factExplanation + ", recommendationID = "
        + recommendationID + ", factCategoryID = " + factCategoryID + "]";
  }

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/ic/dataadapter/UserGPSDataDataAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.ic.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.ic.UserGPSData;

/**
 * This is UserGPSDataDataAdapter class which implements the Data Access Interface for CRUD operations
 * @author Taqdir
 */
public class UserGPSDataDataAdapter implements DataAccessInterface {

     private Connection objConn;
     private static final Logger logger = LoggerFactory.getLogger(UserGPSDataDataAdapter.class);
    public UserGPSDataDataAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving UserGPSData. 
     * @param objUserGPSData
     * @return List of String
     */
    @Override
    public List<String> Save(Object objUserGPSData) {
        UserGPSData objInnerUserGPSData = new UserGPSData();
        objInnerUserGPSData =  (UserGPSData) objUserGPSData;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_UserGPSData(?, ?, ?, ?, ?, ?)}");
            List<Float> arrLatitude = objInnerUserGPSData.getLatitude();
            List<Float> arrLongitude = objInnerUserGPSData.getLongitude();
            List<Float> arrSpeed = objInnerUserGPSData.getSpeed();
            for(int i = 0; i < objInnerUserGPSData.getLatitude().size(); i++)
            {
                objCallableStatement.setLong("UserDeviceID", objInnerUserGPSData.getUserDeviceId());
                objCallableStatement.setFloat("Latitude", arrLatitude.get(i));
                objCallableStatement.setFloat("Longitude", arrLongitude.get(i));
                objCallableStatement.setFloat("Speed", arrSpeed.get(i));
                
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss");	
                Date dttimestamp =  sdf.parse(objInnerUserGPSData.getTimeStamp());
                Timestamp tstimestamp = new Timestamp(dttimestamp.getYear(),dttimestamp.getMonth(), dttimestamp.getDate(), dttimestamp.getHours(), dttimestamp.getMinutes(), dttimestamp.getSeconds(), 00);
                objCallableStatement.setTimestamp("timestamp", tstimestamp);

                objCallableStatement.registerOutParameter("UserGPSDataID", Types.BIGINT);
                objCallableStatement.execute();
            }
            
            
            Long intUserGPSDataID = objCallableStatement.getLong("UserGPSDataID");
            objDbResponse.add(String.valueOf(intUserGPSDataID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("User GPS Data added successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in adding User GPS Data");
        	objDbResponse.add("Error in adding User GPS Data");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for updating UserGPSData. 
     * @param objUserGPSData
     * @return List of String
     */
    @Override
    public List<String> Update(Object objUserGPSData) {
        UserGPSData objInnerUserGPSData = new UserGPSData();
        objInnerUserGPSData =  (UserGPSData) objUserGPSData;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_UserGPSData(?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserGPSDataID", objInnerUserGPSData.getUserGPSDataId());
            objCallableStatement.setLong("UserDeviceID", objInnerUserGPSData.getUserDeviceId());
            objCallableStatement.execute();
            
            objDbResponse.add(String.valueOf(objInnerUserGPSData.getUserGPSDataId()));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("User GPS Data updated successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in updating User GPS Data");
        	objDbResponse.add("Error in updating User GPS Data");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for retrieving UserGPSData. 
     * @param objUserGPSData
     * @return List of UserGPSData
     */
    @Override
    public List<UserGPSData> RetriveData(Object objUserGPSData) {
        UserGPSData objOuterUserGPSData = new UserGPSData();
        List<UserGPSData> objListInnerUserGPSData = new ArrayList<UserGPSData>();
        objOuterUserGPSData =  (UserGPSData) objUserGPSData;
        
        try
        {
            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UserGPSDataByUserID(?, ?, ?)}");
            objCallableStatement.setLong("UserDeviceID", objOuterUserGPSData.getUserDeviceId());
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
            
            Date dtStartTimeStamp = sdf.parse(objOuterUserGPSData.getTimeStamp());
            Timestamp tsStartTimeStamp = new Timestamp(dtStartTimeStamp.getYear(),dtStartTimeStamp.getMonth(), dtStartTimeStamp.getDate(), dtStartTimeStamp.getHours(), dtStartTimeStamp.getMinutes(), dtStartTimeStamp.getSeconds(), 00);
            objCallableStatement.setTimestamp("StartTimeStamp", tsStartTimeStamp);
                
            Date dtEndTimeStamp = sdf.parse(objOuterUserGPSData.getTimeStamp());
            Timestamp tsEndTimeStamp = new Timestamp(dtEndTimeStamp.getYear(),dtEndTimeStamp.getMonth(), dtEndTimeStamp.getDate(), dtEndTimeStamp.getHours(), dtEndTimeStamp.getMinutes(), dtEndTimeStamp.getSeconds(), 00);
            objCallableStatement.setTimestamp("EndTimeStamp", tsEndTimeStamp);

            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                UserGPSData objInnerUserGPSData = new UserGPSData();
                objInnerUserGPSData.setUserGPSDataId(objResultSet.getLong("UserGPSDataID"));
                objInnerUserGPSData.setUserDeviceId(objResultSet.getLong("UserDeviceID"));
                Timestamp tstimestamp = objResultSet.getTimestamp("timestamp"); //updated
                objInnerUserGPSData.setTimeStamp(tstimestamp.toString());
                
                objListInnerUserGPSData.add(objInnerUserGPSData);
            }
            objConn.close();
            logger.info("User GPS Data loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading User GPS Data");
        }   
        return objListInnerUserGPSData;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>data-curation-layer/active-data-reader/src/test/java/org/uclab/mm/dcl/adr/test/HiveServiceTest.java<|end_filename|>
/*
 * Copyright (C) 2016 <NAME>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.uclab.mm.dcl.adr.test;

import static com.jayway.restassured.RestAssured.given;

import org.junit.BeforeClass;
import org.junit.Test;

import com.jayway.restassured.RestAssured;

public class HiveServiceTest {

	// Test the Service is up and Running.
	@Test
	public void makeSureThatServiceIsUp() {
		given().when().get("http://localhost:8080/analytics/").then().statusCode(200);
	}

	// Test the Port is working or Not to communicate with the Hive Server.
	@BeforeClass
	public static void setup() {
		String port = System.getProperty("server.port");
		if (port == null) {
			RestAssured.port = Integer.valueOf(8080);
		} else {
			RestAssured.port = Integer.valueOf(port);
		}

		String basePath = System.getProperty("server.base");
		if (basePath == null) {
			basePath = "/analytics/";
		}
		RestAssured.basePath = basePath;

		String baseHost = System.getProperty("server.host");
		if (baseHost == null) {
			baseHost = "http://localhost";
		}
		RestAssured.baseURI = baseHost;

	}

}

<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sl/dataadapter/UserGPSDataVisulizationAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sl.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.ic.UserGPSData;
import org.uclab.mm.datamodel.sl.UserGPSDataVisulization;

/**
 * This is UserGPSDataVisulizationAdapter class which implements the Data Access Interface for CRUD operations
 * @author dcadmin
 */
public class UserGPSDataVisulizationAdapter implements DataAccessInterface {
    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(UserGPSDataVisulizationAdapter.class);
    public UserGPSDataVisulizationAdapter()
    {
        
    }

    /**
     * This is implementation function for saving UserGPSDataVisulizationAdapter. 
     *Not Implemented
     */
    @Override
    public <T> List<String> Save(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for Update UserGPSDataVisulizationAdapter. 
     *Not Implemented
     */
    @Override
    public <T> List<String> Update(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet."); 
    }

    /**
     * This is implementation function for retrieving UserGPSDataVisulization. 
     * @param objUserGPSData
    * @return List of UserGPSDataVisulization
     */
    @Override
    public List<UserGPSDataVisulization> RetriveData(Object objUserGPSData) {
        UserGPSDataVisulization objOuterUserGPSData = new UserGPSDataVisulization();
        List<UserGPSDataVisulization> objListInnerUserGPSData = new ArrayList<UserGPSDataVisulization>();
        objOuterUserGPSData =  (UserGPSDataVisulization) objUserGPSData;
        
        try
        {
            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UserGPSDataForVisualization(?, ?)}");
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
            
            Date dtStartTimeStamp = sdf.parse(objOuterUserGPSData.getTimeStampStart());
            Timestamp tsStartTimeStamp = new Timestamp(dtStartTimeStamp.getYear(),dtStartTimeStamp.getMonth(), dtStartTimeStamp.getDate(), dtStartTimeStamp.getHours(), dtStartTimeStamp.getMinutes(), dtStartTimeStamp.getSeconds(), 00);
            objCallableStatement.setTimestamp("StartTimeStamp", tsStartTimeStamp);
                
            Date dtEndTimeStamp = sdf.parse(objOuterUserGPSData.getTimeStampEnd());
            Timestamp tsEndTimeStamp = new Timestamp(dtEndTimeStamp.getYear(),dtEndTimeStamp.getMonth(), dtEndTimeStamp.getDate(), dtEndTimeStamp.getHours(), dtEndTimeStamp.getMinutes(), dtEndTimeStamp.getSeconds(), 00);
            objCallableStatement.setTimestamp("EndTimeStamp", tsEndTimeStamp);

            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                UserGPSDataVisulization objInnerUserGPSData = new UserGPSDataVisulization();
                objInnerUserGPSData.setUserGPSDataId(objResultSet.getLong("UserGPSDataID"));
                objInnerUserGPSData.setUserDeviceId(objResultSet.getLong("UserDeviceID"));
                objInnerUserGPSData.setLatitude(objResultSet.getFloat("Latitude"));
                objInnerUserGPSData.setLongitude(objResultSet.getFloat("Longitude"));
                objInnerUserGPSData.setSpeed(objResultSet.getFloat("Speed"));
                
                Timestamp tstimestamp = objResultSet.getTimestamp("timestamp"); //updated
                objInnerUserGPSData.setTimeStamp(tstimestamp.toString());
                
                objListInnerUserGPSData.add(objInnerUserGPSData);
            }
            objConn.close();
            logger.info("User GPS Data Visulization loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading User GPS Data Visulization");
        }   
        return objListInnerUserGPSData;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/dataadapter/RecommendationExceptionAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.sc.Recommendation;
import org.uclab.mm.datamodel.sc.RecommendationException;

/**
 * This is RecommendationExceptionAdapter class which implements the Data Access Interface for CRUD operations
 * @author <NAME>
 */
public class RecommendationExceptionAdapter implements DataAccessInterface {

    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(RecommendationExceptionAdapter.class);
    public RecommendationExceptionAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving RecommendationException.
     * @param objRecommendationException
     * @return List of String 
     */
    @Override
    public List<String> Save(Object objRecommendationException) {
        RecommendationException objInnerRecommendationException = new RecommendationException();
        objInnerRecommendationException =  (RecommendationException) objRecommendationException;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_RecommendationException(?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("RecommendationID", objInnerRecommendationException.getRecommendationID());
            objCallableStatement.setString("Exception", objInnerRecommendationException.getException());
            objCallableStatement.setString("CustomRule", objInnerRecommendationException.getCustomRule());
            objCallableStatement.setString("ExceptionReason", objInnerRecommendationException.getExceptionReason());
            
            objCallableStatement.registerOutParameter("RecommendationExceptionID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intRecommendationExceptionID = objCallableStatement.getLong("RecommendationExceptionID");
            objDbResponse.add(String.valueOf(intRecommendationExceptionID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("RecommendationException saved successfully, RecommendationException Details="+objRecommendationException);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding RecommendationException");
        	objDbResponse.add("Error in adding RecommendationException");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for updating RecommendationException.
     * @param objRecommendationException
     * @return List of RecommendationException 
     */
    @Override
    public List<String> Update(Object objRecommendationException) {
        
        RecommendationException objInnerRecommendationException = new RecommendationException();
        objInnerRecommendationException =  (RecommendationException) objRecommendationException;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_RecommendationException(?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("RecommendationExceptionID", objInnerRecommendationException.getRecommendationExceptionID());
            objCallableStatement.setLong("RecommendationID", objInnerRecommendationException.getRecommendationID());
            objCallableStatement.setString("Exception", objInnerRecommendationException.getException());
            objCallableStatement.setString("CustomRule", objInnerRecommendationException.getCustomRule());
            objCallableStatement.setString("ExceptionReason", objInnerRecommendationException.getExceptionReason());
            
            objCallableStatement.execute();
            
            Long intRecommendationExceptionID = objInnerRecommendationException.getRecommendationExceptionID();
            objDbResponse.add(String.valueOf(intRecommendationExceptionID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("RecommendationException updated successfully, RecommendationException Details="+objRecommendationException);
        }
        catch (Exception e)
        {
        	logger.info("Error in updating RecommendationException");
        	objDbResponse.add("Error in updating RecommendationException");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for retrieving RecommendationException.
     * @param objRecommendationException
     * @return List of RecommendationException 
     */
    @Override
    public List<RecommendationException> RetriveData(Object objRecommendationException) {
        RecommendationException objOuterRecommendationException = new RecommendationException();
        List<RecommendationException> objListInnerRecommendationException = new ArrayList<RecommendationException>();
        objOuterRecommendationException =  (RecommendationException) objRecommendationException;
        
        try
        {
            CallableStatement objCallableStatement = null;
            objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_RecommendationExceptionByRecommendationID(?)}");
                
            objCallableStatement.setLong("RecommendationID", objOuterRecommendationException.getRecommendationID());
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                RecommendationException objInnerRecommendationException = new RecommendationException();
                
                objInnerRecommendationException.setRecommendationExceptionID(objResultSet.getLong("RecommendationExceptionID"));
                objInnerRecommendationException.setRecommendationID(objResultSet.getLong("RecommendationID"));
                objInnerRecommendationException.setException(objResultSet.getString("Exception"));
                objInnerRecommendationException.setCustomRule(objResultSet.getString("CustomRule"));
                objInnerRecommendationException.setExceptionReason(objResultSet.getString("ExceptionReason"));
                
                objListInnerRecommendationException.add(objInnerRecommendationException);
            }
            objConn.close();
            logger.info("Recommendation Exception loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading Recommendation Exception");
        }   
        return objListInnerRecommendationException;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf 
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/Utilities/AgeGroupUtility.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.Utilities;

import java.util.Date;

public class AgeGroupUtility {
  public static enum AgeGroupEnum {
    Adult, Silver_Age, Older_Adult, Young_Adult
  }
  
  private AgeGroupEnum ageGroup;
  private AgeGroupUtility(){}
  
  public static AgeGroupUtility getAgeGroupUtility(){
    return AgeGroupUtilityHolder.INSTANCE;
  }
  
  public AgeGroupEnum getAgeGroup(Date dob) {

    Date today = new Date(); // current date
    int age = today.getYear() - dob.getYear();// .get(Calendar.YEAR);

    if (today.getMonth() < dob.getMonth()) {
      age--;
    } else if (today.getMonth() == dob.getMonth()
        && (today.getDate() < dob.getDate())) {
      age--;
    }

    if (age >= 19 && age <= 45)
      ageGroup = AgeGroupEnum.Adult;
    else if (age > 45)
      ageGroup = AgeGroupEnum.Older_Adult;
    else if (age < 20)
      ageGroup = AgeGroupEnum.Young_Adult;

    return ageGroup;
  }
  
  public String GenderConversion(int gender) {
    if (gender == 1)
      return "Male";
    else if (gender == 2)
      return "Female";
    else
      return "Unknown";
  }
  
  public void setgetAgeGroup(AgeGroupEnum ageGroup){
    this.ageGroup = ageGroup;
  }
  
  private static class AgeGroupUtilityHolder{
    private static final AgeGroupUtility INSTANCE = new AgeGroupUtility();
  }
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/AER/vui/AERFeatureExtraction.java<|end_filename|>
/*
Copyright [2016] [Vui]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.AER.vui;

import java.util.Arrays;

import org.uclab.mm.icl.llc.MachineLearningTools.FeatureExtraction;

import mm.icl.llc.MachineLearningTools.FeatureExtractions.AudioFeatureExtraction;
import mm.icl.llc.MachineLearningTools.FeatureExtractions.StatisticalFunctions;
import mm.icl.llc.MachineLearningTools.FeatureExtractions.TemporalFeatureExtraction;
import mm.icl.llc.MachineLearningTools.Utilities.UtilityFunctions;

public class AERFeatureExtraction extends FeatureExtraction<double[], double[]> {
	private double samplingRate;
	
	private boolean hasIndex;
	private int labelIndex;
	
	/**
	 * 
	 */
	public AERFeatureExtraction() {
		this.hasIndex = false;
		this.labelIndex = -1;
		this.samplingRate = 8000;
	}
	
	/**
	 * 
	 * @param labelIndex
	 */
	public AERFeatureExtraction(int labelIndex) {
		if (labelIndex > -1)
			this.hasIndex = true;
		else
			this.hasIndex = false;
		
		this.labelIndex = labelIndex;
		this.samplingRate = 8000;
	}
	
	/**
	 * 
	 */
	public double[] extractFeature(double[] samples) {
		// 1. Split frames
		double[][] frames = splitFrames(samples);
		
		int numFrames = frames.length;
		int numFeatures = 14;
		
		double[][] matrix = new double[numFrames][numFeatures];
		
		// 2. Extract features
		// a. MFCC
		// b. Zero Crossing
		// c. Power Spectrum 
		// d. Concatenate into 1 vector
		
		for (int i = 0; i < numFrames; i++) {
			double[] frame = frames[i];
			double[] mfcc = AudioFeatureExtraction.extractMFCC(frame, samplingRate);
			double[] zeroCrossing = TemporalFeatureExtraction.extractZeroCrossings(samples, samplingRate);
			
			System.arraycopy(mfcc, 0, matrix[i], 0, mfcc.length);
			System.arraycopy(zeroCrossing, 0, matrix[i], mfcc.length, zeroCrossing.length);
		}
		
		// 3. Compute Delta
		double[][] matrixDelta = computeDelta(matrix); // 14 * 2 = 28 features
		
		// 4. Compute Mean, Standard Deviation, Skewness, Kurtosis
		double[] mean = StatisticalFunctions.computeMean2D(matrixDelta);
		double[] std = StatisticalFunctions.computeStd2D(matrixDelta, mean);
		// double[] skewness = StatisticalFunctions.computeSkewness2D(matrix, mean, std);
		// double[] kurtosis = StatisticalFunctions.computeKurtosis2D(matrix, mean, std);
		
		// Total features 28 * 2 = 54 features
		
		// Concatenate all features to a vector
		double[] features = UtilityFunctions.concat(mean, std);
		
		if (hasIndex) {
			features  = Arrays.copyOf(features, features.length + 1);
			features[features.length - 1] = labelIndex;
		}
		
		return features;
	}
	
	/**
	 * 
	 * @param samplingRate
	 */
	public void setSamplingRate(double samplingRate) {
		this.samplingRate = samplingRate;
	}
	
	/**
	 * @param samples
	 * @return
	 */
	protected double[][] splitFrames(double[] samples) {
		// Window Size: 100 ms
		// Overlap 50ms
		int windowSizeInMs = 200;
		int overlapInMs = 50;
		
		int windowSize = (int)(windowSizeInMs * samplingRate / 1000);
		int overlap = (int)(overlapInMs * samplingRate / 1000);
		
		int numFrames = (int)Math.ceil(samples.length / (windowSize - overlap));
		
		double[][] frames = new double[numFrames][windowSize];
		
		for (int i = 0; i < numFrames; i++)
			for (int j = 0; j < windowSize; j++)
				if (i * (windowSize - overlap) + j < samples.length)
					frames[i][j] = samples[i * (windowSize - overlap) + j];
				else
					frames[i][j] = 0;
		
		return frames;
	}
	
	/**
	 * @param matrix
	 * @return
	 */
	protected double[][] computeDelta(double[][] matrix) {
		int numFeatures = matrix[0].length;
		int numFrames = matrix.length;
		
		double[][] newMatrix = new double[numFrames][numFeatures * 2];
		
		for (int i = 0; i < numFeatures * 2; i++)
			for (int j = 0; j < numFrames; j++)
				newMatrix[j][i] = 0;
		
		for (int i = 0; i < numFeatures; i++)
			for (int j = 0; j < numFrames; j++)
				newMatrix[j][i] = matrix[j][i];
		
		for (int i = 0; i < numFeatures; i++)
			for (int j = 0; j < numFrames - 1; j++)
					newMatrix[j][numFeatures + i] = matrix[j+1][i] - matrix[j][i];
		
		return newMatrix;
	}
	
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/ic/UserRecognizedActivityAccumulate.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.ic;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author <NAME>
 */
@Entity
public class UserRecognizedActivityAccumulate implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private Long userRecognizedActivityAccumulateID;
    private Long userId;
    private int activityId;
    private String activityDate;
    private int duration;
    
    private String activityDescription;
    private String startTime;
    private String endTime;
    private String requestType;
    private String activityIDs;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof UserRecognizedActivityAccumulate)) {
            return false;
        }
        UserRecognizedActivityAccumulate other = (UserRecognizedActivityAccumulate) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.ic.UserRecognizedActivityAccumulate[ id=" + id + " ]";
    }

    /**
     * @return the userRecognizedActivityAccumulateID
     */
    public Long getUserRecognizedActivityAccumulateID() {
        return userRecognizedActivityAccumulateID;
    }

    /**
     * @param userRecognizedActivityAccumulateID the userRecognizedActivityAccumulateID to set
     */
    public void setUserRecognizedActivityAccumulateID(Long userRecognizedActivityAccumulateID) {
        this.userRecognizedActivityAccumulateID = userRecognizedActivityAccumulateID;
    }

    /**
     * @return the userId
     */
    public Long getUserId() {
        return userId;
    }

    /**
     * @param userId the userId to set
     */
    public void setUserId(Long userId) {
        this.userId = userId;
    }

    /**
     * @return the activityId
     */
    public int getActivityId() {
        return activityId;
    }

    /**
     * @param activityId the activityId to set
     */
    public void setActivityId(int activityId) {
        this.activityId = activityId;
    }

    /**
     * @return the activityDate
     */
    public String getActivityDate() {
        return activityDate;
    }

    /**
     * @param activityDate the activityDate to set
     */
    public void setActivityDate(String activityDate) {
        this.activityDate = activityDate;
    }

    /**
     * @return the duration
     */
    public int getDuration() {
        return duration;
    }

    /**
     * @param duration the duration to set
     */
    public void setDuration(int duration) {
        this.duration = duration;
    }

    /**
     * @return the activityDescription
     */
    public String getActivityDescription() {
        return activityDescription;
    }

    /**
     * @param activityDescription the activityDescription to set
     */
    public void setActivityDescription(String activityDescription) {
        this.activityDescription = activityDescription;
    }

    /**
     * @return the startTime
     */
    public String getStartTime() {
        return startTime;
    }

    /**
     * @param startTime the startTime to set
     */
    public void setStartTime(String startTime) {
        this.startTime = startTime;
    }

    /**
     * @return the endTime
     */
    public String getEndTime() {
        return endTime;
    }

    /**
     * @param endTime the endTime to set
     */
    public void setEndTime(String endTime) {
        this.endTime = endTime;
    }

    /**
     * @return the requestType
     */
    public String getRequestType() {
        return requestType;
    }

    /**
     * @param requestType the requestType to set
     */
    public void setRequestType(String requestType) {
        this.requestType = requestType;
    }

    /**
     * @return the activityIDs
     */
    public String getActivityIDs() {
        return activityIDs;
    }

    /**
     * @param activityIDs the activityIDs to set
     */
    public void setActivityIDs(String activityIDs) {
        this.activityIDs = activityIDs;
    }
    
}


<|start_filename|>knowledge-curation-layer/DDKAT/src/main/java/org/uclab/mm/kcl/ddkat/productionmodel/Conclusion.java<|end_filename|>
/**
 * Copyright [2017] [<NAME>, <NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.mm.kcl.ddkat.productionmodel;

import java.io.Serializable;

//TODO: Auto-generated Javadoc
/**
* This class defines the model/structure of the conclusions.
*/
public class Conclusion implements Serializable{

	private static final long serialVersionUID = 1L;

	/** The conclusion id. */
	private int ConclusionID;
	
	/** The conclusion key. */
	private String conclusionKey;
	
	/** The conclusion value. */
	private String conclusionValue;
	
	/** The conclusion operator. */
	private String conclusionOperator;
	
	public Conclusion()  
	 {  
	 }    

	public int getConclusionID() {
		return ConclusionID;
	}

	public void setConclusionID(int conclusionID) {
		ConclusionID = conclusionID;
	}	

	public String getConclusionKey() {
		return conclusionKey;
	}

	public void setConclusionKey(String conclusionKey) {
		this.conclusionKey = conclusionKey;
	}

	public String getConclusionValue() {
		return conclusionValue;
	}

	public void setConclusionValue(String conclusionValue) {
		this.conclusionValue = conclusionValue;
	}

	public String getConclusionOperator() {
		return conclusionOperator;
	}

	public void setConclusionOperator(String conclusionOperator) {
		this.conclusionOperator = conclusionOperator;
	}
	
}



<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/OntologyTools/HLCA.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.OntologyTools;
/**
 * Vocabulary definitions for HLCA in Mining Minds v2.0. Concepts of the Context
 * Ontology which represents the Mining Minds Context Model.
 * 
 * @author <NAME> and <NAME>
 * @version 2.5
 * @since 2015-10-28
 */
public class HLCA {
	/**
	 * Namespace of the Context Ontology.
	 */
	public static final String ns = "http://www.miningminds.re.kr/icl/context/context-v3.owl#";//context-v2-5 context-v3-0
	/**
	 * Prefix for the namespace of the Context Ontology.
	 */
	public static final String nsPrefix = "icl3";
	/**
	 * Name of the PhysicalActivity and Nutrition Context class in the Context Ontology.
	 */
	public static final String hlcClassName = ns + "HighLevelContext";
	/**
	 * Name of the User class in the Context Ontology.
	 */
	public static final String userClassName = ns + "User";
	/**
	 * Name of the property in the Context Ontology which links a Context to the
	 * User it belongs to.
	 */
	public static final String isCtxOfPropName = ns + "isContextOf";
	/**
	 * Name of the property in the Context Ontology which links a Context to its
	 * start time.
	 */
	public static final String hasStartTimePropName = ns + "hasStartTime";
	/**
	 * Name of the property in the Context Ontology which links a Context to its
	 * end time.
	 */
	public static final String hasEndTimePropName = ns + "hasEndTime";
	/**
	 * Name of the Low Level Context class in the Context Ontology.
	 */
	public static final String llcClassName = ns + "LowLevelContext";
	/**
	 * Name of the property in the Context Ontology which links a PhysicalActivity and Nutrition
	 * Context to the Activity which is part of it.
	 */
	public static final String hasActivityPropName = ns + "hasActivity";
	/**
	 * Name of the property in the Context Ontology which links a PhysicalActivity and Nutrition
	 * Context to the Emotion which is part of it.
	 */
	public static final String hasEmotionPropName = ns + "hasEmotion";
	/**
	 * Name of the property in the Context Ontology which links a PhysicalActivity and Nutrition
	 * Context to the Location which is part of it.
	 */
	public static final String hasLocationPropName = ns + "hasLocation";
	/**                    Asif
	 * Name of the property in the Context Ontology which links a PhysicalActivity and Nutrition
	 * Context to the Location which is part of it.
	 */
	public static final String hasFoodPropName = ns + "hasFood";
	/**                    Asif
	 * Name of the property in the Context Ontology which links a PhysicalActivity and Nutrition
	 * Context to the BloodGlucose which is part of it.
	 */
	public static final String hasBloodGlucosePropName = ns + "hasBloodGlucose";    
	/**                    Asif
	 * Name of the property in the Context Ontology which links a PhysicalActivity and Nutrition
	 * Context to the Location which is part of it.
	 */
	public static final String hasBloodPressurePropName = ns + "hasBloodPressure";    
	/**                    Asif
	 * Name of the property in the Context Ontology which links a PhysicalActivity and Nutrition
	 * Context to the Location which is part of it.
	 */
	public static final String hasWaterIntakePropName = ns + "hasWaterIntake";    

	/**
	 * Name of the Activity class in the Context Ontology.
	 */
	public static final String activityClassName = ns + "Activity";
	/**
	 * Name of the Emotion class in the Context Ontology.
	 */
	public static final String emotionClassName = ns + "Emotion";
	/**
	 * Name of the Location class in the Context Ontology.
	 */
	public static final String locationClassName = ns + "Location";
	/**
	 * Name of the Food class in the Context Ontology.        Asif
	 */
	public static final String foodClassName = ns + "Food";
	/**
	 * Name of the Food class in the Context Ontology.        Asif
	 */
	public static final String BloodGlucoseClassName = ns + "BloodGlucose";
	/**
	 * Name of the Food class in the Context Ontology.        Asif
	 */
	public static final String BloodPressureClassName = ns + "BloodPressure";
	/**
	 * Name of the Food class in the Context Ontology.        Asif
	 */
	public static final String WaterIntakeClassName = ns + "WaterIntake";
	
	/**
	 * Name used to represent the Unidentified PhysicalActivity and Nutrition Context. Please note
	 * that this concept is only used by the HLC Notifier but it is not part of
	 * the Context Ontology. This is done in this way in order to ensure the
	 * Context Ontology extensibility.
	 */
	public static final String unidentifiedHlc = ns + "UnidentifiedHLC";
	/**
	 * Name used to represent the lack of information for the Low Level Context
	 * type Activity. Please note that this concept is only used by the Context
	 * Mapper but it is not part of the Context Ontology.
	 */
	public static final String noActivity = "NoActivity";
	/**
	 * Name used to represent the lack of information for the Low Level Context
	 * type Emotion. Please note that this concept is only used by the Context
	 * Mapper but it is not part of the Context Ontology.
	 */
	public static final String noEmotion = "NoEmotion";
	/**
	 * Name used to represent the lack of information for the Low Level Context
	 * type Location. Please note that this concept is only used by the Context
	 * Mapper but it is not part of the Context Ontology.
	 */
	public static final String noLocation = "NoLocation";
	/**  Asif
	 * Name used to represent the lack of information for the Low Level Context
	 * type Food. Please note that this concept is only used by the Context
	 * Mapper but it is not part of the Context Ontology.
	 */
	public static final String noFood= "NoFood";
	/**  Asif
	 * Name used to represent the lack of information for the Low Level Context
	 * type Food. Please note that this concept is only used by the Context
	 * Mapper but it is not part of the Context Ontology.
	 */
	public static final String noBloodGlucose= "NoBloodGlucose";
	/**  Asif
	 * Name used to represent the lack of information for the Low Level Context
	 * type Food. Please note that this concept is only used by the Context
	 * Mapper but it is not part of the Context Ontology.
	 */
	public static final String noBloodPressure= "NoBloodPressure";
	/**  Asif
	 * Name used to represent the lack of information for the Low Level Context
	 * type Food. Please note that this concept is only used by the Context
	 * Mapper but it is not part of the Context Ontology.
	 */
	public static final String noWaterIntake= "NoWaterIntake";
	/**
	 * Name of the variable used in the SPARQL queries to refer to a PhysicalActivity and Nutrition
	 * Context.
	 */
	public static final String hlcSparqlVar = "hlc";
	/**
	 * Name of the variable used in the SPARQL queries to refer to a User.
	 */
	public static final String userSparqlVar = "user";
	/**
	 * Name of the variable used in the SPARQL queries to refer to a start time
	 * value.
	 */
	public static final String startTimeSparqlVar = "starttime";
	/**
	 * Name of the variable used in the SPARQL queries to refer to an end time
	 * value
	 */
	public static final String endTimeSparqlVar = "endtime";
	/**
	 * Name of the variable used in the SPARQL queries to refer to a Low Level
	 * Context.
	 */
	public static final String llcSparqlVar = "llc";
	/**
	 * Name of the variable used in the SPARQL queries to refer to a Low Level
	 * Context type, e.g. sitting or standing for the category activity.
	 */
	public static final String llcTypeSparqlVar = "type";
	/**
	 * Name of the variable used in the SPARQL queries to refer to a Low Level
	 * Context type, e.g. sitting or standing for the category activity.
	 */
	public static final String llcType1SparqlVar = "type1";
	/**
	 * Name of the variable used in the SPARQL queries to refer to a Low Level
	 * Context type, e.g. sitting or standing for the category activity.
	 */
	public static final String llcType2SparqlVar = "type2";
	/**
	 * Name of the variable used in the SPARQL queries to refer to a Low Level
	 * Context type, e.g. sitting or standing for the category activity.
	 */
	public static final String llcType3SparqlVar = "type3";
	/**
	 * Name of the variable used in the SPARQL queries to refer to a Low Level
	 * Context category, e.g., activity, location,food or emotion.
	 */
	public static final String llcCategorySparqlVar = "category";
	/** Asif
	 * Name of the Nutrition Context in the Context Ontology.
	 */
	public static final String nutrClassName = ns + "NutritionContext";
	/** Asif
	 * Name of the Nutrition Context in the Context Ontology.
	 */
	public static final String clinicalClassName = ns + "ClinicalContext";
	/**
	 * Name of the PhysicalActivity Context class in the Context Ontology.
	 */
	public static final String pacClassName = ns + "PhysicalActivityContext";
	/**
	 * Name of the Food Context class in the Context Ontology.
	 */
	public static final String eggClassName = ns + "Eggs";
	/**
	 * Name of the Food Context class in the Context Ontology.
	 */
	public static final String fruitClassName = ns + "Fruits";
	/**
	 * Name of the Food Context class in the Context Ontology.
	 */
	public static final String grainClassName = ns + "Grain";
	/**
	 * Name of the Food Context class in the Context Ontology.
	 */
	public static final String legumesClassName = ns + "Legumes";
	/**
	 * Name of the Food Context class in the Context Ontology.
	 */
	public static final String meatClassName = ns + "Meat";
	/**
	 * Name of the Food Context class in the Context Ontology.
	 */
	public static final String milkdairyClassName = ns + "MilkAndDairyProducts";
	/**
	 * Name of the Food Context class in the Context Ontology.
	 */
	public static final String nutsClassName = ns + "Nuts";
	/**
	 * Name of the Food Context class in the Context Ontology.
	 */
	public static final String seafoodClassName = ns + "SeaFood";
	/**
	 * Name of the Food Context class in the Context Ontology.
	 */
	public static final String snacksClassName = ns + "Snacks";
	/**
	 * Name of the Food Context class in the Context Ontology.
	 */
	public static final String vegClassName = ns + "Vegetable";
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/test/java/org/uclab/mm/datamodel/dc/dataadapter/testcases/UserDataAdapterTest.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.dc.dataadapter.testcases;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.uclab.mm.datamodel.AbstractDataBridge;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.DatabaseStorage;
import org.uclab.mm.datamodel.dc.Users;
import org.uclab.mm.datamodel.dc.dataadapter.UserDataAdapter;


/**
 * This is a class for testing the insertion, fetching, and update of User profile Data 
 * @author <NAME>
 *
 */
public class UserDataAdapterTest {

	/**
	 * This is function for testing the insertion, fetching, and update of PhysiologicalFactorsAdapter 
	 */
	@Test
	public void testCRUDUserProfile() {
		/* Preparing input object for insertion*/
		Users objOuterUsers = new Users();
		Users objInnerUsers = new Users();
		List<Users> objListUsers = new  ArrayList<Users>();
		
		objOuterUsers.setFirstName("TestFirstName");
		objOuterUsers.setLastName("TestLastName");
		objOuterUsers.setMiddleName("TestmiddleName");
		objOuterUsers.setGenderId(1);
		objOuterUsers.setDateOfBirth("1983 05 02 00:00:00");
		objOuterUsers.setContactNumber("2136548");
		objOuterUsers.setEmailAddress("<EMAIL>");
		objOuterUsers.setMartialStatusId(1);
		objOuterUsers.setActivityLevelId(1);
		objOuterUsers.setOccupationId(1);
		objOuterUsers.setPassword("<PASSWORD>");
		objOuterUsers.setUserTypeID(1);
		
		/* Testing of insertion function*/
		 DataAccessInterface objDAInterface = new UserDataAdapter();
         AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
         List<String> lstResponse = objADBridge.SaveUser(objOuterUsers);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerUsers.setUserID(Long.parseLong(lstResponse.get(0)));
        	 objInnerUsers.setRequestType("UserData");
        	 DataAccessInterface objDAInterfaceRetrieval = new UserDataAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListUsers = objADBridgeRetrieval.RetriveUser(objInnerUsers);
        	 objInnerUsers = objListUsers.get(0);
         }
         
         assertEquals(objOuterUsers.getFirstName(), objInnerUsers.getFirstName());
         
         /* Testing of Update function*/
         objInnerUsers.setFirstName("TestFirstNameUpdated");
         DataAccessInterface objDAInterfaceUpdate = new UserDataAdapter();
         AbstractDataBridge objADBridgeUpdate = new DatabaseStorage(objDAInterfaceUpdate);
         lstResponse = objADBridgeUpdate.UpdateUser(objInnerUsers);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerUsers.setUserID(Long.parseLong(lstResponse.get(0)));
        	 DataAccessInterface objDAInterfaceRetrieval = new UserDataAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListUsers = objADBridgeRetrieval.RetriveUser(objInnerUsers);
        	 objInnerUsers = objListUsers.get(0);
         }
         
         assertEquals(objInnerUsers.getFirstName(), "TestFirstNameUpdated");
	}

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/RecommendationException.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author <NAME>
 */
@Entity
public class RecommendationException implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private Long recommendationExceptionID;
    private Long recommendationID;
    private String exception;
    private String customRule;
    private String exceptionReason;
    
    
    

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof RecommendationException)) {
            return false;
        }
        RecommendationException other = (RecommendationException) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.sc.RecommendationException[ id=" + id + " ]";
    }

    /**
     * @return the recommendationExceptionID
     */
    public Long getRecommendationExceptionID() {
        return recommendationExceptionID;
    }

    /**
     * @param recommendationExceptionID the recommendationExceptionID to set
     */
    public void setRecommendationExceptionID(Long recommendationExceptionID) {
        this.recommendationExceptionID = recommendationExceptionID;
    }

    /**
     * @return the recommendationID
     */
    public Long getRecommendationID() {
        return recommendationID;
    }

    /**
     * @param recommendationID the recommendationID to set
     */
    public void setRecommendationID(Long recommendationID) {
        this.recommendationID = recommendationID;
    }

    /**
     * @return the exception
     */
    public String getException() {
        return exception;
    }

    /**
     * @param exception the exception to set
     */
    public void setException(String exception) {
        this.exception = exception;
    }

    /**
     * @return the customRule
     */
    public String getCustomRule() {
        return customRule;
    }

    /**
     * @param customRule the customRule to set
     */
    public void setCustomRule(String customRule) {
        this.customRule = customRule;
    }

    /**
     * @return the exceptionReason
     */
    public String getExceptionReason() {
        return exceptionReason;
    }

    /**
     * @param exceptionReason the exceptionReason to set
     */
    public void setExceptionReason(String exceptionReason) {
        this.exceptionReason = exceptionReason;
    }
    
}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/interpreterdatamodel/InterpretationIngredients.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.interpreterdatamodel;

import java.util.ArrayList;
import java.util.List;

import org.uclab.scl.outputModel.InterpretationModel.PhyActivityException;
/**
 * @version MM v2.5
 * @author Afzal
 *
 */
public class InterpretationIngredients {

 // private List<UserSchedule> userSchedule = new ArrayList<UserSchedule>();
  private List<FiredRule> firedRule = new ArrayList<FiredRule>();
  private long recommendationID;
  private String userID;

  public String getUserID() {
    return userID;
  }

  public void setUserID(String userID) {
    this.userID = userID;
  }

//  /**
//   * @return the userSchedule
//   */
//  public List<UserSchedule> getUserSchedule() {
//    return userSchedule;
//  }
//
//  /**
//   * @param userSchedule
//   *          the userSchedule to set
//   */
//  public void setUserSchedule(List<UserSchedule> userSchedule) {
//    this.userSchedule = userSchedule;
//  }

  public List<FiredRule> getFiredRule() {
    return firedRule;
  }

  public void setFiredRule(List<FiredRule> firedRule) {
    this.firedRule = firedRule;
  }

  /**
   * @return the recommendationID
   */
  public long getRecommendationID() {
    return recommendationID;
  }

  /**
   * @param recommendationID
   *          the recommendationID to set
   */
  public void setRecommendationID(long recommendationID) {
    this.recommendationID = recommendationID;
  }
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/AR/iar/AR_Reasoning.java<|end_filename|>
/**
Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */

package org.uclab.mm.icl.llc.AR.iar;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import org.uclab.mm.icl.utils.FileUtil;

import weka.classifiers.Classifier;
import weka.core.Instances;

/**
 * This class loads the smartphone, smartwatch and integrated AR model. It also
 * executes the weka based on the AR model and returns the activity label
 * 
 * @author <NAME>
 *
 */
public class AR_Reasoning {
	Classifier classifier;

	String name;

	/**
	 * This function loads the AR model
	 * 
	 * @param modelpath
	 * 
	 */
	public AR_Reasoning(String modelpath) {
		try {
			classifier = (Classifier) weka.core.SerializationHelper.read(modelpath);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * This function executes the Weka to infer the activity and returns the activity label
	 * 
	 * @param modelno
	 * @return arLabel
	 */
	public String executeWeka(int modelno) {
		String arLabel = ""; // Stores the activity label
		Instances unlabeled = null;
		try {
			switch (modelno) {
			// Load integrated arff file which contains feature list
			case 1:
				unlabeled = new Instances(new BufferedReader(
						new FileReader(new File(FileUtil.getRootPath() + "/ar/" + "/integrated.txt"))));
				break;
			// Load smartphone arff file which contains feature list
			case 2:
				unlabeled = new Instances(new BufferedReader(
						new FileReader(new File(FileUtil.getRootPath() + "/ar/" + "/sm.txt"))));
				break;
			// Load wearable arff file which contains feature list
			case 3:
				unlabeled = new Instances(new BufferedReader(
						new FileReader(new File(FileUtil.getRootPath() + "/ar/" + "/wm.txt"))));
				break;
			}

			unlabeled.setClassIndex((unlabeled.numAttributes() - 1));
			Instances labeld = new Instances(unlabeled);

			for (int j = 0; j < unlabeled.numInstances(); j++) {
				arLabel += (int) classifier.classifyInstance(unlabeled.instance(j));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return arLabel;
	}
}


<|start_filename|>supporting-layer/descriptive-analytics/src/assets/js/cal_burned.js<|end_filename|>
AmCharts.makeChart("monthcal_burned_chartdiv",
				{
					"type": "serial",
					"path": "http://www.amcharts.com/lib/3/images/",
					"categoryField": "date",
					"dataDateFormat": "YYYY-MM-DD HH",
					"categoryAxis": {
						"minPeriod": "hh",
						"parseDates": true
					},
					"chartCursor": {
						"categoryBalloonDateFormat": "JJ:NN"
					},
					"chartScrollbar": {},
					"trendLines": [],
					"graphs": [
						{
							"bulletBorderThickness": 0,
							"fillAlphas": 1,
							"fixedColumnWidth": 20,
							"id": "Cal Burned",
							"title": "Cal Burned",
							"type": "column",
							"valueField": "column-1"
						}
					],
					"guides": [],
					"valueAxes": [
						{
							"id": "calburned",
							"title": "cal burned"
						}
					],
					"allLabels": [],
					"balloon": {},
					"legend": {
						"useGraphSettings": true
					},
					"titles": [],
					"dataProvider": [
						{
							"column-1": 8,
							"date": "2014-03-01 "
						},
						{
							"column-1": 6,
							"date": "2014-03-02"
						},
						{
							"column-1": 2,
							"date": "2014-03-03"
						},
						{
							"column-1": 1,
							"date": "2014-03-04"
						},
						{
							"column-1": 2,
							"date": "2014-03-05"
						},
						{
							"column-1": 3,
							"date": "2014-03-06"
						},
						{
							"column-1": 6,
							"date": "2014-03-07"
						}
					]
				}
			);









AmCharts.makeChart("monthmet_minutes_chartdiv",
				{
					"type": "serial",
					"path": "http://www.amcharts.com/lib/3/images/",
					"categoryField": "date",
					"dataDateFormat": "YYYY-MM-DD HH",
					"categoryAxis": {
						"minPeriod": "hh",
						"parseDates": true
					},
					"chartCursor": {
						"categoryBalloonDateFormat": "JJ:NN"
					},
					"chartScrollbar": {},
					"trendLines": [],
					"graphs": [
						{
							"bulletBorderThickness": 0,
							"fillAlphas": 1,
							"fixedColumnWidth": 20,
							"id": "Cal Burned",
							"title": "Cal Burned",
							"type": "column",
							"valueField": "column-1"
						}
					],
					"guides": [],
					"valueAxes": [
						{
							"id": "calburned",
							"title": "cal burned"
						}
					],
					"allLabels": [],
					"balloon": {},
					"legend": {
						"useGraphSettings": true
					},
					"titles": [],
					"dataProvider": [
						{
							"column-1": 8,
							"date": "2014-03-01 08"
						},
						{
							"column-1": 6,
							"date": "2014-03-01 09"
						},
						{
							"column-1": 2,
							"date": "2014-03-01 10"
						},
						{
							"column-1": 1,
							"date": "2014-03-01 11"
						},
						{
							"column-1": 2,
							"date": "2014-03-01 12"
						},
						{
							"column-1": 3,
							"date": "2014-03-01 13"
						},
						{
							"column-1": 6,
							"date": "2014-03-01 14"
						}
					]
				}
			);

<|start_filename|>knowledge-curation-layer/DDKAT/target/DDKAT/css/ddka-interface.css<|end_filename|>
IMG {
	BORDER-RIGHT: 0px; BORDER-TOP: 0px; BORDER-LEFT: 0px; BORDER-BOTTOM: 0px
}
TABLE {
	MARGIN: 0px; WIDTH: 100%; BORDER-COLLAPSE: collapse
}
TABLE TD {
	BORDER-TOP-WIDTH: 0px; PADDING-RIGHT: 0px; PADDING-LEFT: 0px; BORDER-LEFT-WIDTH: 0px; BORDER-BOTTOM-WIDTH: 0px; PADDING-BOTTOM: 0px; VERTICAL-ALIGN: top; PADDING-TOP: 0px; BORDER-RIGHT-WIDTH: 0px
}
DIV {
	MARGIN-BOTTOM: 0px
}
BODY {
	SCROLLBAR-FACE-COLOR: #004487; BACKGROUND-IMAGE: url(..); MARGIN: 0px; SCROLLBAR-HIGHLIGHT-COLOR: #d6d9dc; SCROLLBAR-SHADOW-COLOR: #d6d9dc; SCROLLBAR-ARROW-COLOR: #ffffff; SCROLLBAR-TRACK-COLOR: #ffcb7c; BACKGROUND-REPEAT: repeat-x; FONT-FAMILY: Times New Roman, Verdana, Arial, Helvetica, sans-serif; SCROLLBAR-BASE-COLOR: #d6d9dc; BACKGROUND-COLOR: #ffffff; scrollbar-dark-shadow-color: #FFFFFF; scrollbar-3d-light-color: #FFFFFF
}
#header {
	BACKGROUND: #4c7cab; HEIGHT: 106px
}
#tran1 {
	BACKGROUND-IMAGE: url(..); BACKGROUND-REPEAT: repeat-y; HEIGHT: 6px; BACKGROUND-COLOR: #ffffff
}
.headergfx {
	BACKGROUND-IMAGE: url(../images/citypic_homepage_tile2.gif); WIDTH: 750px; HEIGHT: 209px; BACKGROUND-COLOR: #d5d5d2
}
#headergfx3 {
	BACKGROUND-IMAGE: url(../images/citypic_homepage_tile2.gif); HEIGHT: 209px; BACKGROUND-COLOR: #d5d5d2
}
#headergfx2 {
	BACKGROUND-IMAGE: url(../images/citypic_2.jpg); HEIGHT: 209px; BACKGROUND-COLOR: #d5d5d2
}
#tran2 {
	BACKGROUND-IMAGE: url(..); BACKGROUND-REPEAT: repeat-y; HEIGHT: 6px; BACKGROUND-COLOR: #ff9900
}
#menubar {
	HEIGHT: 21px; BACKGROUND-COLOR: #004487
}
#main {
	WIDTH: 750px
}
#main2 {
	WIDTH: 100%; TEXT-ALIGN: center
}
#leftMenu {
	PADDING-RIGHT: 5px; PADDING-LEFT: 5px; FONT-SIZE: 0.7em; PADDING-BOTTOM: 0px; WIDTH: 190px; COLOR: #004488; PADDING-TOP: 10px; FONT-FAMILY: Arial, Helvetica, sans-serif; TEXT-DECORATION: none
}
#leftMenu A {
	PADDING-RIGHT: 5px; PADDING-LEFT: 20px; PADDING-BOTTOM: 0px; COLOR: #004488; PADDING-TOP: 10px; TEXT-DECORATION: none
}
#leftMenu A:visited {
	COLOR: #004488
}
#leftMenu A:hover {
	COLOR: #ff9900
}
#leftMenu A:active {
	COLOR: #ff9900
}
#body {
	PADDING-RIGHT: 5px; PADDING-LEFT: 5px; FONT-SIZE: 0.7em; PADDING-BOTTOM: 0px; WIDTH: 560px; PADDING-TOP: 10px; FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif
}
.body {
	FONT-SIZE: 1em; VERTICAL-ALIGN: top; WIDTH: 580px
}
#bodyMain {
	PADDING-RIGHT: 5px; PADDING-LEFT: 5px; FONT-SIZE: 0.7em; PADDING-BOTTOM: 0px; WIDTH: 590px; PADDING-TOP: 10px; FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif
}
#rightMenu {
	PADDING-RIGHT: 5px; PADDING-LEFT: 1px; FONT-SIZE: 0.7em; PADDING-BOTTOM: 0px; WIDTH: 0px; PADDING-TOP: 10px; FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif
}
.teritoryBox {
	MARGIN: 0px 0px 10px 10px
}
#footer {
	FONT-SIZE: 0.6em; MARGIN: 10px 10px 0px 0px; WIDTH: 740px; COLOR: #444444; TEXT-ALIGN: right
}
H1 {
	BACKGROUND-POSITION: center top; FONT-WEIGHT: normal; FONT-SIZE: 2em; TEXT-TRANSFORM: uppercase; COLOR: #4586d3; LINE-HEIGHT: normal; FONT-STYLE: normal; FONT-FAMILY: Arial, Verdana, Helvetica, sans-serif; LETTER-SPACING: 30px
}
H2 {
	FONT-WEIGHT: bold; FONT-SIZE: 1.5em; TEXT-TRANSFORM: uppercase; COLOR: #4586d3; LINE-HEIGHT: normal; FONT-STYLE: normal; FONT-FAMILY: Arial, Verdana, Helvetica, sans-serif; LETTER-SPACING: 5px
}
H3 {
	FONT-WEIGHT: bold; FONT-SIZE: 1.2em; MARGIN-BOTTOM: 4px; COLOR: #03335c; LINE-HEIGHT: normal; BORDER-BOTTOM: #000000 1px solid; FONT-STYLE: normal; FONT-FAMILY: Arial, Helvetica, sans-serif
}
H4 {
	FONT-WEIGHT: bold; FONT-SIZE: 1em; MARGIN-BOTTOM: 4px; MARGIN-RIGHT: 8px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif
}
.name {
	FONT-WEIGHT: bold; FONT-SIZE: 12px; COLOR: #004488; FONT-FAMILY: Arial, Helvetica, sans-serif
}
.body A {
	FONT-SIZE: 1.15em; COLOR: #004488; FONT-FAMILY: Arial, Helvetica, sans-serif
}
.body A:hover {
	FONT-SIZE: 1.15em; COLOR: #ff9900; FONT-FAMILY: Arial, Helvetica, sans-serif
}
#dropBox {
	BORDER-RIGHT: #7f9db9 1px solid; BORDER-TOP: #7f9db9 1px solid; FONT-SIZE: 10px; BORDER-LEFT: #7f9db9 1px solid; WIDTH: 145px; MARGIN-RIGHT: 30px; BORDER-BOTTOM: #7f9db9 1px solid; FONT-FAMILY: Arial, Helvetica, sans-serif; HEIGHT: 20px; BACKGROUND-COLOR: #ffffff
}
.inputBox {
	BORDER-RIGHT: #7f9db9 1px solid; BORDER-TOP: #7f9db9 1px solid; FONT-SIZE: 10px; BORDER-LEFT: #7f9db9 1px solid; WIDTH: 145px; BORDER-BOTTOM: #7f9db9 1px solid; FONT-FAMILY: Arial, Helvetica, sans-serif; HEIGHT: 20px; BACKGROUND-COLOR: #ffffff
}
.form {
	FONT-SIZE: 1em; WIDTH: 330px
}


ul.radio  { 
  margin: 0; 
  padding: 0; 
  margin-left: 20px; 
  list-style: none; 
} 

ul.radio li { 
  border: 1px transparent solid; 
} 

ul.radio li:hover, 
ul.radio li.focus  { 
  background-color: lightyellow; 
  border: 1px gray solid; 
  width: 10em; 
} 






<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/UserRewards.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author dcadmin
 */
@Entity
public class UserRewards implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private Long userRewardID;
    private Long userID;
    private int rewardPoints;
    private String rewardDescription;
    private String rewardDate;
    private int rewardTypeID;
    private String rewardTypeDescription;
    
    

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof UserRewards)) {
            return false;
        }
        UserRewards other = (UserRewards) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.sc.UserRewards[ id=" + id + " ]";
    }

    /**
     * @return the userRewardID
     */
    public Long getUserRewardID() {
        return userRewardID;
    }

    /**
     * @param userRewardID the userRewardID to set
     */
    public void setUserRewardID(Long userRewardID) {
        this.userRewardID = userRewardID;
    }

    /**
     * @return the userID
     */
    public Long getUserID() {
        return userID;
    }

    /**
     * @param userID the userID to set
     */
    public void setUserID(Long userID) {
        this.userID = userID;
    }

    /**
     * @return the rewardPoints
     */
    public int getRewardPoints() {
        return rewardPoints;
    }

    /**
     * @param rewardPoints the rewardPoints to set
     */
    public void setRewardPoints(int rewardPoints) {
        this.rewardPoints = rewardPoints;
    }

    /**
     * @return the rewardDescription
     */
    public String getRewardDescription() {
        return rewardDescription;
    }

    /**
     * @param rewardDescription the rewardDescription to set
     */
    public void setRewardDescription(String rewardDescription) {
        this.rewardDescription = rewardDescription;
    }

    /**
     * @return the rewardDate
     */
    public String getRewardDate() {
        return rewardDate;
    }

    /**
     * @param rewardDate the rewardDate to set
     */
    public void setRewardDate(String rewardDate) {
        this.rewardDate = rewardDate;
    }

    /**
     * @return the rewardTypeID
     */
    public int getRewardTypeID() {
        return rewardTypeID;
    }

    /**
     * @param rewardTypeID the rewardTypeID to set
     */
    public void setRewardTypeID(int rewardTypeID) {
        this.rewardTypeID = rewardTypeID;
    }

    /**
     * @return the rewardTypeDescription
     */
    public String getRewardTypeDescription() {
        return rewardTypeDescription;
    }

    /**
     * @param rewardTypeDescription the rewardTypeDescription to set
     */
    public void setRewardTypeDescription(String rewardTypeDescription) {
        this.rewardTypeDescription = rewardTypeDescription;
    }
    
}


<|start_filename|>knowledge-curation-layer/DDKAT/src/main/java/org/uclab/mm/kcl/ddkat/datapreprocessor/OutlierHandler.java<|end_filename|>
/**
 * Copyright [2017] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.mm.kcl.ddkat.datapreprocessor;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import weka.filters.Filter;
import weka.filters.unsupervised.attribute.InterquartileRange;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Range;
import weka.core.converters.ArffSaver;
import weka.core.converters.CSVLoader;

// TODO: Auto-generated Javadoc
/**
 * This class detects the outlier values using Interquartile approach, replaces them with attribute mean values, and stores the consistent data.
 */
public class OutlierHandler extends InterquartileRange {
	
	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;
	
	/** The Constant log. */
	private static final Logger log = LoggerFactory.getLogger(OutlierHandler.class);
	
	/** base directory to store resource data files */
	private static final String BASE_DIR = System.getProperty("user.home") + "/DDKAT/resources/";
		
	/**
	 * Constructor to instantiate a new OutlierHandler object.
	 *
	 * @throws Exception the exception
	 */
	public OutlierHandler() throws Exception {
		
		replaceOutliers();
	}
	
	/**
	 * Method to replace the detected outlier values.
	 *
	 * @throws Exception the exception
	 */
	public void replaceOutliers() throws Exception {
		
		Instances inputData, outputData;
		
		String inputFile = BASE_DIR + "OriginalDataSet.csv";
			
        // load CSV file
		CSVLoader fileLoader=new CSVLoader();
		fileLoader.setSource(new File(inputFile));
	    inputData = fileLoader.getDataSet();   
	    this.setInputFormat(inputData);
	    outputData = Filter.useFilter(inputData, this);
   
        int numInstances = outputData.numInstances();
        int numAttributes = outputData.numAttributes();

        final int NON_NUMERIC = -1;
        double[] outlier_AttributeValues = null;
        double[] extreme_AttributeValues = null;
        int[] m_AttributeIndices = null;
        
        Range m_Attributes = new Range("first-last");

        // attributes must be numeric
        m_Attributes.setUpper(outputData.numAttributes() - 1);
        m_AttributeIndices = m_Attributes.getSelection();

        for (int i = 0; i < m_AttributeIndices.length; i++) {
            // ignore class
            if (m_AttributeIndices[i] == outputData.classIndex()) {
                m_AttributeIndices[i] = NON_NUMERIC;
                continue;
                }
            // not numeric -> ignore it
            if (!outputData.attribute(m_AttributeIndices[i]).isNumeric())
                m_AttributeIndices[i] = NON_NUMERIC;
            }

        for (int instanceIndex = 0; instanceIndex < numInstances; instanceIndex++) {
            // access instance 
            Instance tempInstance = outputData.instance(instanceIndex);                     

            for (int attributeIndex = 0; attributeIndex < numAttributes; attributeIndex++) {
                // non-numeric attribute?
                if (m_AttributeIndices[attributeIndex] == NON_NUMERIC){
                    continue;
                    }
                
                // detect the outlier values using Interquartile approach
                if (this.isOutlier(tempInstance, m_AttributeIndices[attributeIndex])){

                    double outlierValue = tempInstance.value(attributeIndex);
                    int outlierColumnIndex = attributeIndex;
                    double sum = 0.0;

                    outlier_AttributeValues = outputData.attributeToDoubleArray(outlierColumnIndex);

                    for (int i = 0; i < outlier_AttributeValues.length; i++){
                        sum = sum + outlier_AttributeValues[i]; 
                        }

                    sum = sum - outlierValue;
                    double replacedValue = sum/(outlier_AttributeValues.length-1);
                    replacedValue = Math.round(replacedValue * 100D) / 100D;
                    
                    // replace the outliers with attribute mean values
                    outputData.instance(instanceIndex).setValue(outlierColumnIndex, replacedValue);
                    }

                // extreme value?
                if (this.isExtremeValue(tempInstance, m_AttributeIndices[attributeIndex])){

                    double extremeValue = tempInstance.value(attributeIndex);
                    int extremeColumnIndex = attributeIndex;
                    double sum = 0.0;

                    extreme_AttributeValues = outputData.attributeToDoubleArray(extremeColumnIndex);

                    for (int i = 0; i < extreme_AttributeValues.length; i++){
                        sum = sum + extreme_AttributeValues[i]; 
                        }

                    sum = sum - extremeValue;
                    double replacedValue = sum/(extreme_AttributeValues.length-1);
                    replacedValue = Math.round(replacedValue * 100D) / 100D;
                    outputData.instance(instanceIndex).setValue(extremeColumnIndex, replacedValue);
                    }

                } 
            }
        outputData.deleteAttributeAt(outputData.numAttributes()-1); 
        outputData.deleteAttributeAt(outputData.numAttributes()-1);
        
        saveConsistentData(inputFile, outputData);
                           
 	}
	
	/**
	 * Method to store the consistent data.
	 *
	 * @param filePath the file path
	 * @param outputData the output data
	 * @throws Exception the exception
	 */
	public void saveConsistentData(String filePath, Instances outputData) throws Exception {
		
		// save ARFF file
        String outputFile = filePath.substring(0,filePath.lastIndexOf('/'));
        outputFile = outputFile + "/ProcessedDataSet.arff";
        log.info("Output file : "+outputFile);
        log.info("Outliers are successfully removed");
               
        ArffSaver saver = new ArffSaver();
        saver.setInstances(outputData);
        saver.setFile(new File(outputFile));
        saver.writeBatch();
        
	}
	
}



<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/datamodel/UserSchedule.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.datamodel;

/**
 * @version MM v2.5
 * @author Afzal
 *
 */
public class UserSchedule {

  private String startTime;

  private long userID;

  private String scheduledTask;

  private String endTime;

  private long userScheduleID;

  public String getStartTime() {
    return startTime;
  }

  public void setStartTime(String startTime) {
    this.startTime = startTime;
  }

  public long getUserID() {
    return userID;
  }

  public void setUserID(long userID) {
    this.userID = userID;
  }

  public String getScheduledTask() {
    return scheduledTask;
  }

  public void setScheduledTask(String scheduledTask) {
    this.scheduledTask = scheduledTask;
  }

  public String getEndTime() {
    return endTime;
  }

  public void setEndTime(String endTime) {
    this.endTime = endTime;
  }

  public long getUserScheduleID() {
    return userScheduleID;
  }

  public void setUserScheduleID(long userScheduleID) {
    this.userScheduleID = userScheduleID;
  }

  @Override
  public String toString() {
    return "ClassPojo [startTime = " + startTime + ", userID = " + userID
        + ", scheduledTask = " + scheduledTask + ", endTime = " + endTime
        + ", userScheduleID = " + userScheduleID + "]";
  }
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/MMDataCurationRestfulService/src/main/java/org/uclab/mm/rs/datacuration/ApplicationConfig.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.rs.datacuration;

import java.util.Set;
import javax.ws.rs.core.Application;

/**
 *
 * @author <NAME>
 */
@javax.ws.rs.ApplicationPath("webresources")
public class ApplicationConfig extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> resources = new java.util.HashSet<>();
        addRestResourceClasses(resources);
        return resources;
    }

    /**
     * Do not modify addRestResourceClasses() method.
     * It is automatically populated with
     * all resources defined in the project.
     * If required, comment out calling this method in getClasses().
     */
    private void addRestResourceClasses(Set<Class<?>> resources) {
        resources.add(org.uclab.mm.rs.datacuration.DataCurationResource.class);
        resources.add(org.uclab.mm.rs.informationcuration.InformationCurationResource.class);
        resources.add(org.uclab.mm.rs.servicecuration.ServiceCurationResource.class);
        resources.add(org.uclab.mm.rs.supportinglayer.SupportingLayerResource.class);
    }
    
}


<|start_filename|>supporting-layer/uiux-authoring-tool/JavaDoc/index-files/index-5.html<|end_filename|>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_76-release) on Fri Dec 23 12:27:02 KST 2016 -->
<title>E-Index</title>
<meta name="date" content="2016-12-23">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
<script type="text/javascript" src="../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
    try {
        if (location.href.indexOf('is-external=true') == -1) {
            parent.document.title="E-Index";
        }
    }
    catch(err) {
    }
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!--   -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!--   -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-4.html">Prev Letter</a></li>
<li><a href="index-6.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-files/index-5.html" target="_top">Frames</a></li>
<li><a href="index-5.html" target="_top">No&nbsp;Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
  allClassesLink = document.getElementById("allclasses_navbar_top");
  if(window==top) {
    allClassesLink.style.display = "block";
  }
  else {
    allClassesLink.style.display = "none";
  }
  //-->
</script>
</div>
<a name="skip.navbar.top">
<!--   -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="contentContainer"><a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">J</a>&nbsp;<a href="index-11.html">L</a>&nbsp;<a href="index-12.html">M</a>&nbsp;<a href="index-13.html">N</a>&nbsp;<a href="index-14.html">O</a>&nbsp;<a href="index-15.html">P</a>&nbsp;<a href="index-16.html">Q</a>&nbsp;<a href="index-17.html">R</a>&nbsp;<a href="index-18.html">S</a>&nbsp;<a href="index-19.html">T</a>&nbsp;<a href="index-20.html">U</a>&nbsp;<a href="index-21.html">V</a>&nbsp;<a href="index-22.html">W</a>&nbsp;<a name="I:E">
<!--   -->
</a>
<h2 class="title">E</h2>
<dl>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/R.id.html#edit_query">edit_query</a></span> - Static variable in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/R.id.html" title="class in org.uclab.mm.sl.uiux.analytics">R.id</a></dt>
<dd>&nbsp;</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/R.attr.html#editTextBackground">editTextBackground</a></span> - Static variable in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/R.attr.html" title="class in org.uclab.mm.sl.uiux.analytics">R.attr</a></dt>
<dd>
<div class="block">Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/R.attr.html#editTextColor">editTextColor</a></span> - Static variable in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/R.attr.html" title="class in org.uclab.mm.sl.uiux.analytics">R.attr</a></dt>
<dd>
<div class="block">May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/R.attr.html#editTextStyle">editTextStyle</a></span> - Static variable in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/R.attr.html" title="class in org.uclab.mm.sl.uiux.analytics">R.attr</a></dt>
<dd>
<div class="block">Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/dispatcher/TrackerBulkURLWrapper.Page.html#elementsCount--">elementsCount()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.dispatcher.<a href="../org/uclab/mm/sl/uiux/analytics/dispatcher/TrackerBulkURLWrapper.Page.html" title="class in org.uclab.mm.sl.uiux.analytics.dispatcher">TrackerBulkURLWrapper.Page</a></dt>
<dd>
<div class="block">Elements count int.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/R.attr.html#elevation">elevation</a></span> - Static variable in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/R.attr.html" title="class in org.uclab.mm.sl.uiux.analytics">R.attr</a></dt>
<dd>
<div class="block">Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/R.id.html#end">end</a></span> - Static variable in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/R.id.html" title="class in org.uclab.mm.sl.uiux.analytics">R.id</a></dt>
<dd>&nbsp;</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/R.id.html#end_padder">end_padder</a></span> - Static variable in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/R.id.html" title="class in org.uclab.mm.sl.uiux.analytics">R.id</a></dt>
<dd>&nbsp;</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html#equals-java.lang.Object-">equals(Object)</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html" title="class in org.uclab.mm.sl.uiux.analytics">Tracker</a></dt>
<dd>&nbsp;</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/TrackHelper.html#event-java.lang.String-java.lang.String-">event(String, String)</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/TrackHelper.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper</a></dt>
<dd>
<div class="block">Events are a useful way to collect data about a user's interaction with interactive components of your app,
 like button presses or the use of a particular item in a game.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/TrackHelper.html#exception-java.lang.Throwable-">exception(Throwable)</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/TrackHelper.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper</a></dt>
<dd>
<div class="block">Caught exceptions are errors in your app for which you've defined exception handling code,
 such as the occasional timeout of a network connection during a request for data.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/R.id.html#expand_activities_button">expand_activities_button</a></span> - Static variable in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/R.id.html" title="class in org.uclab.mm.sl.uiux.analytics">R.id</a></dt>
<dd>&nbsp;</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/R.attr.html#expandActivityOverflowButtonDrawable">expandActivityOverflowButtonDrawable</a></span> - Static variable in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/R.attr.html" title="class in org.uclab.mm.sl.uiux.analytics">R.attr</a></dt>
<dd>
<div class="block">Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/R.id.html#expanded_menu">expanded_menu</a></span> - Static variable in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/R.id.html" title="class in org.uclab.mm.sl.uiux.analytics">R.id</a></dt>
<dd>&nbsp;</dd>
</dl>
<a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">J</a>&nbsp;<a href="index-11.html">L</a>&nbsp;<a href="index-12.html">M</a>&nbsp;<a href="index-13.html">N</a>&nbsp;<a href="index-14.html">O</a>&nbsp;<a href="index-15.html">P</a>&nbsp;<a href="index-16.html">Q</a>&nbsp;<a href="index-17.html">R</a>&nbsp;<a href="index-18.html">S</a>&nbsp;<a href="index-19.html">T</a>&nbsp;<a href="index-20.html">U</a>&nbsp;<a href="index-21.html">V</a>&nbsp;<a href="index-22.html">W</a>&nbsp;</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!--   -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!--   -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-4.html">Prev Letter</a></li>
<li><a href="index-6.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-files/index-5.html" target="_top">Frames</a></li>
<li><a href="index-5.html" target="_top">No&nbsp;Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
  allClassesLink = document.getElementById("allclasses_navbar_bottom");
  if(window==top) {
    allClassesLink.style.display = "block";
  }
  else {
    allClassesLink.style.display = "none";
  }
  //-->
</script>
</div>
<a name="skip.navbar.bottom">
<!--   -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/OntologyTools/IContext.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.OntologyTools;

import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntResource;
/**
 * IContext interface provides common methods.
 * 
 * @author <NAME>
 * @version 2.5
 * @since 2016-10-28
 */
public interface IContext {
//	public boolean isValidInstanceOfHlc();
//	public boolean isClassified();
//	public void setHlcInstance(OntResource inst);	
//	public void setHlcClass(OntClass c);
//	public void setUnidentifiedHlc();
}


<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/dataaccess/DBConnection.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */
package org.uclab.mm.dcl.llm.dataaccess;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.uclab.mm.dcl.llm.exception.DatabaseConnectionProblem;

/**
 * This class is used to define the connection with database. JDBC driver is used to connect.
 * @author Rizvi
 */
public class DBConnection{

  private static Connection conn = null;

  /**
   * Constructor to establish the connection with database.
   */
  private DBConnection(){ 
    try{
      Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
     
      conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=MMLLM;user=sa;password=<PASSWORD>");
      
    } catch (  SQLException | ClassNotFoundException exp){
      
     StringWriter errors = new StringWriter();
      exp.printStackTrace(new PrintWriter(errors));
      System.out.println("conn exception "+ exp);
      }
  }

  /**
   * This method is used to access the connection
   * @return 
   */
  public Connection getConnection(){
    return conn;
  }
/**
 * This method is used to get the established connection with database.
 * @return 
 */
  public static DBConnection getDBConnection(){
    return DBConnectionHolder.INSTANCE;
  }

  /**
   * This method is defined to access same database connection.
   */
  private static class DBConnectionHolder {
    
    private static final DBConnection INSTANCE = new DBConnection();
  
  }
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/MachineLearningTools/classification/KinectARClassification.java<|end_filename|>
/*
Copyright [2016] [Thien]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.MachineLearningTools.classification;

import org.uclab.mm.icl.utils.FileUtil;
import weka.classifiers.functions.SMO;
import weka.core.Attribute;
import weka.core.FastVector;
import weka.core.Instance;
import weka.core.Instances;


/**
 * 
 * @author Nailbrainz
 * THis class classfies user context based on the 25 skeleton coordinates data 
 * inputtype - double[15][76]
 */
public class KinectARClassification extends Classification<double[]>{
	String[] labelString = new String[] {"Stretching", "LyingDown", "Sweeping","Sitting","Eating","Standing"};
	
	private SMO smo;
	Instances dummyDataset;
	/**
	 * 
	 */
	public KinectARClassification() {
		smo = null;
		loadModel(FileUtil.getRootPath()+"/SMOVAR.model");
	}
	/**
	 * This function loads the var model(SMO weka algorihtm) from local file
	 * @param filename file name to load the model from
	 * @return returns true when loading model was successful, false otherwise
	 */
	public boolean loadModel(String filename) {
		try {
			smo = (SMO) weka.core.SerializationHelper.read(filename);
			dummyDataset = createDummyDataset(281);
			return true;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return false;
	}
	
	/**
	 * This function saves the weka smo model into local file system
	 * @param filename file path to save the model
	 * @return true when saving model was successful, false otherwise
	 */
	public boolean saveModel(String filename) {
		try {
			weka.core.SerializationHelper.write(filename, smo);
			return true;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return false;
	}
	
	/**
	 * This function creates Weka instance
	 * @param features
	 * @return created instances
	 */
	protected Instance createInstance(double[] features) {
		int numAttributes = features.length;
		Instance instance = new Instance(numAttributes + 1);
		for (int i = 0; i < numAttributes; i++)
			instance.setValue(i, features[i]);
		return instance;
	}
	
	/**
	 * This function creates Weka instance
	 * @param features
	 * @return created instances
	 */
	protected Instances createDummyDataset(int numAttributes) {
		// Create attribute set
		FastVector fvWekaAttributes = new FastVector(numAttributes);
		
		// Create numeric attributes
		for (int i = 0; i < numAttributes - 1; i++) {
			Attribute attribute = new Attribute("f" + i);
			fvWekaAttributes.addElement(attribute);
		}
		
		// Create class attribute
		FastVector fvClassVal = new FastVector(6);
		fvClassVal.addElement("c1");
		fvClassVal.addElement("c2");
		fvClassVal.addElement("c3");
		fvClassVal.addElement("c4");
		fvClassVal.addElement("c5");
		fvClassVal.addElement("c6");
		Attribute classAttribute = new Attribute("class", fvClassVal);
		fvWekaAttributes.addElement(classAttribute);
		
		// Create an empty training set
		Instances dataset = new Instances("Rel", fvWekaAttributes, 1);
		// Set class index
		dataset.setClassIndex(numAttributes - 1);
		
		return dataset;
	}

	
	
	@Override
	public String Classify(double[] data) {
		// TODO Auto-generated method stub
		try {
			// Convert features to an instance
			Instance instance = createInstance(data);
			instance.setDataset(dummyDataset);
			
			// Classify
			int labelIndex =  Double.valueOf(smo.classifyInstance(instance)).intValue();
			
			return labelString[labelIndex];
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/LLCRecognizer/FoodRecognizer.java<|end_filename|>
package org.uclab.mm.icl.llc.LLCRecognizer;

import org.uclab.mm.icl.MainServlet;
import org.uclab.mm.icl.data.DeviceData;
import org.uclab.mm.icl.data.SmartphoneData;
import org.uclab.mm.icl.llc.LLCManager.ContextLabel;
import org.uclab.mm.icl.llc.LLCManager.LLCUnifier;
import org.uclab.mm.icl.llc.config.RecognizerType;
import org.uclab.mm.icl.llc.restservices.RestClients;
import org.uclab.mm.icl.llc.config.ContextType;
import org.uclab.mm.icl.llc.config.DeviceType;

class FoodData{

	byte[] image;
	String label;
	public byte[] getImage() {
		return image;
	}
	public void setImage(byte[] image) {
		this.image = image;
	}
	public String getLabel() {
		return label;
	}
	public void setLabel(String label) {
		this.label = label;
	}
	public FoodData(byte[] image, String label) {
		super();
		this.image = image;
		this.label = label;
	}
}

public class FoodRecognizer extends LLCRecognizer<FoodData>{

	int eatingCnt = 0;
	
	public FoodRecognizer(long userID) {
		super(userID);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void ConsumeData(DeviceType it, DeviceData obj) {
		// TODO Auto-generated method stub
		if(it.equals(DeviceType.SmartPhone)){
			SmartphoneData sd = (SmartphoneData) obj;
			//get the z coordinate of smartphone data
			byte[] data = null;
			String label = null;
			if(sd.getImage() != null)data = sd.getImage();
			if(sd.getFoodTag() != null)label = sd.getFoodTag();
			setData(new FoodData(data, label));
		}
	}

	@Override
	public RecognizerType getType() {
		// TODO Auto-generated method stub
		return RecognizerType.FR;
	}

	@Override
	public ContextLabel recognize(FoodData input, String timeStamp) {
		// TODO Auto-generated method stub
		
		
		String[] labels = getType().getContext().getLabels(); //up, down, nodir
		return new ContextLabel(userID, labels[labels.length-1],timeStamp, getType().getContext()); //down
	}
	
	@Override
	public Runnable getRunnable(String timeStamp, LLCUnifier unifier){
    	return new Runnable() { // new Handler and Runnable
            @Override
            public void run() {
            	if(MainServlet.server.getUser(userID).getcurLabels().get(ContextType.Food.getValue()).equals("Eating")){
        			eatingCnt++;
        		}else{
        			eatingCnt = 0;
        		}
        		if(eatingCnt > 4){ //if eating prolonged than 12seconds
        			while(isThresholdReached()){
        				FoodData idd = inputDatas.get(0);
                		inputDatas.remove(0);
                		ContextLabel rlt = recognize(idd, timeStamp);
                		try {
							RestClients.AddFoodLog(rlt);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
                		//unifier.push(recognize(idd, timeStamp), getType());
                	}
        		}
            	
            }
        };
    }

}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/MachineLearningTools/Preprocessing.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Bang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.MachineLearningTools;

/**
 * 
 * @author Nailbrainz
 * This class preprocess the data
 * @param <InputType> Data which will be preprocessed
 * @param <OutputType> preprocessed output
 */
public abstract class Preprocessing<InputType, OutputType> {
    
    /**
     * Abstract function, a structure for child preprocessing classes
     * @param input input data to preprocess
     * @return processed data
     */
    abstract public OutputType preprocessing(InputType input);
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/dataadapter/SituationAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.sc.Situation;
import org.uclab.mm.datamodel.sc.UserGoal;

/**
 * This is SituationAdapter class which implements the Data Access Interface for CRUD operations
 * @author <NAME>
 */
public class SituationAdapter implements DataAccessInterface {

    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(SituationAdapter.class);
    public SituationAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving Situation. 
     * @param objSituation
     * @return List of String
     */
    @Override
    public List<String> Save(Object objSituation) {
        Situation objInnerSituation = new Situation();
        objInnerSituation =  (Situation) objSituation;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_Situation(?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserID", objInnerSituation.getUserID());
            objCallableStatement.setInt("SituationCategoryID", objInnerSituation.getSituationCategoryID());
            objCallableStatement.setString("SituationDescription", objInnerSituation.getSituationDescription());
          
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
            Date dtDate = sdf.parse(objInnerSituation.getSituationDate());
            
            Timestamp tsDate = new Timestamp(dtDate.getYear(),dtDate.getMonth(), dtDate.getDate(), dtDate.getHours(), dtDate.getMinutes(), dtDate.getSeconds(), 00);
            objCallableStatement.setTimestamp("SituationDate", tsDate);
                        
            objCallableStatement.registerOutParameter("SituationID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intSituationID = objCallableStatement.getLong("SituationID");
            objDbResponse.add(String.valueOf(intSituationID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("situation saved successfully, User Details="+objSituation);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding situation");
        	objDbResponse.add("Error in adding situation");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for updating Situation. 
     * @param objSituation
     * @return List of String
     */
    @Override
    public List<String> Update(Object objSituation) {
        
        Situation objInnerSituation = new Situation();
        objInnerSituation =  (Situation) objSituation;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.[usp_Update_Situation](?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("SituationID", objInnerSituation.getSituationID());
            objCallableStatement.setLong("UserID", objInnerSituation.getUserID());
            objCallableStatement.setInt("SituationCategoryID", objInnerSituation.getSituationCategoryID());
            objCallableStatement.setString("SituationDescription", objInnerSituation.getSituationDescription());
          
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
            Date dtDate = sdf.parse(objInnerSituation.getSituationDate());
            
            Timestamp tsDate = new Timestamp(dtDate.getYear(),dtDate.getMonth(), dtDate.getDate(), dtDate.getHours(), dtDate.getMinutes(), dtDate.getSeconds(), 00);
            objCallableStatement.setTimestamp("SituationDate", tsDate);

            objCallableStatement.execute();
            
            Long intSituationID = objInnerSituation.getSituationID();
            objDbResponse.add(String.valueOf(intSituationID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("situation saved successfully, situation Details="+objSituation);
        }
        catch (Exception e)
        {
        	logger.info("Error in updating situation");
        	objDbResponse.add("Error in updating situation");
        } 
        return objDbResponse;
        
    }

    /**
     * This is implementation function for retrieving Situation.
     * @param objSituation
     * @return List of Situation 
     */
    @Override
    public List<Situation> RetriveData(Object objSituation) {
        
        Situation objOuterSituation = new Situation();
        List<Situation> objListInnerSituation = new ArrayList<Situation>();
        objOuterSituation =  (Situation) objSituation;
        
        try
        {
            CallableStatement objCallableStatement = null;
            if(objOuterSituation.getRequestType() == "ByUserOnly")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_SituationByUserID(?)}");
                objCallableStatement.setLong("UserID", objOuterSituation.getUserID());
            }
            else if(objOuterSituation.getRequestType() == "ByUserandDate")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_SituationByUserIDDate(?, ?, ?)}");
                
               SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
               Date dtStartDate = sdf.parse(objOuterSituation.getStartDate());
               Timestamp tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);

               Date dtEndDate =sdf.parse( objOuterSituation.getEndDate()); //.getTime();
               Timestamp tsEndDate = new Timestamp(dtEndDate.getYear(),dtEndDate.getMonth(), dtEndDate.getDate(), dtEndDate.getHours(), dtEndDate.getMinutes(),dtEndDate.getSeconds(),0);
            
                objCallableStatement.setLong("UserID", objOuterSituation.getUserID());
                objCallableStatement.setTimestamp("StartTime", tsStartDate);
                objCallableStatement.setTimestamp("EndTime", tsEndDate);
            }
            else if(objOuterSituation.getRequestType() == "BySituationID")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_SituationBySituationID(?)}");
                objCallableStatement.setLong("SituationID", objOuterSituation.getSituationID());
            }
            
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                Situation objInnerSituation = new Situation();
                objInnerSituation.setSituationID(objResultSet.getLong("SituationID"));
                objInnerSituation.setUserID(objResultSet.getLong("UserID"));
                objInnerSituation.setSituationCategoryID(objResultSet.getInt("SituationCategoryID"));
                objInnerSituation.setSituationDescription(objResultSet.getString("SituationDescription"));
                if(objResultSet.getTimestamp("SituationDate") != null)
                {
                    Timestamp tsSituationDate = objResultSet.getTimestamp("SituationDate");
                    objInnerSituation.setSituationDate(tsSituationDate.toString());
                }
                   
               objInnerSituation.setSituationCategoryDescription(objResultSet.getString("SituationCategoryDescription"));
               objListInnerSituation.add(objInnerSituation);
            }
            objConn.close();
            logger.info("situation loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading situation");
        }   
        return objListInnerSituation;
        
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf 
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/kc/Tables.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.kc;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author Taqdir
 */
public class Tables implements Serializable  {
    
    private int tableID;
    private String tableName;
    private List<Columns> objListColumns = new ArrayList<Columns>();

    /**
     * @return the tableID
     */
    public int getTableID() {
        return tableID;
    }

    /**
     * @param tableID the tableID to set
     */
    public void setTableID(int tableID) {
        this.tableID = tableID;
    }

    /**
     * @return the tableName
     */
    public String getTableName() {
        return tableName;
    }

    /**
     * @param tableName the tableName to set
     */
    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    /**
     * @return the objListColumns
     */
    public List<Columns> getObjListColumns() {
        return objListColumns;
    }

    /**
     * @param objListColumns the objListColumns to set
     */
    public void setObjListColumns(List<Columns> objListColumns) {
        this.objListColumns = objListColumns;
    }
    
    
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/MMDataCurationRestfulService/src/main/java/org/uclab/mm/rs/informationcuration/InformationCurationResource.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.rs.informationcuration;

import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.AbstractDataBridge;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.DatabaseStorage;
import org.uclab.mm.datamodel.ic.Device;
import org.uclab.mm.datamodel.ic.FoodLog;
import org.uclab.mm.datamodel.ic.UserDetectedLocation;
import org.uclab.mm.datamodel.ic.UserDevice;
import org.uclab.mm.datamodel.ic.UserPreferredLocation;
import org.uclab.mm.datamodel.ic.UserRecognizedActivity;
import org.uclab.mm.datamodel.ic.UserRecognizedActivityAccumulate;
import org.uclab.mm.datamodel.ic.UserRecognizedActivityLog;
import org.uclab.mm.datamodel.ic.UserRecognizedEmotion;
import org.uclab.mm.datamodel.ic.UserRecognizedHLC;
import org.uclab.mm.datamodel.ic.dataadapter.DeviceAdapter;
import org.uclab.mm.datamodel.ic.dataadapter.FoodLogAdapter;
import org.uclab.mm.datamodel.ic.dataadapter.UserDetectedLocationAdapter;
import org.uclab.mm.datamodel.ic.dataadapter.UserDeviceAdapter;
import org.uclab.mm.datamodel.ic.dataadapter.UserPreferredLocationAdapter;
import org.uclab.mm.datamodel.ic.dataadapter.UserRecognizedActivityAccumulateAdapter;
import org.uclab.mm.datamodel.ic.dataadapter.UserRecognizedActivityAdapter;
import org.uclab.mm.datamodel.ic.dataadapter.UserRecognizedActivityLogAdapter;
import org.uclab.mm.datamodel.ic.dataadapter.UserRecognizedEmotionAdapter;
import org.uclab.mm.datamodel.ic.dataadapter.UserRecognizedHLCAdapter;
import org.uclab.mm.rs.datacuration.DataCurationResource;

/**
 * REST Web Service
 *
 * @author <NAME>
 */
@Path("InformationCuration")
public class InformationCurationResource {

    @Context
    private UriInfo context;

    /**
     * Creates a new instance of InformationCurationResource
     */
    public InformationCurationResource() {
    }

    private static final Logger logger = LoggerFactory.getLogger(DataCurationResource.class);
    
    /**
     * This function is using to Register Device 
     * @param objOuterDevice
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("RegisterDevice")
    public List<String> RegisterDevice(Device objOuterDevice) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new DeviceAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveDevice(objOuterDevice);
            logger.info("Device saved successfully, Device Details="+objOuterDevice);
        }
        catch(Exception ex)
        {
        	logger.info("Error in registring Device");
        	response.add("Error in registering Device");
        }
        return response;
    }
    
    /**
     * This function is using to Update Device 
     * @param objOuterDevice
     * @return aa list of object string with "Error", "No Error" and updated ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UpdateDevice")
    public List<String> UpdateDevice(Device objOuterDevice) {
        
        List<String> response = new ArrayList<String>();
        String strResponse = "";
        try
        {
            DataAccessInterface objDAInterface = new DeviceAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.UpdateDevice(objOuterDevice);
            logger.info("Device updated successfully, Device Details="+objOuterDevice);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updated Device");
        	response.add("Error in updated Device");
        }
        return response;
    }
    
     /**
     * This function is using to Retrieves Device by DeviceID 
     * @param DeviceID
     * @return an instance of list of Device
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("Device/{DeviceID}")
    public List<Device> GetDevice(@PathParam ("DeviceID") String DeviceID) {
        Device objOuterDevice = new Device();
        List<Device> objListDevice = new  ArrayList<Device>();
        try
        {
            objOuterDevice.setDeviceId(Long.parseLong(DeviceID));
        
            DataAccessInterface objDAInterface = new DeviceAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListDevice = objADBridge.RetriveDevice(objOuterDevice);
            logger.info("Device loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in Device loadeding");
        }
        return objListDevice;
    }
    

   /**
     * This function is using to Register Device for user.
     * @param objOuterUserDevice
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("SubscribeUserDevice")
    public List<String> SubscribeUserDevice(UserDevice objOuterUserDevice) {
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserDeviceAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveUserDevice(objOuterUserDevice);
            logger.info("Device registered successfully, User Details="+objOuterUserDevice);

        }
        catch(Exception ex)
        {
        	logger.info("Error in registering Device");
        	response.add("Error in registering Device");
        }
        return response;
    }
    
     /**
     * This function is using to subscribe the sensors of interest.
     * @param objListUserDevice
     * @return an object of string
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("subscribeToSensorsOfInterest")
    public List<String> subscribeToSensorsOfInterest(List<UserDevice> objListUserDevice) {
        List<String> response = new ArrayList<String>();
        try{
                
            UserDevice objUserDevice = new UserDevice();
            for(int i = 0; i < objListUserDevice.size(); i++)
            {
                objUserDevice = objListUserDevice.get(i);
                DataAccessInterface objDAInterface = new UserDeviceAdapter();
                AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
                response = objADBridge.UpdateUserDevice(objUserDevice);
            }
            logger.info("Sensor subscribed successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in subscribing sensor");
        	response.add("Error in subscribing sensor");
        }
        return response;
    }
    
    /**
     * This function is using to Update User Device 
     * @param objOuterUserDevice
     * @return a list of object string with "Error", "No Error" and updated ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UpdateUserDevice")
    public List<String> UpdateUserDevice(UserDevice objOuterUserDevice) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserDeviceAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.UpdateUserDevice(objOuterUserDevice);
            logger.info("User Device Updated successfully,  User Device Details="+objOuterUserDevice);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating  User Device");
        	response.add("Error in updating  User Device");
        }
        
        return response;
    }
    
    /**
     * This function is using to Retrieves User Device by UserDeviceID 
     * @param UserDeviceID
     * @return an instance of list of UserDevice
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UserDevice/{UserDeviceID}")
    public List<UserDevice> GetUserDevice(@PathParam ("UserDeviceID") String UserDeviceID) {
        UserDevice objOuterUserDevice = new UserDevice();
        List<UserDevice> objListUserDevice = new  ArrayList<UserDevice>();
        try
        {
            objOuterUserDevice.setUserDeviceID(Long.parseLong(UserDeviceID));
        
            DataAccessInterface objDAInterface = new UserDeviceAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserDevice = objADBridge.RetriveUserDevice(objOuterUserDevice);
            logger.info("User device loaded successfully.");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading user device");
        }
        return objListUserDevice;
    }
    
    /**
     * This function is using to Add user recognized activities 
     * @param objOuterUserRecognizedActivity
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddUserRecognizedActivity")
    public List<String> AddUserRecognizedActivity(UserRecognizedActivity objOuterUserRecognizedActivity) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserRecognizedActivityAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveUserRecognizedActivity(objOuterUserRecognizedActivity);
            logger.info("user recognized activities saved successfully, user recognized activities Details="+objOuterUserRecognizedActivity);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding  user recognized activities");
        	response.add("Error in adding user recognized activities");
        }
        return response;
    }
    
    /**
     * This function is using to  Retrieves users recognized activities by userid, start time and end time
     * @param objOuterUserRecognizedActivity
     * @return an instance of list of UserRecognizedActivity
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("GetUserRecognizedActivity")
    public List<UserRecognizedActivity> GetUserRecognizedActivity(UserRecognizedActivity objOuterUserRecognizedActivity) {
        
        List<UserRecognizedActivity> objListUserRecognizedActivity = new ArrayList<UserRecognizedActivity>();
        String strResponse = "";
        objOuterUserRecognizedActivity.setRequestType("UserDateRange");
        try
        {
            DataAccessInterface objDAInterface = new UserRecognizedActivityAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserRecognizedActivity = objADBridge.RetriveUserRecognizedActivity(objOuterUserRecognizedActivity);
            logger.info("users recognized activities successfully loaded");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading users recognized activities");
        }
        return objListUserRecognizedActivity;
    }
    
    /**
     * This function is using to Retrieves users accumulative recognized activities by userid, start time and end time
     * @param objOuterUserRecognizedActivity
     * @return an instance of list of UserRecognizedActivity
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("GetUserRecognizedActivityAccumulate")
    public List<UserRecognizedActivity> GetUserRecognizedActivityAccumulate(UserRecognizedActivity objOuterUserRecognizedActivity) {
        
        List<UserRecognizedActivity> objListUserRecognizedActivity = new ArrayList<UserRecognizedActivity>();
        String strResponse = "";
        objOuterUserRecognizedActivity.setRequestType("UserDateRangeAccumulate");
        try
        {
            DataAccessInterface objDAInterface = new UserRecognizedActivityAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserRecognizedActivity = objADBridge.RetriveUserRecognizedActivity(objOuterUserRecognizedActivity);
            logger.info("users recognized accumulative activities successfully loaded");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading users recognized accumulative activities");
        }
        return objListUserRecognizedActivity;
    }
    
    
     /**
     * This function is using to Add User Detected Location
     * @param objOuterUserDetectedLocation
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddUserDetectedLocation")
    public List<String> AddUserDetectedLocation(UserDetectedLocation objOuterUserDetectedLocation) {
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserDetectedLocationAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveUserDetectedLocation(objOuterUserDetectedLocation);
            logger.info("User Detected Location saved successfully, User Detected Location Details="+objOuterUserDetectedLocation);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding User Detected Location");
        	response.add("Error in adding User Detected Location");
        }
        return response;
    }
    
    /**
     * This function is using to Retrieves User Detected Location by userid, start time and end time
     * @param objOuterUserDetectedLocation
     * @return an instance of list of UserDetectedLocation
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("GetUserDetectedLocation")
    public List<UserDetectedLocation> GetUserDetectedLocation(UserDetectedLocation objOuterUserDetectedLocation) {
        
        List<UserDetectedLocation> objListUserDetectedLocation = new ArrayList<UserDetectedLocation>();
        objOuterUserDetectedLocation.setRequestType("UserDateRange");
        try
        {
            DataAccessInterface objDAInterface = new UserDetectedLocationAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserDetectedLocation = objADBridge.RetriveUserDetectedLocation(objOuterUserDetectedLocation);
            logger.info("User Detected Location laoded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading User Detected Location");
        }
        
        return objListUserDetectedLocation;
    }
    
    /**
     * This function is using to Add user recognized activities Log
     * @param objOuterUserRecognizedActivityLog
     * @return  a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddUserRecognizedActivityLog")
    public List<String> AddUserRecognizedActivityLog(UserRecognizedActivityLog objOuterUserRecognizedActivityLog) {
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserRecognizedActivityLogAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveUserRecognizedActivityLog(objOuterUserRecognizedActivityLog);
            logger.info("user recognized activities Log saved successfully, User Details="+objOuterUserRecognizedActivityLog);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding user recognized activities Log");
        	response.add("Error in adding user recognized activities Log");
        }
        return response;
    }
    
    /**
     * This function is using to Retrieves users recognized activities log by userid, start time and end time
     * @param objOuterUserRecognizedActivityLog
     * @return an instance of list of UserRecognizedActivityLog
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("GetUserRecognizedActivityLog")
    public List<UserRecognizedActivityLog> GetUserRecognizedActivityLog(UserRecognizedActivityLog objOuterUserRecognizedActivityLog) {
        List<UserRecognizedActivityLog> objListUserRecognizedActivityLog = new ArrayList<UserRecognizedActivityLog>();
        try
        {
            DataAccessInterface objDAInterface = new UserRecognizedActivityLogAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserRecognizedActivityLog = objADBridge.RetriveUserRecognizedActivityLog(objOuterUserRecognizedActivityLog);
            logger.info("users recognized activities log laoded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading users recognized activities log");
        }
        return objListUserRecognizedActivityLog;
    }
    
    /**
     * This function is using to Add User Recognized Activity Accumulate
     * @param objOuterUserRecognizedActivityAccumulate
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddUserRecognizedActivityAccumulateForNotCalling")
    public List<String> AddUserRecognizedActivityAccumulateForNotCalling(UserRecognizedActivityAccumulate objOuterUserRecognizedActivityAccumulate) {
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserRecognizedActivityAccumulateAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveUserRecognizedActivityAccumulate(objOuterUserRecognizedActivityAccumulate);
            logger.info("User Recognized Activity Accumulate saved successfully, User Details="+objOuterUserRecognizedActivityAccumulate);        
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding User Recognized Activity Accumulate");
        	response.add("Error in adding User Recognized Activity Accumulate");
        }
        return response;
    }
    
    /**
     * This function is using to Update User Recognized Activity Accumulate
     * @param objOuterUserRecognizedActivityAccumulate
     * @return  a list of object string with "Error", "No Error" and updated ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UpdateUserRecognizedActivityAccumulate")
    public List<String> UpdateUserRecognizedActivityAccumulate(UserRecognizedActivityAccumulate objOuterUserRecognizedActivityAccumulate) {
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserRecognizedActivityAccumulateAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.UpdateUserRecognizedActivityAccumulate(objOuterUserRecognizedActivityAccumulate);
            logger.info("Recognized Activity Accumulate updated successfully, User Details="+objOuterUserRecognizedActivityAccumulate);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating Recognized Activity Accumulate");
        	response.add("Error in updating Recognized Activity Accumulate");
        }
        return response;
    }
    
    /**
     * This function is using to Retrieves User Recognized Activity Accumulate by userid, start time and end time
     * @param objOuterUserRecognizedActivityAccumulate
     * @return an instance of list of UserRecognizedActivityAccumulate
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("GetUserRecognizedActivityAccumulateByUserAndDate")
    public List<UserRecognizedActivityAccumulate> GetUserRecognizedActivityAccumulateByUserAndDate(UserRecognizedActivityAccumulate objOuterUserRecognizedActivityAccumulate) {
        List<UserRecognizedActivityAccumulate> objListUserRecognizedActivityAccumulate = new ArrayList<UserRecognizedActivityAccumulate>();
        objOuterUserRecognizedActivityAccumulate.setRequestType("UserOneDate");
        try
        {
            DataAccessInterface objDAInterface = new UserRecognizedActivityAccumulateAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserRecognizedActivityAccumulate = objADBridge.RetriveUserRecognizedActivityAccumulate(objOuterUserRecognizedActivityAccumulate);
            logger.info("Recognized Activity Accumulate are loaded successfully.");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Recognized Activity Accumulate");
        }
        return objListUserRecognizedActivityAccumulate;
    }
    
    /**
     * This function is using to Retrieves User Recognized Activity Accumulate by userid, start time and end time
     * @param objOuterUserRecognizedActivityAccumulate
     * @return an instance of list of UserRecognizedActivityAccumulate
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("GetUserRecognizedActivityAccumulateByUserAndDateRange")
    public List<UserRecognizedActivityAccumulate> GetUserRecognizedActivityAccumulateByUserAndDateRange(UserRecognizedActivityAccumulate objOuterUserRecognizedActivityAccumulate) {
        
        List<UserRecognizedActivityAccumulate> objListUserRecognizedActivityAccumulate = new ArrayList<UserRecognizedActivityAccumulate>();
        objOuterUserRecognizedActivityAccumulate.setRequestType("UserDateRange");
        try
        {
            DataAccessInterface objDAInterface = new UserRecognizedActivityAccumulateAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserRecognizedActivityAccumulate = objADBridge.RetriveUserRecognizedActivityAccumulate(objOuterUserRecognizedActivityAccumulate);
            logger.info("Recognized Activity Accumulate are loaded successfully.");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Recognized Activity Accumulate");
        }
        return objListUserRecognizedActivityAccumulate;
    }
    
    /**
     * This function is using to Retrieves User Recognized Activity Accumulate by ActivitiesID, start time and end time
     * @param objOuterUserRecognizedActivityAccumulate
     * @return an instance of list of UserRecognizedActivityAccumulate
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("GetUserRecognizedActivityAccumulateByActivitiesAndDateRange")
    public List<UserRecognizedActivityAccumulate> GetUserRecognizedActivityAccumulateByActivitiesAndDateRange(UserRecognizedActivityAccumulate objOuterUserRecognizedActivityAccumulate) {
        List<UserRecognizedActivityAccumulate> objListUserRecognizedActivityAccumulate = new ArrayList<UserRecognizedActivityAccumulate>();
        objOuterUserRecognizedActivityAccumulate.setRequestType("ActivitiesDateRange");
        try
        {
            DataAccessInterface objDAInterface = new UserRecognizedActivityAccumulateAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserRecognizedActivityAccumulate = objADBridge.RetriveUserRecognizedActivityAccumulate(objOuterUserRecognizedActivityAccumulate);
            logger.info("Recognized Activity Accumulate are loaded successfully.");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Recognized Activity Accumulate");
        }
        return objListUserRecognizedActivityAccumulate;
    }
    
    /**
     *This function is using to  Add User Recognized Emotion
     * @param objOuterUserRecognizedEmotion
     * @return an object of string
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddUserRecognizedEmotion")
    public List<String> AddUserRecognizedEmotion(UserRecognizedEmotion objOuterUserRecognizedEmotion) {
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserRecognizedEmotionAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveUserRecognizedEmotion(objOuterUserRecognizedEmotion);
            logger.info("User Recognized Emotion saved successfully, User Recognized Emotion Details="+objOuterUserRecognizedEmotion);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding User Recognized Emotion");
        	response.add("Error in adding User Recognized Emotion");
        }
        return response;
    }
    
    /**
     * This function is using to Retrieves User Recognized emotion by userid, start time and end time
     * @param objOuterUserRecognizedEmotion
     * @return an instance of list of UserRecognizedEmotion
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("GetUserRecognizedEmotionByUserIDDateRange")
    public List<UserRecognizedEmotion> GetUserRecognizedEmotionByUserIDDateRange(UserRecognizedEmotion objOuterUserRecognizedEmotion) {
        
        List<UserRecognizedEmotion> objListUserRecognizedEmotion = new ArrayList<UserRecognizedEmotion>();
        objOuterUserRecognizedEmotion.setRequestType("UserDateRange");
        String strResponse = "";
        try
        {
            DataAccessInterface objDAInterface = new UserRecognizedEmotionAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserRecognizedEmotion = objADBridge.RetriveUserRecognizedEmotion(objOuterUserRecognizedEmotion);
            logger.info("User Recognized emotion are loaded successfully.");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading User Recognized emotion");
        }
        return objListUserRecognizedEmotion;
    }
    
    /**
     * This function is using to Add User Recognized HighLC
     * @param objOuterUserRecognizedHLC
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddUserRecognizedHLC")
    public List<String> AddUserRecognizedHLC(UserRecognizedHLC objOuterUserRecognizedHLC) {
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserRecognizedHLCAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveUserRecognizedHLC(objOuterUserRecognizedHLC);
            logger.info("User Recognized HighLC saved successfully, User Recognized HighLC Details="+objOuterUserRecognizedHLC);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding User Recognized HighLC");
        	response.add("Error in adding User Recognized HighLC");
        }
        return response;
    }
    
    /**
     * This function is using to Retrieves User Recognized HLC by userid, start time and end time
     * @param objOuterUserRecognizedHLC
     * @return an instance of list of UserRecognizedHLC
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("GetUserRecognizedHLCByUserIDDateRange")
    public List<UserRecognizedHLC> GetUserRecognizedHLCByUserIDDateRange(UserRecognizedHLC objOuterUserRecognizedHLC) {
        List<UserRecognizedHLC> objListUserRecognizedHLC = new ArrayList<UserRecognizedHLC>();
        objOuterUserRecognizedHLC.setRequestType("UserDateRange");
        try
        {
            DataAccessInterface objDAInterface = new UserRecognizedHLCAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserRecognizedHLC = objADBridge.RetriveUserRecognizedHLC(objOuterUserRecognizedHLC);
            logger.info("User Recognized HLC are loaded successfully.");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading User Recognized HLC");
        }
        return objListUserRecognizedHLC;
    }
    
    /**
     * This function is using to Add User Preferred Location
     * @param objOuterUserPreferredLocation
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddUserPreferredLocation")
    public List<String> AddUserPreferredLocation(UserPreferredLocation objOuterUserPreferredLocation) {
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserPreferredLocationAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveUserPreferredLocation(objOuterUserPreferredLocation);
            logger.info("User Preferred Location saved successfully, User Details="+objOuterUserPreferredLocation);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding User Preferred Location");
        	response.add("Error in adding User Preferred Location");
        }
        return response;
    }
    
    /**
     * This function is using to Update User Preferred Location
     * @param objOuterUserPreferredLocation
     * @return a list of object string with "Error", "No Error" and updated ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UpdateUserPreferredLocation")
    public List<String> UpdateUserPreferredLocation(UserPreferredLocation objOuterUserPreferredLocation) {
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserPreferredLocationAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.UpdateUserPreferredLocation(objOuterUserPreferredLocation);
            logger.info(" User Preferred Location saved successfully,  User Preferred Location Details="+objOuterUserPreferredLocation);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating  User Preferred Location");
        	response.add("Error in updating  User Preferred Location");
        }
        return response;
    }
    
    /**
     * This function is using to Retrieves users preferred location by UserID 
     * @param UserID
     * @return an instance of list of UserPreferredLocation
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UserPreferredLocation/{UserID}")
    public List<UserPreferredLocation> GetUserPreferredLocation(@PathParam ("UserID") String UserID) {
        UserPreferredLocation objOuterUserPreferredLocation = new UserPreferredLocation();
        List<UserPreferredLocation> objListUserPreferredLocation = new  ArrayList<UserPreferredLocation>();
        try
        {
            objOuterUserPreferredLocation.setUserId(Long.parseLong(UserID));
            DataAccessInterface objDAInterface = new UserPreferredLocationAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserPreferredLocation = objADBridge.RetriveUserPreferredLocation(objOuterUserPreferredLocation);
            logger.info("users preferred location loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading  users preferred location");
        }
        return objListUserPreferredLocation;
    }
    
    /**
     * This function is using to Retrieves food log by userid, start time and end time
     * @param objOuterFoodLog
     * @return an instance of list of FoodLog
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("GetFoodLogByUserIDDateRange")
    public List<FoodLog> GetFoodLogByUserIDDateRange(FoodLog objOuterFoodLog) {
        List<FoodLog> objListFoodLog = new ArrayList<FoodLog>();
        try
        {
            DataAccessInterface objDAInterface = new FoodLogAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListFoodLog = objADBridge.RetriveFoodLog(objOuterFoodLog);
            logger.info("food log loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading  food log");
        }
        return objListFoodLog;
    }
    
     /**
     * This function is using to Add food log
     * @param objOuterFoodLog
     * @return an object of string
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddFoodLog")
    public List<String> AddFoodLog(FoodLog objOuterFoodLog) {
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new FoodLogAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveFoodLog(objOuterFoodLog);
            logger.info("food log saved successfully, food log Details="+objOuterFoodLog);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding food log");
        	response.add("Error in adding food log");
        }
        return response;
    }
}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/communication/DCRiskFactorsWSClient.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.communication;

import java.util.List;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.uclab.scl.datamodel.RiskFactors;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
/**
 * @version MM v2.5
 * @author Afzal
 *
 */
public class DCRiskFactorsWSClient extends
    AbstractRestClient<List<RiskFactors>, String> {

  public DCRiskFactorsWSClient(String baseURI) {
    super(baseURI);
  }

  @Override
  public List<RiskFactors> GetData(String getResourceURI) {
    ClientConfig config = new DefaultClientConfig();
    config.getClasses().add(JacksonJsonProvider.class);
    Client client = Client.create(config);
    WebResource service = client.resource(UriBuilder.fromUri(baseURI).build());
    List<RiskFactors> riskFactors = 
        service.path(getResourceURI).accept(MediaType.APPLICATION_JSON).get(new GenericType<List<RiskFactors>>() {});
    if (riskFactors.size() > 0)
      return riskFactors;
    else
      return null;
  }

  @Override
  public String PostData(String postResourceURI, List<RiskFactors> postedResource) {
    throw new UnsupportedOperationException("Not supported yet.");
  }

}


<|start_filename|>knowledge-curation-layer/DDKAT/target/DDKAT/WEB-INF/views/modellearner.jsp<|end_filename|>
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<HTML><HEAD><TITLE>Data Driven Knowledge Acquisition</TITLE>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<link href="css/ddka-interface.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/bootstrap.min.js" ></script>
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"> 

<script language="javascript">

$(document).ready(function(){
	
	document.getElementById("learnmodel_btn").disabled = true;
	document.getElementById("translatemodel_btn").disabled = true;
	
	$('#algolist li').on('click', function(){
	    $('#algotxtbox').val($(this).text());
	    var algo = $("#algotxtbox").val();
	    var selectedAlgoHTML='<br><br><font size="3" color="#004584"><b>Algorithm Selected for Model Learning : </b></font><font size="3" color="red"><b>'+algo+'</b></font><br><br>';
	    document.getElementById("ManualSelectedAlgorithmDiv").innerHTML = selectedAlgoHTML;
	    document.getElementById("learnmodel_btn").disabled = false;
	});
	
	
	$("#autoalgorithmselector_btn").click(function () {
		
		$.ajaxSetup({
			contentType: "application/json; charset=utf-8"
			});
		
		var request = $.ajax({
			url: "autoalgoselection",
			type: "POST",
			dataType: "json",
			success : function(response) {
				var tabletitleHTML='<b><font size="4" color="#004584">Top (k=3) Recommended Algorithms</font></b><br/><br/>';
			   	var tableHTML=''; 
				var headerrowHTML='<tr><td style="border-style: solid; border-width: 1px" vertical-align:middle" align="center"><font face="Times New Roman" size="3" color="#FF9900"><b>Rank</b></font></td>';
				headerrowHTML+='<td style="border-style: solid; border-width: 1px" vertical-align:middle" align="center"><font face="Times New Roman" size="3" color="#FF9900"><b>Case ID</b></font></td>';
				headerrowHTML+='<td style="border-style: solid; border-width: 1px" vertical-align:middle" align="center"><font face="Times New Roman" size="3" color="#FF9900"><b>Algorithm</b></font></td>';
				headerrowHTML+='<td style="border-style: solid; border-width: 1px" vertical-align:middle" align="center"><font face="Times New Roman" size="3" color="#FF9900"><b>Similarity Score</b></font></td></tr>';
			   	var datarowsHTML='';
			   	var rowcounter = 0;
			   	while(rowcounter < response.autoSelectedAlgos.length){
			   		datarowsHTML+='<tr>';
			   		datarowsHTML+='<td style="border-style: solid; border-width: 1px; vertical-align:middle" width="5%" align="center"><font face="Times New Roman" size="3" color="#004584">' + (rowcounter+1) + '</font></td>';
			   		datarowsHTML+='<td style="border-style: solid; border-width: 1px; vertical-align:middle" width="15%" align="center"><font face="Times New Roman" size="3" color="#004584">' + response.caseIDs[rowcounter] + '</font></td>';
			   		datarowsHTML+='<td style="border-style: solid; border-width: 1px; vertical-align:middle" width="15%" align="center"><font face="Times New Roman" size="3" color="#004584">' + response.autoSelectedAlgos[rowcounter] + '</font></td>';
			   		datarowsHTML+='<td style="border-style: solid; border-width: 1px; vertical-align:middle" width="15%" align="center"><font face="Times New Roman" size="3" color="#004584">' + response.similarityScores[rowcounter] + '</font></td>';
					datarowsHTML+='</tr>';
			   		rowcounter++;
			   		}		    		    			   	
			   	tableHTML = tabletitleHTML + '<table border="2" width="100%" style="width: 40%" bordercolor="#004584">' + headerrowHTML + datarowsHTML + '</table>';
			   	document.getElementById("SimilarCasesDiv").innerHTML = tableHTML;
		
			 	var autoselectedalgotableHTML='<font size="5" color="#004584"><b>Best Recommended Algorithm : </b></font><font size="5" color="red"><b>' + response.autoSelectedAlgos[0] + '</b></font>';
				document.getElementById("MachineSelectedAlgorithmDiv").innerHTML = autoselectedalgotableHTML; 						
				},
			error: function(errorThrown) {
				alert("error : " + errorThrown.responseText);
				}
				
			});
		});	
	
	
	$("#learnmodel_btn").click(function () {
		
		$.ajaxSetup({
			contentType: "application/json; charset=utf-8"
			});
		
		var algo = $("#algotxtbox").val();
		$("#algoTxtAreaVal").val(algo);
		var request = $.ajax({
		url: "learnmodel",
		type: "POST",
		data: algo,
		dataType: "json",
		success : function(response) {
			var accuracytableHTML='<br><br><b><font size="5" color="#004584">Accuracy of Classification Model</font></b><br/><br/>';
			accuracytableHTML=accuracytableHTML+'<font size="3" color="#004584"><b>Original Data Accuracy : </b></font><font size="3" color="red"><b>' + response.modelAccuracies[0] + '</b></font><br><br>';
			accuracytableHTML=accuracytableHTML+'<font size="3" color="#004584"><b>Processed Data Accuracy : </b></font><font size="3" color="red"><b>' + response.modelAccuracies[1] + '</b></font><br><br>';
			document.getElementById("ModelAccuraciesDiv").innerHTML = accuracytableHTML;
			
			$("#decisionattributeTxtAreaVal").val(response.decisionAttribute);
			$("#modelStringTxtAreaVal").val(response.modelString);
						
			},
		error: function(errorThrown) {
			alert("error : " + errorThrown.responseText);
			}
			
			});		

		document.getElementById("translatemodel_btn").disabled = false;
		
	});	
	
     
    $("#translatemodel_btn").click(function () {
    	   	
		var algo = $("#algoTxtAreaVal").val();
		$("#algoVar").val(algo);
		var decisionattribute = $("#decisionattributeTxtAreaVal").val();
		$("#decisionattributeVar").val(decisionattribute);
		var modelstring = $("#modelStringTxtAreaVal").val();
		$("#modelstringVar").val(modelstring);
		   		
		$.ajaxSetup({
			contentType: "application/json; charset=utf-8"
			});
		    	
 			var request = $.ajax({
			url: "modeltranslator",
			type: "POST",
			data: algo+"#####"+decisionattribute+"#####"+modelstring,
			dataType: "json",
			success : function(response) {
				var tabletitleHTML='<b><font size="5" color="#004584">Rules extracted from Classification Model</font></b><br/><br/>';
			   	var tableHTML=''; 
				var headerrowHTML='<tr><td style="border-style: solid; border-width: 1px" vertical-align:middle" align="center"><font face="Times New Roman" size="3" color="#FF9900"><b>Rule ID</b></font></td>';
			   	headerrowHTML+='<td style="border-style: solid; border-width: 1px" vertical-align:middle" align="center"><font face="Times New Roman" size="3" color="#FF9900"><b>Conditions</b></font></td>';
			   	headerrowHTML+='<td style="border-style: solid; border-width: 1px" vertical-align:middle" align="center"><font face="Times New Roman" size="3" color="#FF9900"><b>Conclusion</b></font></td></tr>';
			   	var datarowsHTML='';
			   	var rowcounter = 0;
			   	while(rowcounter < response.ruleConditions.length){
			   		datarowsHTML+='<tr>';
			   		datarowsHTML+='<td style="border-style: solid; border-width: 1px; vertical-align:middle" width="10%" align="center"><font face="Times New Roman" size="3" color="#004584">' + (rowcounter+1) + '</font></td>';
			   		datarowsHTML+='<td style="border-style: solid; border-width: 1px; vertical-align:middle" width="55%" align="center"><font face="Times New Roman" size="3" color="#004584">' + response.ruleConditions[rowcounter] + '</font></td>';		  
			   		datarowsHTML+='<td style="border-style: solid; border-width: 1px; vertical-align:middle" width="20%" align="center"><font face="Times New Roman" size="3" color="#004584">' + response.ruleConclusions[rowcounter] + '</font></td>';
				   	datarowsHTML+='</tr>';
			   		rowcounter++;
			   		}				    			   	
			   	tableHTML = tabletitleHTML + '<table border="2" width="100%" style="width: 60%" bordercolor="#004584">' + headerrowHTML + datarowsHTML + '</table>';
			   	document.getElementById("ExtractedRulesDiv").innerHTML = tableHTML;
				},
			error: function(errorThrown) {
				alert("error : " + e.responseText);
				}
 			});
 			
		});

});
</script>
</HEAD>
<BODY>

<TABLE id=header cellPadding=0 style="width: 100%">
  <TBODY>
  <TR>
    <TD align="left" class="style1">
	<img border="0" src="images/banner.jpg" height="106"></TD>
    <TD align="right" style="width: 30%">
	<img border="0" src="images/MM_logo.png" height="106"></TD>
    </TR></TBODY></TABLE>
<TABLE cellPadding=0>
  <TBODY>
  <TR>
    <TD id=tran1></TD></TR>
  <TR>
    <TD id=tran2 height="171"></TD></TR></TBODY></TABLE>
<TABLE id=menubar cellPadding=0>
  <TBODY>
  <TR>
    <TD>
     <TABLE style="WIDTH: 100%" cellSpacing=0 cellPadding=0 border=0>
        <TBODY>
        <TR>
          <TD align=right>
          <a href="index.jsp">
		  <img border="0" src="images/main.gif" height="21"></a>
          </TD>
		  </TR></TBODY></TABLE></TD></TR></TBODY></TABLE>
		  
		  
<TABLE id=main cellPadding=0 width="777" style="width: 100%">
  <TBODY>
  <TR>
    <TD id=leftMenu width="654" rowspan="2">
                 &nbsp;</TD>
    </TR></TBODY></TABLE>
    
    <TABLE align=center border=2 borderColor=#39597d width="82%">
              <TBODY>
              <TR>
                <TD>
        <br><br>
		<div align="center">
		    <font size="5" color="#004584"><b>Model Learner</b></font><br><br><br>
		    <p class="bg-info"><b>For Automatic Algorithm Selection, click <font color="#004584"><i>'Automatic Algorithm Selector'</i></font> button.</b></p>
		    <br>
			<button id="autoalgorithmselector_btn" class="btn btn-primary" type="button"><span class="glyphicon glyphicon-asterisk"></span> Automatic Algorithm Selector</button>
		    <br><br><div id="SimilarCasesDiv" align="center" style="border: 0px #d3d3d3 solid;"></div>
			<br><br><div id="MachineSelectedAlgorithmDiv" align="center" style="border: 0px #d3d3d3 solid;"><br/></div><br/>
			<br><br>
		    <p class="bg-info"><b>For creating Classification Model, choose the decision tree algorithm from list and then click  <font color="#004584"><i>'Learn Model'</i></font> button.</b></p>
		    <br>
			
			<div class = "btn-group">
			   <button id="algobtn" type = "button" class = "btn btn-primary dropdown-toggle" data-toggle = "dropdown"><span class="glyphicon glyphicon-check"></span> 
			      Choose Decision Tree Algorithm 
			      <span class = "caret"></span>
			   </button>
			   <ul id="algolist" class = "dropdown-menu" role = "menu">
			      <li><a>BFTree</a></li>
			      <li><a>FT</a></li>
			      <li><a>J48</a></li>
			      <li><a>J48graft</a></li>
			      <li><a>RandomTree</a></li>
			      <li><a>REPTree</a></li>
			      <li><a>SimpleCart</a></li>
			   </ul>
			</div>
			<div id="ManualSelectedAlgorithmDiv" align="center" style="border: 0px #d3d3d3 solid;"><br/></div><br/>
			<br>
		    <button id="learnmodel_btn" class="btn btn-primary" type="button"><span class="glyphicon glyphicon-cog"></span> Learn Model</button>
		    <div id="ModelAccuraciesDiv" align="center" style="border: 0px #d3d3d3 solid;"></div>
			<br><br>
  			
		    <p class="bg-info"><b>For extracting rules from Classification Model and sharing with expert, click  <font color="#004584"><i>'Translate Model'</i></font> button.</b></p>
		    <br>
			<form method="POST" name='modelTranslationForm' action="modeltranslation">
				<button id="translatemodel_btn" class="btn btn-primary" type="button"><span class="glyphicon glyphicon-cog"></span> Translate Model</button>
				<input type="hidden" id="algoVar" name="algoVar" />
				<input type="hidden" id="decisionattributeVar" name="decisionattributeVar" />
				<input type="hidden" id="modelstringVar" name="modelstringVar" />
  			</form>
		</div>
		<br/><br/>
		<div class="row">
		<div id="ExtractedRulesDiv" align="center" style="border: 0px #d3d3d3 solid;"><br/></div>
		</div>
	     <input type="TextBox" ID="algotxtbox" Class="form-control" style="visibility: hidden"></input>
	     <textarea id="algoTxtAreaVal" style="visibility: hidden"></textarea>
	    <textarea id="decisionattributeTxtAreaVal" style="visibility: hidden"></textarea>
	    <textarea id="modelStringTxtAreaVal" style="visibility: hidden"></textarea>
	    </TD></TR></TBODY></TABLE>

    <table align="center" style="width: 100%">
           <tr>
		<td style="width: 100%; text-align:center">
		<font size="1" color="#39597B">
        <script language="JavaScript">
            copyright = new Date();
            currentYear = copyright.getFullYear();
            document.write("�" + currentYear + "Ubiquitous Computing Lab., Dept. of Computer Engg.");
            </script>
            </font></td>
	</tr>
	<tr>
		<td style="width: 100%; text-align:center">
		<font size="1" color="#39597B">Kyung Hee University, Korea</font></td>
	</tr>
	      
                </table>
                </BODY>

</HTML>

<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/objectmodel/VoilationNotification.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */

package org.uclab.mm.dcl.llm.objectmodel;

import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.uclab.mm.dcl.llm.dataaccess.DBConnection;

/**
 * This class provides the access to details of different kind of violations in
 * term of respective user id, log id and violations details.
 * @author Rizvi
 */
public class VoilationNotification implements Serializable{

  private List<Violations> listViolations = new ArrayList<Violations>();
  /**
   * The function provides the 10 latest violation of users either physical or nutrition based on abnormal conditions identified.
   * select top 10 
   * ActivityID,
   * ActivityTargetDuration, 
   * RecordedTime,
   * Log_Id, 
   * UserID 
   * from tbllog_CurrentLifeLog 
   * where ActivityStatus!='NM'
   * order by RecordedTime desc;
   * 
   */
  
  public List<Violations> getViolations(){
    Connection conn = null;
    
    try{
      conn = DBConnection.getDBConnection().getConnection();
      CallableStatement callableStatement = conn.prepareCall("{call usp_GetTopViolations()}");
      ResultSet rs = callableStatement.executeQuery();

      if (rs != null){
        while (rs.next()){
          String UserID = rs.getString("UserID");
          String ActivityID = rs.getString("ActivityID");
          String StartTime = rs.getString("RecordedTime");
          String ActivityTargetDuration = rs.getString("ActivityTargetDuration");
          String LogID = rs.getString("Log_Id");
          Violations objViolations = new Violations();
          objViolations.setActivityID(ActivityID);
          objViolations.setActivityTargetDuration(ActivityTargetDuration);
          objViolations.setStartTime(StartTime);
          objViolations.setLogID(LogID);
          objViolations.setUserID(UserID);
          listViolations.add(objViolations);
        }
      }
    } catch (Exception e){
      StringWriter errors = new StringWriter();
      e.printStackTrace(new PrintWriter(errors));
    }
    return listViolations;
  }

  /**
   * The function provides the 10 latest violation of users other than previously shown, either physical or nutrition based on abnormal conditions identified.
   * select top 10 ActivityID,
   * ActivityTargetDuration,
   * RecordedTime,
   * Log_Id,
   * UserID from
   * tbllog_CurrentLifeLog 
   * where ActivityStatus!='NM' and Log_id> maxlgid 
   * order by RecordedTime desc;
   *
   * @param maxlgid
   * @return
   */
  public List<Violations> getMaxViolations(String maxlgid){
    Connection conn = null;
    try{
      conn = DBConnection.getDBConnection().getConnection();
      CallableStatement callableStatement = conn.prepareCall("{call usp_GetMaxViolationsLog( " + maxlgid + ")}");
      ResultSet rs = callableStatement.executeQuery();

      if (rs != null){
        while (rs.next()){
          String UserID = rs.getString("UserID");
          String ActivityID = rs.getString("ActivityID");
          String StartTime = rs.getString("RecordedTime");
          String ActivityTargetDuration = rs.getString("ActivityTargetDuration");
          String LogID = rs.getString("Log_Id");
          Violations objViolations = new Violations();
          objViolations.setActivityID(ActivityID);
          objViolations.setActivityTargetDuration(ActivityTargetDuration);
          objViolations.setStartTime(StartTime);
          objViolations.setLogID(LogID);
          objViolations.setUserID(UserID);
          listViolations.add(objViolations);
        }
      }
    } catch (Exception e){
      StringWriter errors = new StringWriter();
      e.printStackTrace(new PrintWriter(errors));
    }
    return listViolations;
  }

  /**
   * The function provides toal count of violation of every users either physical or nutrition based on abnormal conditions identified.
   * It projects  userid,
   * COUNT(userid)TotalViolations
   * from  Table tbllog_CurrentLifeLog 
   * where ActivityStatus!='NM' 
   * group by UserId);
   *
   * @return
   */
  
  
  public List<Violations> getTotalViolations(){
    Connection conn = null;
      try{
      conn = DBConnection.getDBConnection().getConnection();
      CallableStatement callableStatement = conn.prepareCall("{call usp_GetTotalViolations()}");
      ResultSet rs = callableStatement.executeQuery();

      if (rs != null){
          while (rs.next()){
          String UserID = rs.getString("UserID");
          String TotalViolations = rs.getString("TotalViolations");
          Violations objViolations = new Violations();
          objViolations.setUserID(UserID);
          objViolations.setTotalViolations(TotalViolations);
          listViolations.add(objViolations);
        }
      }
    } catch (Exception e){
      StringWriter errors = new StringWriter();
      e.printStackTrace(new PrintWriter(errors));
    }
    return listViolations;
  }

  /**
   * The function provides  violation of the user either physical or nutrition based on abnormal conditions identified.
   * It projects ActivityID,
   * ActivityTargetDuration,
   * RecordedTime,
   * Log_Id, 
   * UserID from  TABLE tbllog_CurrentLifeLog
   * where
   * ActivityStatus!='NM' 
   * and UserId= uid ;
   *
   * @param userId
   * @return
   */

  public List<Violations> getUserViolations(String userId){

    Connection conn = null;
  
    try{
      conn = DBConnection.getDBConnection().getConnection();
      CallableStatement callableStatement = conn.prepareCall("{call usp_GetUserViolations( " + userId + ")}");
      ResultSet rs = callableStatement.executeQuery();

      if (rs != null){
          while (rs.next()){
          String UserID = rs.getString("UserID");
          String ActivityID = rs.getString("ActivityID");
          String StartTime = rs.getString("RecordedTime");
          String ActivityTargetDuration = rs.getString("ActivityTargetDuration");
          String LogID = rs.getString("Log_Id");
          Violations objViolations = new Violations();
          objViolations.setActivityID(ActivityID);
          objViolations.setActivityTargetDuration(ActivityTargetDuration);
          objViolations.setStartTime(StartTime);
          objViolations.setLogID(LogID);
          objViolations.setUserID(UserID);
          listViolations.add(objViolations);
        }
      }
    } catch (Exception e){
      StringWriter errors = new StringWriter();
      e.printStackTrace(new PrintWriter(errors));
    }
    return listViolations;
  }

  /**
   * The function provides the details of a the violation of users either physical or nutrition based on abnormal conditions identified.
   * select ActivityID,
   * ActivityTargetDuration,
   * RecordedTime,
   * Log_Id, UserID 
   * from tbllog_CurrentLifeLog
   * where log_Id= lgid ;
   *
   * @param logId
   * @return
   */
  public List<Violations> getLogDeatails(String logId){

    Connection conn = null;
   
    try{
      conn = DBConnection.getDBConnection().getConnection();
      CallableStatement callableStatement = conn.prepareCall("{call usp_GetLogDeatails( " + logId + ")}");
      ResultSet rs = callableStatement.executeQuery();

      if (rs != null){
        while (rs.next()){
          String UserID = rs.getString("UserID");
          String ActivityID = rs.getString("ActivityID");
          String StartTime = rs.getString("RecordedTime");
          String ActivityTargetDuration = rs.getString("ActivityTargetDuration");
          String LogID = rs.getString("Log_Id");
          Violations objViolations = new Violations();
          objViolations.setActivityID(ActivityID);
          objViolations.setActivityTargetDuration(ActivityTargetDuration);
          objViolations.setStartTime(StartTime);
          objViolations.setLogID(LogID);
          objViolations.setUserID(UserID);
          listViolations.add(objViolations);
        }
      }
    } catch (Exception e){
      StringWriter errors = new StringWriter();
      e.printStackTrace(new PrintWriter(errors));
    }
    return listViolations;
  }

}


<|start_filename|>knowledge-curation-layer/DDKAT/src/main/java/org/uclab/mm/kcl/ddkat/datapreprocessor/DataConverter.java<|end_filename|>
/**
 * Copyright [2017] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.mm.kcl.ddkat.datapreprocessor;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.wink.json4j.JSONArray;
import org.apache.wink.json4j.OrderedJSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// TODO: Auto-generated Javadoc
/**
 * This class converts the data into CSV format and then stores it into local machine at specific location.
 */
public class DataConverter {
	
	/** The Constant log. */
	private static final Logger log = LoggerFactory.getLogger(OutlierHandler.class);
	
	/** base directory to store resource data files */
	private static final String BASE_DIR = System.getProperty("user.home") + "\\DDKAT\\resources\\";
		
	/**
	 * Constructor to instantiate a new DataConverter object.
	 * @param dataUnorderedObject the json data object
	 * @param filePath the file path
	 * @throws Exception the exception
	 */
	public DataConverter(String dataUnorderedObject) throws Exception {
		convertData(dataUnorderedObject);
	}
	
	/**
	 * Method to convert the data.
	 *
	 * @param filePath the file path
	 * @throws Exception the exception
	 */
	public void convertData(String dataUnorderedObject) throws Exception {
		log.info("JSON object is successfully loaded : " + dataUnorderedObject);
        OrderedJSONObject jsonObject = new OrderedJSONObject(dataUnorderedObject);
        JSONArray jsontokenArray = jsonObject.getJSONArray("unprocessed_data");
        String csvString="";
        String str;
        for(int i=0;i<jsontokenArray.length();i++){
        	str= jsontokenArray.get(i).toString();
            str = str.substring(1, str.length()-1);
            csvString += str +"\n";
            }
        
        try{
        	

        String filePath = BASE_DIR + "OriginalDataSet.csv";
        File file=new File(filePath);
        // if file does not exists, then create it
        if (!file.exists()) {
        	file.createNewFile();
            }
        FileUtils.writeStringToFile(file,csvString);
        log.info("Data is successfully converted into CSV format and is stored at specific location into your machine");
        
        }catch(Exception e){System.out.println(e);}
	
	}
		
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/llm/SituationEvents.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.llm;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author Rizvi
 */
@XmlRootElement()
public class SituationEvents implements Serializable {
private List<SituationEvent> listSEvents = new ArrayList<SituationEvent>();

    /**
     * @return the listSEvents
     */
    public List<SituationEvent> getListSEvents() {
        return listSEvents;
    }

    /**
     * @param listSEvents the listSEvents to set
     */
    public void setListSEvents(List<SituationEvent> listSEvents) {
        this.listSEvents = listSEvents;
    }
}



<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/datamodel/User.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.datamodel;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonProperty;
import org.uclab.scl.Utilities.ComputationUtilityMethods;

/**
 * @version MM v2.5
 * @author Afzal
 *
 */
public class User implements Serializable{
  
  @JsonProperty("id")
  private long id;
  
  @JsonProperty("requestType")
  private String requestType;
  
  @JsonProperty("middleName")
  private String middleName;

  @JsonProperty("dateOfBirth")
  private String dateOfBirth;

  @JsonProperty("userID")
  private long userID;
  
  @JsonProperty("lastName")
  private String lastName;

  @JsonProperty("contactNumber")
  private String contactNumber;

  @JsonProperty("activityLevelId")
  private int activityLevelId;

  @JsonProperty("martialStatusId")
  private int martialStatusId;
  
  @JsonProperty("genderId")
  private int genderId;
  @JsonProperty("emailAddress")
  private String emailAddress;
  @JsonProperty("firstName")
  private String firstName;
  @JsonProperty("password")
  private String password;
  @JsonProperty("occupationId")
  private int occupationId;
  @JsonProperty("userTypeID")
  private int userTypeID;
  @JsonProperty("userTypeDescription")
  private String userTypeDescription;
  @JsonProperty("genderDescription")
  private String genderDescription;
  @JsonProperty("maritalStatusDescription")
  private String maritalStatusDescription;
  @JsonProperty("occupationDescription")
  private String occupationDescription;
  @JsonProperty("activityLevelDescription")
  private String activityLevelDescription;
  public int getUserTypeID() {
    return userTypeID;
  }

  public void setUserTypeID(int userTypeID) {
    this.userTypeID = userTypeID;
  }

  public String getUserTypeDescription() {
    return userTypeDescription;
  }

  public void setUserTypeDescription(String userTypeDescription) {
    this.userTypeDescription = userTypeDescription;
  }

  public String getGenderDescription() {
    return genderDescription;
  }

  public void setGenderDescription(String genderDescription) {
    this.genderDescription = genderDescription;
  }

  public String getMaritalStatusDescription() {
    return maritalStatusDescription;
  }

  public void setMaritalStatusDescription(String maritalStatusDescription) {
    this.maritalStatusDescription = maritalStatusDescription;
  }

  public String getOccupationDescription() {
    return occupationDescription;
  }

  public void setOccupationDescription(String occupationDescription) {
    this.occupationDescription = occupationDescription;
  }

  public String getMiddleName() {
    return middleName;
  }

  public void setMiddleName(String middleName) {
    this.middleName = middleName;
  }

  public String getDateOfBirth() {
    return dateOfBirth;
  }

  public void setDateOfBirth(String dateOfBirth) {
    this.dateOfBirth = dateOfBirth;
  }

  public long getUserID() {
    return userID;
  }

  public void setUserID(long userID) {
    this.userID = userID;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public String getContactNumber() {
    return contactNumber;
  }

  public void setContactNumber(String contactNumber) {
    this.contactNumber = contactNumber;
  }

  public int getActivityLevelId() {
    return activityLevelId;
  }

  public void setActivityLevelId(int activityLevelId) {
    this.activityLevelId = activityLevelId;
  }

  public int getMartialStatusId() {
    return martialStatusId;
  }

  public void setMartialStatusId(int martialStatusId) {
    this.martialStatusId = martialStatusId;
  }

  public int getGenderId() {
    return genderId;
  }

  public void setGenderId(int genderId) {
    this.genderId = genderId;
  }

  public String getEmailAddress() {
    return emailAddress;
  }

  public void setEmailAddress(String emailAddress) {
    this.emailAddress = emailAddress;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public int getOccupationId() {
    return occupationId;
  }

  public void setOccupationId(int occupationId) {
    this.occupationId = occupationId;
  }
  
  //
  // @Override
  // public String toString()
  // {
  // return
  // "User [middleName = "+middleName+", dateOfBirth = "+dateOfBirth+", userID = "+userID+", lastName = "+lastName+", contactNumber = "+contactNumber+", activityLevelId = "+activityLevelId+", martialStatusId = "+martialStatusId+", genderId = "+genderId+", emailAddress = "+emailAddress+", firstName = "+firstName+", password = "+password+", occupationId = "+occupationId+"]";
  // }

  public String getActivityLevelDescription() {
    return activityLevelDescription;
  }

  public void setActivityLevelDescription(String activityLevelDescription) {
    this.activityLevelDescription = activityLevelDescription;
  }
  
  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public String getRequestType() {
    return requestType;
  }

  public void setRequestType(String requestType) {
    this.requestType = requestType;
  }

  @Override
  public String toString() {
    String keyValue = "";
    try {

      ComputationUtilityMethods cUtility = ComputationUtilityMethods
          .getComputationUtilityMethods();
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
      Date dob = new Date();
      dob = sdf.parse(dateOfBirth);

      keyValue += "\"Age Group\":\"" + cUtility.getAgeGroup(dob) + "\",\n";

      keyValue += "\"Gender\":\"" + cUtility.GenderConversion(genderId) + "\",";

    } catch (ParseException pExp) {
      pExp.printStackTrace();
    }

    return keyValue;
  }

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sl/dataadapter/RecommendationFeedbackAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sl.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.sc.Recommendation;
import org.uclab.mm.datamodel.sl.RecommendationFeedback;

/**
 * This is RecommendationFeedbackAdapter class which implements the Data Access Interface for CRUD operations
 * @author <NAME>
 */
public class RecommendationFeedbackAdapter implements DataAccessInterface {

    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(RecommendationFeedbackAdapter.class);
    public RecommendationFeedbackAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving RecommendationFeedback. 
     * @param objRecommendationFeedback
     * @return List of String
     */
    @Override
    public List<String> Save(Object objRecommendationFeedback) {
        RecommendationFeedback objInnerRecommendationFeedback = new RecommendationFeedback();
        objInnerRecommendationFeedback =  (RecommendationFeedback) objRecommendationFeedback;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_RecommendationFeedback(?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("RecommendationID", objInnerRecommendationFeedback.getRecommendationID());
            objCallableStatement.setLong("UserID", objInnerRecommendationFeedback.getUserID());
            objCallableStatement.setInt("Rate", objInnerRecommendationFeedback.getRate());
            objCallableStatement.setString("Reason", objInnerRecommendationFeedback.getReason());
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
            Date dtDate = sdf.parse(objInnerRecommendationFeedback.getFeedbackDate());
            
            Timestamp tsDate = new Timestamp(dtDate.getYear(),dtDate.getMonth(), dtDate.getDate(), dtDate.getHours(), dtDate.getMinutes(), dtDate.getSeconds(), 00);
            objCallableStatement.setTimestamp("FeedbackDate", tsDate);
            
                        
            objCallableStatement.registerOutParameter("RecommendationFeedbackID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intRecommendationFeedbackID = objCallableStatement.getLong("RecommendationFeedbackID");
            objDbResponse.add(String.valueOf(intRecommendationFeedbackID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Recommendation Feedback saved successfully, Recommendation Feedback Details="+objRecommendationFeedback);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding Recommendation Feedback");
        	objDbResponse.add("Error in adding Recommendation Feedback");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for updating RecommendationFeedback. 
     * @param objRecommendationFeedback
     * @return List of String
     */
    @Override
    public List<String> Update(Object objRecommendationFeedback) {
        RecommendationFeedback objInnerRecommendationFeedback = new RecommendationFeedback();
        objInnerRecommendationFeedback =  (RecommendationFeedback) objRecommendationFeedback;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_RecommendationFeedback(?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("RecommendationFeedbackID", objInnerRecommendationFeedback.getRecommendationFeedbackID());
            objCallableStatement.setLong("RecommendationID", objInnerRecommendationFeedback.getRecommendationID());
            objCallableStatement.setLong("UserID", objInnerRecommendationFeedback.getUserID());
            objCallableStatement.setInt("Rate", objInnerRecommendationFeedback.getRate());
            objCallableStatement.setString("Reason", objInnerRecommendationFeedback.getReason());
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
            Date dtDate = sdf.parse(objInnerRecommendationFeedback.getFeedbackDate());
            
            Timestamp tsDate = new Timestamp(dtDate.getYear(),dtDate.getMonth(), dtDate.getDate(), dtDate.getHours(), dtDate.getMinutes(), dtDate.getSeconds(), 00);
            objCallableStatement.setTimestamp("FeedbackDate", tsDate);
            
            objCallableStatement.execute();
            
            Long intRecommendationFeedbackID = objInnerRecommendationFeedback.getRecommendationFeedbackID();
            objDbResponse.add(String.valueOf(intRecommendationFeedbackID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Recommendation Feedback updated successfully, Recommendation Feedback Details="+objRecommendationFeedback);
        }
        catch (Exception e)
        {
        	logger.info("Error in updating Recommendation Feedback");
        	objDbResponse.add("Error in updating Recommendation Feedback");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for retrieving RecommendationFeedback. 
     * @param objRecommendationFeedback
     * @return List of RecommendationFeedback
     */
    @Override
    public List<RecommendationFeedback> RetriveData(Object objRecommendationFeedback) {
        RecommendationFeedback objOuterRecommendationFeedback = new RecommendationFeedback();
        List<RecommendationFeedback> objListInnerRecommendationFeedback = new ArrayList<RecommendationFeedback>();
        objOuterRecommendationFeedback =  (RecommendationFeedback) objRecommendationFeedback;
        
        try
        {
            CallableStatement objCallableStatement = null;
            if(objOuterRecommendationFeedback.getRequestType() == "ByRecommendationID")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_RecommendationFeedbackByRecommendationID(?)}");
                objCallableStatement.setLong("RecommendationID", objOuterRecommendationFeedback.getRecommendationID());
            }
            else if(objOuterRecommendationFeedback.getRequestType() == "ByUserID")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_RecommendationFeedbackByUserID(?)}");
                objCallableStatement.setLong("UserID", objOuterRecommendationFeedback.getUserID());
            }
            
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                RecommendationFeedback objInnerRecommendationFeedback = new RecommendationFeedback();
                
                objInnerRecommendationFeedback.setRecommendationFeedbackID(objResultSet.getLong("RecommendationFeedbackID"));
                objInnerRecommendationFeedback.setRecommendationID(objResultSet.getLong("RecommendationID"));
                objInnerRecommendationFeedback.setUserID(objResultSet.getLong("UserID"));
                objInnerRecommendationFeedback.setRate(objResultSet.getInt("Rate"));
                objInnerRecommendationFeedback.setReason(objResultSet.getString("Reason"));
                
                if(objResultSet.getTimestamp("FeedbackDate") != null)
                {
                    Timestamp tsFeedbackDate = objResultSet.getTimestamp("FeedbackDate");
                    objInnerRecommendationFeedback.setFeedbackDate(tsFeedbackDate.toString());
                }
                
                objInnerRecommendationFeedback.setSituationCategoryID(objResultSet.getInt("SituationCategoryID"));
                objInnerRecommendationFeedback.setSituationCategoryDescription(objResultSet.getString("SituationCategoryDescription"));
                
                 
                objListInnerRecommendationFeedback.add(objInnerRecommendationFeedback);
            }
            objConn.close();
            logger.info("Recommendation Feedback loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading Recommendation Feedback");
        }   
        return objListInnerRecommendationFeedback;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }


    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/utils/TimeUtil.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
/**
 * TimeUtil: 
 * Provides time date format utility.
 * 
 * @author Nailbrainz
 * @version 2.5
 * @since 2015-11-06
 */
public class TimeUtil {
	static SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss", Locale.KOREA);
	static SimpleDateFormat demoSdf = new SimpleDateFormat("HH:mm:ss", Locale.KOREA);
	
	public String toDemoStr(Calendar cal){
		synchronized(this){
			String formatted = demoSdf.format(cal.getTime());
			return formatted;
		}
	}
	
	public String parseCal(Calendar cal){
		synchronized(this){
			String formatted = sdf.format(cal.getTime());
			return formatted;
		}
	}
	
	public Calendar parseString(String str){
		synchronized(this){
			Calendar cal = Calendar.getInstance();
			try {
				cal.setTime(sdf.parse(str));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return cal;
		}
	}
	
	public String getTime(){
		synchronized(this){
			Calendar cal = Calendar.getInstance();
		    return sdf.format(cal.getTime());
		}
	}
	
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/dc/dataadapter/UserFacilitiesAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.dc.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.dc.UserFacilities;

/**
 * This is UserFacilitiesAdapter class which implements the Data Access Interface for CRUD operations
 * @author Taqdir
 */
public class UserFacilitiesAdapter implements DataAccessInterface {

     private Connection objConn;
     private static final Logger logger = LoggerFactory.getLogger(UserFacilitiesAdapter.class);
    
    public UserFacilitiesAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving UserFacilities. 
     * @param objUserFacilities
     * @return List of String
     */
    @Override
    public List<String> Save(Object objUserFacilities) {
        UserFacilities objInnerUserFacilities = new UserFacilities();
        objInnerUserFacilities =  (UserFacilities) objUserFacilities;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_UserFacilities(?, ?, ?)}");
            
            objCallableStatement.setLong("UserID", objInnerUserFacilities.getUserId());
            objCallableStatement.setInt("FacitlityID", objInnerUserFacilities.getFacilityId());
           
            
            objCallableStatement.registerOutParameter("UserFacilityID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intUserFacilityID = objCallableStatement.getLong("UserFacilityID");
            objDbResponse.add(String.valueOf(intUserFacilityID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("user Facilities saved successfully, User Details="+objUserFacilities);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding user Facilities");
        	objDbResponse.add("Error in adding user Facilities");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for updating UserFacilities. 
     * @param objUserFacilities
     * @return List of String
     */
    @Override
    public List<String> Update(Object objUserFacilities) {
        UserFacilities objInnerUserFacilities = new UserFacilities();
        objInnerUserFacilities =  (UserFacilities) objUserFacilities;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_UserFacilities(?, ?, ?)}");
            
            objCallableStatement.setLong("UserFacilityID", objInnerUserFacilities.getUserFacilityId());
            objCallableStatement.setLong("UserID", objInnerUserFacilities.getUserId());
            objCallableStatement.setInt("FacitlityID", objInnerUserFacilities.getFacilityId());
            
            objCallableStatement.execute();
            
            objDbResponse.add(String.valueOf(objInnerUserFacilities.getUserFacilityId()));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("user Facilities saved successfully, UserFacilities Details="+objUserFacilities);
        }
        catch (Exception e)
        {
        	logger.info("Error in updated user Facilities");
        	objDbResponse.add("Error in updated user Facilities");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for retrieving UserFacilities.
     * @param objUserFacilities
     * @return List of UserFacilities
     */
    @Override
    public List<UserFacilities> RetriveData(Object objUserFacilities) {
        UserFacilities objOuterUserFacilities = new UserFacilities();
        List<UserFacilities> objListInnerUserFacilities = new ArrayList<UserFacilities>();
        objOuterUserFacilities =  (UserFacilities) objUserFacilities;
        
        try
        {
            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UserFacilitiesByUserID(?)}");
            objCallableStatement.setLong("UserID", objOuterUserFacilities.getUserId());
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                UserFacilities objInnerUserFacilities = new UserFacilities();
                objInnerUserFacilities.setUserFacilityId(objResultSet.getLong("UserFacilityID"));
                objInnerUserFacilities.setUserId(objResultSet.getLong("UserID"));
                objInnerUserFacilities.setFacilityId(objResultSet.getInt("FacitlityID"));
                
                objListInnerUserFacilities.add(objInnerUserFacilities);
            }
            objConn.close();
            logger.info("user Facilities loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading user Facilities");
        }   
        return objListInnerUserFacilities;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

     /**
      * This is implementation function for connection database.
      * @param objConf
      */
     @Override
      public void ConfigureAdapter(Object objConf) {
          try
          {
             objConn = (Connection)objConf;
             logger.info("Database connected successfully");
          }
          catch(Exception ex)
          {
         	 logger.info("Error in connection to Database");
          }
     }
    
}


<|start_filename|>supporting-layer/descriptive-analytics/src/assets/js/div.js<|end_filename|>

AmCharts.makeChart("feedback_location_chartdiv",
				{
					"type": "serial",
					"pathToImages": "http://cdn.amcharts.com/lib/3/images/",
					"categoryField": "category",
					"rotate": true,
					"startDuration": 1,
					"categoryAxis": {
						"gridPosition": "start"
					},
					"trendLines": [],
					"graphs": [
						{
							"balloonText": "[[title]] of [[category]]:[[value]]",
							"fillAlphas": 1,						
							"title": "Location",
							"type": "column",
							"valueField": "Location"
						}
						
					],
					"guides": [],
					"valueAxes": [
						{
							"id": "activities_feedback",
							"stackType": "regular",
							"title": ""
						}
					],
					"allLabels": [],
					"balloon": {},
					"legend": {
						"periodValueText": "Total : [[value.sum]]",
						"useGraphSettings": true,
						"valueAlign": "left"
					},
					
					"dataProvider": [
						{
							"category": "Home",
							"Location": 8,

						},
						{
							"category": "Work",
							"Location": 6,

						},
						{
							"category": "Gym",
							"Location": 2,

						}
					]
				}
			);
			
			
var chart = AmCharts.makeChart( "chartdiv", {
  "type": "pie",
  "theme": "light",
  "dataProvider": [ {
    "activity": "Sitting",
    "Minutes": 501.9
  }, {
    "activity": "Standing",
    "Minutes": 301.9
  }, {
    "activity": "Walking",
    "Minutes": 201.1
  }, {
    "activity": "Running",
    "Minutes": 165.8
  } ],
  "valueField": "Minutes",
  "titleField": "activity",
   "balloon":{
   "fixedPosition":true
  },
  "export": {
    "enabled": true
  }
} );



<?php

$response='{
	"word":["??","??","???","??","???","??","??","????","??","??"],
	
	"freq":[634,627,623,603,601,596,593,592,590,588]
	
}';
//echo "<pre>";
$result=json_decode($response,true);

?>


var chart = AmCharts.makeChart("snschartdiv", {
    "theme": "light",
    "type": "serial",
	"startDuration": 2,
    "dataProvider": [{
        "country": "USA",
        "visits": 4025,
        "color": "#FF0F00"
    }, {
        "country": "China",
        "visits": 1882,
        "color": "#FF6600"
    }, {
        "country": "Japan",
        "visits": 1809,
        "color": "#FF9E01"
    }, {
        "country": "Germany",
        "visits": 1322,
        "color": "#FCD202"
    }, {
        "country": "UK",
        "visits": 1122,
        "color": "#F8FF01"
    }, {
        "country": "France",
        "visits": 1114,
        "color": "#B0DE09"
    }, {
        "country": "India",
        "visits": 984,
        "color": "#04D215"
    }, {
        "country": "Spain",
        "visits": 711,
        "color": "#0D8ECF"
    }, {
        "country": "Netherlands",
        "visits": 665,
        "color": "#0D52D1"
    }, {
        "country": "Russia",
        "visits": 580,
        "color": "#2A0CD0"
    }, {
        "country": "South Korea",
        "visits": 443,
        "color": "#8A0CCF"
    }, {
        "country": "Canada",
        "visits": 441,
        "color": "#CD0D74"
    }, {
        "country": "Brazil",
        "visits": 395,
        "color": "#754DEB"
    }, {
        "country": "Italy",
        "visits": 386,
        "color": "#DDDDDD"
    }, {
        "country": "Australia",
        "visits": 384,
        "color": "#999999"
    }, {
        "country": "Taiwan",
        "visits": 338,
        "color": "#333333"
    }, {
        "country": "Poland",
        "visits": 328,
        "color": "#000000"
    }],
    "valueAxes": [{
        "position": "left",
        "title": "Visitors"
    }],
    "graphs": [{
        "balloonText": "[[category]]: <b>[[value]]</b>",
        "fillColorsField": "color",
        "fillAlphas": 1,
        "lineAlpha": 0.1,
        "type": "column",
        "valueField": "visits"
    }],
    "depth3D": 20,
	"angle": 30,
    "chartCursor": {
        "categoryBalloonEnabled": false,
        "cursorAlpha": 0,
        "zoomable": false
    },    
    "categoryField": "country",
    "categoryAxis": {
        "gridPosition": "start",
        "labelRotation": 90
    },
    "export": {
    	"enabled": true
     }

});
jQuery('.chart-input').off().on('input change',function() {
	var property	= jQuery(this).data('property');
	var target		= chart;
	chart.startDuration = 0;

	if ( property == 'topRadius') {
		target = chart.graphs[0];
      	if ( this.value == 0 ) {
          this.value = undefined;
      	}
	}

	target[property] = this.value;
	chart.validateNow();
});

<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/outputModel/RecModel/PhyActivityRecommendations.java<|end_filename|>
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.uclab.scl.outputModel.RecModel;

import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonProperty;
import org.uclab.scl.datamodel.User;
import org.uclab.scl.framework.recbuilder.RecIdentifierEnum;

/**
 * 
 * @author User
 */
public class PhyActivityRecommendations {

  // @JsonIgnore
  // private int testInt;
  //
  // @JsonProperty
  // public int getTestInt() {
  // return testInt;
  // }
  //
  // @JsonProperty
  // public void setTestInt(int testInt) {
  // this.testInt = testInt;
  // }

  private long recommendationID;

  private String conditionValue;

  private String recommendationIdenfier;

  private String recommendationDate;

  private int recommendationLevelID;

  private String recommendationDescription;

  private long situationID;

  private int recommendationStatusID;

  private int recommendationTypeID;

  private String recommendationLevelDescription;

  private String recommendationStatusDescription;

  private String recommendationTypeDescription;

  public String getRecommendationLevelDescription() {
    return recommendationLevelDescription;
  }

  public void setRecommendationLevelDescription(
      String recommendationLevelDescription) {
    this.recommendationLevelDescription = recommendationLevelDescription;
  }

  public String getRecommendationStatusDescription() {
    return recommendationStatusDescription;
  }

  public void setRecommendationStatusDescription(
      String recommendationStatusDescription) {
    this.recommendationStatusDescription = recommendationStatusDescription;
  }

  public String getRecommendationTypeDescription() {
    return recommendationTypeDescription;
  }

  public void setRecommendationTypeDescription(
      String recommendationTypeDescription) {
    this.recommendationTypeDescription = recommendationTypeDescription;
  }

  public String getRecommendationIdentifier() {
    return recommendationIdenfier;
  }

  public void setRecommendationIdentifier(String recommendationIdentifier) {
    this.recommendationIdenfier = recommendationIdentifier;
  }

  public String getConditionValue() {
    return conditionValue;
  }

  public void setConditionValue(String conditionValue) {
    this.conditionValue = conditionValue;
  }

  public String getRecommendationDate() {
    return recommendationDate;
  }

  public void setRecommendationDate(String recommendationDate) {
    this.recommendationDate = recommendationDate;
  }

  public int getRecommendationLevelID() {
    return recommendationLevelID;
  }

  public void setRecommendationLevelID(int recommendationLevelID) {
    this.recommendationLevelID = recommendationLevelID;
  }

  public String getRecommendationDescription() {
    return recommendationDescription;
  }

  public void setRecommendationDescription(String recommendationDescription) {
    this.recommendationDescription = recommendationDescription;
  }

  public long getSituationID() {
    return situationID;
  }

  public void setSituationID(long situationID) {
    this.situationID = situationID;
  }

  public int getRecommendationStatusID() {
    return recommendationStatusID;
  }

  public void setRecommendationStatusID(int recommendationStatusID) {
    this.recommendationStatusID = recommendationStatusID;
  }

  public int getRecommendationTypeID() {
    return recommendationTypeID;
  }

  public void setRecommendationTypeID(int recommendationTypeID) {
    this.recommendationTypeID = recommendationTypeID;
  }

  public long getRecommendationID() {
    return recommendationID;
  }

  public void setRecommendationID(long recommendationID) {
    this.recommendationID = recommendationID;
  }

  @Override
  public String toString() {
    return "ClassPojo [conditionValue = " + conditionValue
        + ", recommendationIdentifier = "
        + RecIdentifierEnum.SittingOneHour01
        + ", recommendationDate = " + recommendationDate
        + ", recommendationLevelID = " + recommendationLevelID
        + ", recommendationDescription = " + recommendationDescription
        + ", situationID = " + situationID + ", recommendationStatusID = "
        + recommendationStatusID + ", recommendationTypeID = "
        + recommendationTypeID + "]";
  }

}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/LLCRecognizer/InertialActivityRecognizer.java<|end_filename|>
/**
Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */

package org.uclab.mm.icl.llc.LLCRecognizer;

import java.io.File;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.uclab.mm.icl.data.DeviceData;
import org.uclab.mm.icl.data.SmartphoneData;
import org.uclab.mm.icl.llc.AR.iar.AR_DecisionFusion;
import org.uclab.mm.icl.llc.AR.iar.AR_Reasoning;
import org.uclab.mm.icl.llc.AR.iar.AR_makeARFF;
import org.uclab.mm.icl.llc.LLCManager.ContextLabel;
import org.uclab.mm.icl.llc.config.ContextType;
import org.uclab.mm.icl.llc.config.DeviceType;
import org.uclab.mm.icl.llc.config.RecognizerType;
import org.uclab.mm.icl.utils.FileUtil;
import org.uclab.mm.icl.utils.TimeChecker;

/**
 * This class processes the inertial sensor based activity recognition
 * @author <NAME>
 *
 */


class IARData{
	public double[][] getAcc_wm() {
		return acc_wm;
	}

	public double[][] getGy_wm() {
		return gy_wm;
	}

	public double[][] getAcc_sm() {
		return acc_sm;
	}

	public double[][] getGy_sm() {
		return gy_sm;
	}

	public IARData(double[][] acc_wm, double[][] gy_wm, double[][] acc_sm, double[][] gy_sm) {
		super();
		this.acc_wm = acc_wm;
		this.gy_wm = gy_wm;
		this.acc_sm = acc_sm;
		this.gy_sm = gy_sm;
	}

	double[][] acc_wm, gy_wm, acc_sm, gy_sm;
	
}

public class InertialActivityRecognizer extends LLCRecognizer<IARData>{
	
	private final static Logger logger = Logger.getLogger(InertialActivityRecognizer.class);
	private AR_Reasoning ar_integrated = null; // Integrated model instance for reasoning
	private AR_Reasoning ar_smartphone = null; // Smartphone model instance for reasoning
	private AR_Reasoning ar_wearable = null; // Wearable model instance for reasoning
	private AR_makeARFF mkArff = null; // Instance for making ARFF file
	
	AR_DecisionFusion df; // To store decision fusion result

	// Stores the sensor variables
   
	/**
	 * This function loads the integrated, smartphone and smartwatch AR model
	 * @param userID
	 */
	public InertialActivityRecognizer(long userID){
		super(userID);
		
		ar_integrated = new AR_Reasoning(FileUtil.getRootPath()+"/armodel/integrated model_0126.model");
		ar_smartphone = new AR_Reasoning(FileUtil.getRootPath()+"/armodel/sm model_0126.model");
		ar_wearable = new AR_Reasoning(FileUtil.getRootPath()+"/armodel/wm model_0126.model");
		
		df = new AR_DecisionFusion();
				
		if (!new File(FileUtil.getRootPath()+"/arffFile/").exists()) {
			new File(FileUtil.getRootPath()+"/arffFile/").mkdirs();
		}
		
	}
	
	/**
	 * This function proceeds the inertial based activity reasoning 
	 */
	@Override
	public ContextLabel recognize(IARData input, String timeStamp) {
		
		// Execute to make the ARFF file
		try {
			mkArff = new AR_makeARFF(input.getAcc_wm(), input.getGy_wm(), input.getAcc_sm(), input.getGy_sm());
		} catch (IOException e) {
		
			e.printStackTrace();
		}
		
		String in = null; // To store activity result from integrated AR model
		String sm = null; // To store activity result from smartphone AR model
		String wm = null; // To store activity result from wearable AR model
		
		// Return the result of each AR model
		try{
			 in = AR_DecisionFusion.getActivity(Integer.parseInt(ar_integrated.executeWeka(1)));
			 sm = AR_DecisionFusion.getActivity(Integer.parseInt(ar_smartphone.executeWeka(2)));
			 wm = AR_DecisionFusion.getActivity(Integer.parseInt(ar_wearable.executeWeka(3)));
			 
		}catch(Exception e){
			wm = null;
			e.printStackTrace();
		}
		
		// Store all the information with activity label
		ContextLabel act = new ContextLabel(userID, df.getFinalActivity(in, sm, wm), timeStamp, ContextType.Activity);

		// Simple notification for successful reasoning
		if(verbose)logger.info("Output from Inertial recognizer!" + userID + "\t" + act.getLabel() + "\t" + act.getTimeStamp());
	
		long localTime = TimeChecker.time;
		return act;
	}


	/**
	 * This class loads the sensor data
	 */
	@Override
	public void ConsumeData(DeviceType it, DeviceData obj) {
		// TODO Auto-generated method stub
		
		if(it.equals(DeviceType.SmartPhone)){
			SmartphoneData data = (SmartphoneData) obj;
			IARData idd = new IARData(data.getAcc_wm(),data.getGy_wm(),data.getAcc_sm(),data.getGy_sm());
			setData(idd);
		}
	}

	@Override
	public RecognizerType getType() {
		// TODO Auto-generated method stub
		return RecognizerType.IAR;
	}
	
	
	
	/*
	 * 
	public boolean isFull(){
		return acc_wm != null && acc_wm[0] != null;
	}
	
	@Override
	public Runnable getRunnable(String timeStamp, LLCUnifier unifier) {
		// TODO Auto-generated method stub
		return new IARunnable(timeStamp, unifier, this);
	}
	class IARunnable implements Runnable{
		LLCUnifier unifier;
		InertialActivityRecognizer rec;
		String timeStamp;
		
		public IARunnable(String timeStamp, LLCUnifier unifier, InertialActivityRecognizer rec){
			this.unifier = unifier;
			this.rec = rec;
			this.timeStamp = timeStamp;
			
		}
		@Override
		public void run() {
			// TODO Auto-generated method stub
			if(rec.isFull()){
				unifier.push(rec.recognize(new double[5], timeStamp), RecognizerType.IAR);
			}
				
			else{
				unifier.push(new ContextLabel(userID, "NoActivity", timeStamp, ContextType.Activity), RecognizerType.IAR);
			}
				
		}
		
	}
	@Override
	public RecognizerType getType() {
		// TODO Auto-generated method stub
		return RecognizerType.IAR;
	}
	

	@Override
	public boolean isThresholdReached() {
		// TODO Auto-generated method stub
		return acc_sm != null;
	}*/
	 
}



<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/AER/jh/AERFeatureExtraction.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Bang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.AER.jh;

import java.io.IOException;
import java.util.Arrays;
import java.util.Vector;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.UnsupportedAudioFileException;

import org.uclab.mm.icl.llc.MachineLearningTools.FeatureExtraction;
import org.uclab.mm.icl.llc.MachineLearningTools.FilterBankPreprocessing;
import org.uclab.mm.icl.llc.MachineLearningTools.TimeDomainFeatureExtraction;

/**
 * This Class extract MiningMind v2.5 Audio based ER Feature Extraction
 * 
 * @author <NAME>
 *
 */
public class AERFeatureExtraction extends
		FeatureExtraction<AudioInputStream, double[]> {

	
	/**
	 * Extract the Audio features
	 */
	@Override
	public double[] extractFeature(AudioInputStream input) {
		// TODO Auto-generated method stub
		FilterBankPreprocessing fbp = new FilterBankPreprocessing();
		TimeDomainFeatureExtraction tdfe = new TimeDomainFeatureExtraction();
		double[][] mfccMatrix = null;
		double[] features = null;
		try {
			mfccMatrix = fbp.getMfcc(input);
			features = tdfe.getTimeDomainFeatures(mfccMatrix);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return features;
	}

}


<|start_filename|>knowledge-curation-layer/i-kat/src/main/java/org/uclab/mm/kcl/edkat/service/RuleServiceImpl.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.kcl.edkat.service;

import java.util.List;

import org.springframework.transaction.annotation.Transactional;
import org.uclab.mm.kcl.edkat.dao.RuleDAO;
import org.uclab.mm.kcl.edkat.datamodel.Rule;

/**
* This is service implementation class for the rule it provides implementation to
* create, update, retrieve of rules, conditions, conclusions, and situation
 * @author  <NAME>
 * @version 1.0
 * @since   2015-08-16
 * */
public class RuleServiceImpl implements RuleService {

	private RuleDAO ruleDAO;
	public RuleDAO getRuleDAO() {
		return ruleDAO;
	}
	public void setRuleDAO(RuleDAO ruleDAO) {
		this.ruleDAO = ruleDAO;
	}

	/**
	 * This function is for add new rule with conditions, conclusions, and situations
	 * @param objRule
	 * @return Object of Rule
	*/
	@Transactional
	public Rule addRule(Rule objRule) {
		return this.ruleDAO.addRule(objRule);
	}

	/**
	 *  This interface function is for update the existing rule with conditions, conclusions, and situations
	 * @param objRule
	 * @return Object of Rule
	*/
	@Transactional
	public Rule updateRule(Rule objRule) {
		return this.ruleDAO.updateRule(objRule);
	}

	/**
	 * This function get all rules with conditions, conclusions, and situations
	 * @return List of Rules
	*/
	public List<Rule> listRules() {
		return this.ruleDAO.listRule();
	}

	/**
	 * This function get a specific rule by rule id (primary key)
	 * @param id
	 * @return Object of Rule
	*/
	public Rule getRuleById(int id) {
		return this.ruleDAO.getRuleById(id);
	}

	/**
	 * This function delete a specific rule by rule id (primary key)
	 * @param id
	*/
	public void removeRule(int id) {
		this.ruleDAO.removeRule(id);
	}

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/dataadapter/RecommendationAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.sc.Recommendation;
import org.uclab.mm.datamodel.sc.Situation;

/**
 * This is RecommendationAdapter class which implements the Data Access Interface for CRUD operations
 * @author <NAME>
 */
public class RecommendationAdapter implements DataAccessInterface {

    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(RecommendationAdapter.class);
    public RecommendationAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving Recommendation. 
     * @param objRecommendation
     * @return List of String
     */
    @Override
    public List<String> Save(Object objRecommendation) {
        Recommendation objInnerRecommendation = new Recommendation();
        objInnerRecommendation =  (Recommendation) objRecommendation;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_Recommendation(?, ?, ?, ?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setString("RecommendationIdentifier", objInnerRecommendation.getRecommendationIdentifier());
            objCallableStatement.setLong("SituationID", objInnerRecommendation.getSituationID());
            objCallableStatement.setString("RecommendationDescription", objInnerRecommendation.getRecommendationDescription());
            objCallableStatement.setString("ConditionValue", objInnerRecommendation.getConditionValue());
            objCallableStatement.setInt("RecommendationTypeID", objInnerRecommendation.getRecommendationTypeID());
            objCallableStatement.setInt("RecommendationLevelID", objInnerRecommendation.getRecommendationLevelID());
            objCallableStatement.setInt("RecommendationStatusID", objInnerRecommendation.getRecommendationStatusID());
            
             SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
            Date dtDate = sdf.parse(objInnerRecommendation.getRecommendationDate());
            
            Timestamp tsDate = new Timestamp(dtDate.getYear(),dtDate.getMonth(), dtDate.getDate(), dtDate.getHours(), dtDate.getMinutes(), dtDate.getSeconds(), 00);
            objCallableStatement.setTimestamp("RecommendationDate", tsDate);
            
            objCallableStatement.registerOutParameter("RecommendationID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intRecommendationID = objCallableStatement.getLong("RecommendationID");
            objDbResponse.add(String.valueOf(intRecommendationID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Recommendation saved successfully, Recommendation Details="+objRecommendation);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding Recommendation");
        	objDbResponse.add("Error in adding Recommendation");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for updating Recommendation. 
     * @param objRecommendation
     * @return List of String
     */
    @Override
    public List<String> Update(Object objRecommendation) {
        Recommendation objInnerRecommendation = new Recommendation();
        objInnerRecommendation =  (Recommendation) objRecommendation;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_Recommendation(?, ?, ?, ?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("RecommendationID", objInnerRecommendation.getRecommendationID());
            objCallableStatement.setString("RecommendationIdentifier", objInnerRecommendation.getRecommendationIdentifier());
            objCallableStatement.setLong("SituationID", objInnerRecommendation.getSituationID());
            objCallableStatement.setString("RecommendationDescription", objInnerRecommendation.getRecommendationDescription());
            objCallableStatement.setString("ConditionValue", objInnerRecommendation.getConditionValue());
            objCallableStatement.setInt("RecommendationTypeID", objInnerRecommendation.getRecommendationTypeID());
            objCallableStatement.setInt("RecommendationLevelID", objInnerRecommendation.getRecommendationLevelID());
            objCallableStatement.setInt("RecommendationStatusID", objInnerRecommendation.getRecommendationStatusID());
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
            Date dtDate = sdf.parse(objInnerRecommendation.getRecommendationDate());
            
            Timestamp tsDate = new Timestamp(dtDate.getYear(),dtDate.getMonth(), dtDate.getDate(), dtDate.getHours(), dtDate.getMinutes(), dtDate.getSeconds(), 00);
            objCallableStatement.setTimestamp("RecommendationDate", tsDate);
            
           objCallableStatement.execute();
            
            Long intRecommendationID = objInnerRecommendation.getRecommendationID();
            objDbResponse.add(String.valueOf(intRecommendationID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Recommendation saved successfully, Recommendation Details="+objRecommendation);
        }
        catch (Exception e)
        {
        	logger.info("Error in updating Recommendation");
        	objDbResponse.add("Error in updating Recommendation");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for retrieving Recommendation. 
     * @param objRecommendation
     * @return List of Recommendation
     */
    @Override
    public List<Recommendation> RetriveData(Object objRecommendation) {
        Recommendation objOuterRecommendation = new Recommendation();
        List<Recommendation> objListInnerRecommendation = new ArrayList<Recommendation>();
        objOuterRecommendation =  (Recommendation) objRecommendation;
        
        try
        {
            CallableStatement objCallableStatement = null;
            if(objOuterRecommendation.getRequestType() == "ByUserOnly")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_RecommendationByUser(?)}");
                objCallableStatement.setLong("UserID", objOuterRecommendation.getUserID());
            }
            else if(objOuterRecommendation.getRequestType() == "ByUserandDate")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_RecommendationByUserIDDate(?, ?, ?)}");
                
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
               Date dtStartDate = sdf.parse(objOuterRecommendation.getStartDate());
               Timestamp tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);

               Date dtEndDate =sdf.parse( objOuterRecommendation.getEndDate()); //.getTime();
               Timestamp tsEndDate = new Timestamp(dtEndDate.getYear(),dtEndDate.getMonth(), dtEndDate.getDate(), dtEndDate.getHours(), dtEndDate.getMinutes(),dtEndDate.getSeconds(),0);
            
                objCallableStatement.setLong("UserID", objOuterRecommendation.getUserID());
                objCallableStatement.setTimestamp("StartTime", tsStartDate);
                objCallableStatement.setTimestamp("EndTime", tsEndDate);
            }
            else if(objOuterRecommendation.getRequestType() == "ByActivityIDsAndDate")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_RecommendationsByDateRangeActivityIDs(?, ?, ?)}");
                
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
               Date dtStartDate = sdf.parse(objOuterRecommendation.getStartDate());
               Timestamp tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);

               Date dtEndDate =sdf.parse( objOuterRecommendation.getEndDate()); //.getTime();
               Timestamp tsEndDate = new Timestamp(dtEndDate.getYear(),dtEndDate.getMonth(), dtEndDate.getDate(), dtEndDate.getHours(), dtEndDate.getMinutes(),dtEndDate.getSeconds(),0);
            
                objCallableStatement.setString("ActivityIDs", objOuterRecommendation.getSituationCategoryIDs());
                objCallableStatement.setTimestamp("StartDate", tsStartDate);
                objCallableStatement.setTimestamp("EndDate", tsEndDate);
            }
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                Recommendation objInnerRecommendation = new Recommendation();
                objInnerRecommendation.setRecommendationID(objResultSet.getLong("RecommendationID"));
                objInnerRecommendation.setRecommendationIdentifier(objResultSet.getString("RecommendationIdentifier"));
                objInnerRecommendation.setSituationID(objResultSet.getLong("SituationID"));
                objInnerRecommendation.setRecommendationDescription(objResultSet.getString("RecommendationDescription"));
                objInnerRecommendation.setRecommendationTypeID(objResultSet.getInt("RecommendationTypeID"));
                objInnerRecommendation.setConditionValue(objResultSet.getString("ConditionValue"));
                objInnerRecommendation.setRecommendationLevelID(objResultSet.getInt("RecommendationLevelID"));
                objInnerRecommendation.setRecommendationStatusID(objResultSet.getInt("RecommendationStatusID"));
                
                if(objResultSet.getTimestamp("RecommendationDate") != null)
                {
                    Timestamp tsRecommendationDate = objResultSet.getTimestamp("RecommendationDate");
                    objInnerRecommendation.setRecommendationDate(tsRecommendationDate.toString());
                }
                   
               objInnerRecommendation.setRecommendationTypeDescription(objResultSet.getString("RecommendationTypeDescription"));
               objInnerRecommendation.setRecommendationLevelDescription(objResultSet.getString("RecommendationLevelDescription"));
               objInnerRecommendation.setRecommendationStatusDescription(objResultSet.getString("RecommendationStatusDescription"));
               
               objInnerRecommendation.setSituationCategoryID(objResultSet.getInt("SituationCategoryID"));
               objInnerRecommendation.setSituationCategoryDescription(objResultSet.getString("SituationCategoryDescription"));
                              
               objListInnerRecommendation.add(objInnerRecommendation);
            }
            objConn.close();
            logger.info("Recommendation loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading Recommendation");
        }   
        return objListInnerRecommendation;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet."); 
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/utils/TimeChecker.java<|end_filename|>
package org.uclab.mm.icl.utils;

public class TimeChecker {
	public static long time;
	
	
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/hlca/GetHLCA.java<|end_filename|>
/*
 * 
Copyright [2016] [name of copyright owner <-Put your name]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
package mm.hlca;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.ModelFactory;

import mm.icl.hlc.ContextOntologyManager.ContextOntologyManager;
import mm.icl.hlc.HLC.TimeUtil;
import mm.icl.hlc.HLCBuilder.ContextInstantiator;
import mm.icl.hlc.HLCBuilder.ContextSynchronizer;
import mm.icl.hlc.HLCNotifier.HLCNotifier;
import mm.icl.hlc.HLCReasoner.HLCReasoner;

import org.apache.log4j.Logger;

public class TestHLCA {
	
	final static Logger logger = Logger.getLogger(TestHLCA.class);
	
	
	static final String directory = "E:\\ICL_LOG\\TDB";                                
	static final String ontologyFile = "file:////E:/ICL_LOG/TDB/context-v2-5.owl";     
	static final int windowSizeInSec = 15;  
	static final int simulationTimeInSec = 240; 
	static final int year = 2016; 
	static final int month = 4;  
	static final int day = 18;
	static final int hour = 10; 
	static final int minute = 8; 
	static final int second = 50;    
	public static void main(String[] args) {
		 long hlc_start = System.currentTimeMillis();
		 OntModel ontModel = ModelFactory.createOntologyModel( OntModelSpec.OWL_DL_MEM );   
		 ontModel.read(ontologyFile);

		 ContextOntologyManager mng = new ContextOntologyManager(directory, ontModel);
		 if(mng.correctInitialization()) {
			HLCReasoner r = new HLCReasoner(mng.getInferredContextOntology());
			HLCNotifier n = new HLCNotifier(mng.getContextOntology());
			ContextInstantiator inst = new ContextInstantiator(mng.getContextOntology());
			ContextSynchronizer sync = new ContextSynchronizer(mng.getContextOntology(), inst, r, n, null);
			TimeUtil util= new TimeUtil();
			Calendar windowStart = util.parseString("2016 04 18 10:08:50");
			Calendar simulationEnd = GregorianCalendar.getInstance();
			simulationEnd.setTime(windowStart.getTime());;
			simulationEnd.add(Calendar.SECOND, simulationTimeInSec);  
			while(windowStart.before(simulationEnd)){
				Calendar windowEnd = GregorianCalendar.getInstance();
				windowEnd.setTime(windowStart.getTime());;
				windowEnd.add(Calendar.SECOND, windowSizeInSec);   
				
				logger.info(" ");
				logger.info("-----------------------------------------------------------------------------------------------");
				logger.info("Synchronizing for window (" + windowStart.getTime() + ", " + windowEnd.getTime() + "]");
				sync.synchronizeTest(windowStart, windowEnd, r, n);
				windowStart.setTime(windowEnd.getTime());
			}
		}
		long elapsed = System.currentTimeMillis() - hlc_start;
		DateFormat df = new SimpleDateFormat("HH 'hours', mm 'mins,' ss 'seconds', SSS  'milliseconds'");
		df.setTimeZone(TimeZone.getTimeZone("GMT+0"));
		System.out.println("Time taken to Reason HLC: " + df.format(new Date(elapsed)));
	}
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/llm/SituationNotification.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.llm;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author Rizvi
 */
@XmlRootElement()
public class SituationNotification implements Serializable {
    
     private String UserID;
    //private List<SituationConditions> ListSConditions = new ArrayList<SituationConditions>();
    private SituationEvent situationEvent = new SituationEvent();

    /**
     * @return the SituationID
     */
    public String getUserID() {
        return UserID;
    }

    /**
     * @param UserID the SituationID to set
     */
    public void setUserID(String UserID) {
        this.UserID = UserID;
    }



    /**
     * @return the situationEvent
     */
    public SituationEvent getSituationEvent() {
        return situationEvent;
    }

    /**
     * @param situationEvent the situationEvent to set
     */
    public void setSituationEvent(SituationEvent situationEvent) {
        this.situationEvent = situationEvent;
    }

    
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/LLCRecognizer/LLCRecognizer.java<|end_filename|>
/**
Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
package org.uclab.mm.icl.llc.LLCRecognizer;

import java.util.ArrayList;

import org.uclab.mm.icl.data.DeviceData;
import org.uclab.mm.icl.llc.LLCManager.ContextLabel;
import org.uclab.mm.icl.llc.LLCManager.LLCUnifier;
import org.uclab.mm.icl.llc.MachineLearningTools.MachineLearning;
import org.uclab.mm.icl.llc.config.DeviceType;
import org.uclab.mm.icl.llc.config.RecognizerType;

/**
 *	Basic interface of the recognizers used in ICL
 * @author Nailbrainz
 */
public abstract class LLCRecognizer<InputDataType>{
    
	public static final boolean verbose = true;
	long userID;
    private LLCRecognizer(){}; //prohibited.
    
    ArrayList<InputDataType> inputDatas = new ArrayList<InputDataType>();
    
    public LLCRecognizer(long userID){
    	this.userID = userID;
    }
    
    /**
     * With this method, each child recognizer can receive Data sent from each sensor. It depends on each child class to whether consume the data or do nothing.
     * @param it Type of sensor sending the data
     * @param obj Data that sensor sends
     */
    public abstract void ConsumeData(DeviceType it, DeviceData obj);
    
    /**
     * Returns the RecognizerType of the current instance
     * @return RecognizerType of the current instance
     */
    public abstract RecognizerType getType();
    
    /**
     * Recognizes the low level context. Recognition methodology is dependent on each child class.
     * @param input Input data
     * @param timeStamp time of the llc
     * @return recognized low level context, in ContextLabel instance
     */
    public abstract ContextLabel recognize(final InputDataType input, String timeStamp);
    
    
    public Runnable getRunnable(String timeStamp, LLCUnifier unifier){
    	return new Runnable() { // new Handler and Runnable
            @Override
            public void run() {
            	while(isThresholdReached()){
            		InputDataType idd = inputDatas.get(0);
            		inputDatas.remove(0);
            		unifier.push(recognize(idd, timeStamp), getType());
            	}
            }
        };
    }
    protected void setData(InputDataType inputData){
    	inputDatas.add(inputData);
    }
    public boolean isThresholdReached(){
    	return inputDatas.size() != 0;
    }
}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/framework/RecInterpreter/Explanation/AbstractRecExplanation.java<|end_filename|>
/* Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.scl.framework.RecInterpreter.Explanation;

import org.uclab.scl.outputModel.InterpretationModel.InterpretedRecommendations;

public abstract class AbstractRecExplanation {
	 public abstract String parseAggregateVec(int[] aggregateVec) throws Exception;
	 public abstract InterpretedRecommendations handleExplanation(int[] interpRec, String duration, String context, String description) throws Exception;
	 public abstract String explanationSentenceTemplate(String rec, String duration, String sentence, String context) throws Exception;
	 public abstract String buildUrl(String recValue ) throws Exception;
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/HLCBuilder/ContextMapper.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.HLCBuilder;
import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.sparql.util.Utils;

import java.util.Calendar;
import java.util.Random;

import org.apache.log4j.Logger;

import mm.hlca.TestHLCAMapper;
import mm.icl.hlc.ContextOntologyManager.ContextHandler;
import mm.icl.hlc.OntologyTools.ContextOntology;
import mm.icl.hlc.OntologyTools.HLCA;
import mm.icl.hlc.OntologyTools.LowLevelContext;
import mm.icl.utils.FileUtil;

/**
 * Context Mapper. Component of HLCA which maps into ontological format the
 * labels plus metadata generated by the LLC Recognizers.
 * 
 * @author <NAME> and <NAME>
 * @version 2.5
 * @since 2015-11-12
 */
public class ContextMapper {
	
	/** The Constant logger. */
	final static Logger logger = Logger.getLogger(ContextMapper.class);
	/**
	 * Context Ontology which represents the Mining Minds Context Model.
	 */
	private ContextOntology ont;
	/**
	 * Identifier of the Context Mapper.
	 */
	private int mapperId;
	/**
	 * Counter of the number LLC instances generated by the Context Mapper.
	 */
	private long llcInstNum;
	
	/**
	 * Constructor of a new Context Mapper.
	 *
	 */
	
	private ContextHandler contextHandler = ContextHandler.getContextHandler();  
	
	/**
	 * Instantiates a new context mapper.
	 *
	 * @param ont the ont
	 */
	public ContextMapper(ContextOntology ont) {
		this.ont = ont;
		Random rand = new Random();
		this.mapperId = rand.nextInt(Integer.MAX_VALUE);
		this.llcInstNum = 0;
	}
	/**
	 * Method to map into ontological format the labels plus metadata generated
	 * by the LLC Recognizers.
	 * 
	 * @param llcLabel
	 *            Label (or category) of the new LLC.
	 * @param userId
	 *            Identifier of the user which has associated the LLC.
	 * @param startTime
	 *            Start time of the new LLC in the XSD dateTime format
	 *            "2015-08-10T11:05:30+09:00".
	 */
	public void mapLLC(String llcLabel, String userId, Calendar startTime) {
		OntModel llcModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);
		llcModel.setNsPrefix(HLCA.nsPrefix, HLCA.ns);
		Individual user = llcModel.createIndividual(HLCA.ns + "user_" + userId, ont.getUserClass());
		Literal time = llcModel.createTypedLiteral(Utils.calendarToXSDDateTimeString(startTime), XSDDatatype.XSDdateTime);

		if (llcLabel.equals(HLCA.noActivity))
			contextHandler.finalizePreviousLlc(ont.getLlcCategoryClass(HLCA.activityClassName), user, time); 
		else if (llcLabel.equals(HLCA.noLocation)){
			logger.error("No location recieved by Context Mapper");
			contextHandler.finalizePreviousLlc(ont.getLlcCategoryClass(HLCA.locationClassName), user, time); 
		}
		else if (llcLabel.equals(HLCA.noEmotion))
			contextHandler.finalizePreviousLlc(ont.getLlcCategoryClass(HLCA.emotionClassName), user, time);  
		else if (llcLabel.equals(HLCA.noFood)) 
		{	contextHandler.finalizePreviousLlc(ont.getLlcCategoryClass(HLCA.foodClassName), user, time);     
		}
		
		else if (llcLabel.equals(HLCA.noBloodGlucose)) 
		{	contextHandler.finalizePreviousLlc(ont.getLlcCategoryClass(HLCA.BloodGlucoseClassName), user, time);     
		}else if (llcLabel.equals(HLCA.noBloodPressure)) 
		{	contextHandler.finalizePreviousLlc(ont.getLlcCategoryClass(HLCA.BloodPressureClassName), user, time);     
		}else if (llcLabel.equals(HLCA.noWaterIntake)) 
		{	contextHandler.finalizePreviousLlc(ont.getLlcCategoryClass(HLCA.WaterIntakeClassName), user, time);     
		}

		
		else {
			OntClass llcClass = ont.getLlcTypeClass(HLCA.ns + llcLabel);
			if (llcClass != null) {
				long instanceId = 0;
				synchronized(this){
					instanceId = this.llcInstNum;
					this.llcInstNum++;
				}
				Individual llcIndiv = llcModel.createIndividual(HLCA.ns + "llc_" + String.format("%010d", this.mapperId)
						+ "_" + String.format("%019d", instanceId), llcClass);
				llcIndiv.addProperty(ont.getContextOfProp(), user);
				llcIndiv.addProperty(ont.getStartTimeProp(), time);
				LowLevelContext llc = new LowLevelContext(llcModel, ont);
				contextHandler.storeNewLlc(llc); 
			}
			else{
				logger.error ("[Context Mapper] LLC could not be mapped. " + llcLabel + " is not a valid label.");
				logger.info("[Context Mapper] LLC could not be mapped. " + llcLabel + " is not a valid label."); 
			}
		}
	}
	
	/**
	 * Gets the context handler.
	 *
	 * @return the context handler
	 */
	public ContextHandler getContextHandler() {
		return contextHandler;
	}
	
	/**
	 * Sets the context handler.
	 *
	 * @param contextHandler the new context handler
	 */
	public void setContextHandler(ContextHandler contextHandler) {
		this.contextHandler = contextHandler;
	}

}

<|start_filename|>supporting-layer/descriptive-analytics/src/assets/js/monthlyactivites.js<|end_filename|>
				   
				   AmCharts.makeChart("monthly_activities_chartdiv",
				{
					"type": "serial",
					"pathToImages": "http://cdn.amcharts.com/lib/3/images/",
					"categoryField": "date",
					"dataDateFormat": "YYYY-MM-DD",
					"categoryAxis": {
						"autoRotateCount": 0,
						"parseDates": true,
						"startOnAxis": true
					},
					"chartCursor": {},
					"chartScrollbar": {},
					"trendLines": [
						{
							"finalDate": "2014-03-20",
							"finalValue": 7,
							"id": "TrendLine-1",
							"initialDate": "2014-03-01",
							"initialValue": 7,
							"lineAlpha": 0.43,
							"lineColor": "#CC0000",
							"lineThickness": 3
						}
					],
					"graphs": [
						{
							"bullet": "round",
							"id": "AmGraph-1",
							"title": "Walking",
							"valueField": "Walking"
						},
						{
							"bullet": "round",
							"columnWidth": 0,
							"fillAlphas": 0.27,
							"id": "AmGraph-2",
							"title": "Running",
							"valueField": "Running"
						},
						{
							"bullet": "round",
							"id": "AmGraph-3",
							"title": "Standing",
							"valueField": "Standing"
						},
						{
							"bullet": "round",
							"id": "AmGraph-4",
							"title": "Sitting",
							"valueField": "Sitting"
						},
						{
							"bullet": "round",
							"id": "AmGraph-5",
							"title": "Jogging",
							"valueField": "Jogging"
						}
					],
					"guides": [],
					"valueAxes": [
						{
							"id": "durations",
							"title": "Minutes"
						}
					],
					"allLabels": [],
					"balloon": {},
					"legend": {
						"periodValueText": "Total : [[value.sum]]",
						"useGraphSettings": true,
						"valueAlign": "left"
					},
					"dataProvider": [
										
					
					
					{
					
						"date": "2015-05-05",
						
						"Walking": 0,"Running": 0,"Standing": 240,"Sitting": 90.05,"Jogging": 0},										
					
					
					{
					
						"date": "2015-05-06",
						
						"Walking": 0,"Running": 0,"Standing": 0,"Sitting": 360,"Jogging": 0},										
					
					
					{
					
						"date": "2015-05-07",
						
						"Walking": 0,"Running": 0,"Standing": 0,"Sitting": 360,"Jogging": 0},										
					
					
					{
					
						"date": "2015-05-08",
						
						"Walking": 0,"Running": 0,"Standing": 0,"Sitting": 79.9,"Jogging": 0},										
					
					
					{
					
						"date": "2015-05-09",
						
						"Walking": 0,"Running": 0,"Standing": 0,"Sitting": 0.05,"Jogging": 0},										
					
					
					{
					
						"date": "2015-05-10",
						
						"Walking": 0,"Running": 0,"Standing": 0,"Sitting": 0.05,"Jogging": 0},										
					
					
					{
					
						"date": "2015-05-11",
						
						                                    "Walking": 0,
                                    "Running": 0,
                                    "Standing": 0,
                                    "Sitting": 0,
                                    "Jogging": 0
						  },					                           
					]
				}
			);					
					
					


<|start_filename|>knowledge-curation-layer/DDKAT/src/main/java/org/uclab/mm/kcl/ddkat/modeltranslator/ModelTranslator.java<|end_filename|>
/**
 * Copyright [2017] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.mm.kcl.ddkat.modeltranslator;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.inra.qualscape.wekatexttoxml.WekaTextfileToXMLTextfile;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.apache.wink.json4j.JSONArray;
import org.apache.wink.json4j.JSONObject;
import org.apache.wink.json4j.OrderedJSONObject;

//TODO: Auto-generated Javadoc
/**
* This class processes the classification model, converts into XML model, and finally parses the XML model to extract the rules.
*/
public class ModelTranslator {
	
	/** The rule conditions. */
	private ArrayList<String> ruleConditions;
	
	/** The rule conclusion. */
	private ArrayList<String> ruleConclusions;
	
	/** base directory to store resource data files */
	private static final String BASE_DIR = System.getProperty("user.home") + "/DDKAT/resources/";
	
	/**
	 * Constructor to instantiate a new ModelTranslator object.
	 * @param algo_modelstr that contains algo, decision attribute, classification model, and file path information
	 * @throws Exception the exception
	 */    
    public ModelTranslator(String algo_modelstr) throws Exception {
    	
    	this.ruleConditions = new ArrayList<String>();
    	this.ruleConclusions = new ArrayList<String>();
    
       int rulesCounter = 0;
       int lastTrimIndex = 0;
       String treemodelStr ="";
     
       String[] parts = algo_modelstr.split("#####", 3);
       String algo = parts[0]; 
       String decisionattribute = parts[1]; 
       String modelstr = parts[2];
              
       //process the classification model based on decision tree algorithm
       if (algo.equals("J48")){
    	   	lastTrimIndex = modelstr.indexOf("Number of Leaves  :");
    	   	treemodelStr = modelstr.substring(36, lastTrimIndex-2);
    	   	System.out.println("\n\nDecision Tree:\n\n"+treemodelStr);
       	} else if (algo.equals("J48graft")) {
       		lastTrimIndex = modelstr.indexOf("Number of Leaves  :");
       		treemodelStr = modelstr.substring(41, lastTrimIndex-2);
       		treemodelStr = treemodelStr.replace("| ", "*****");
       		treemodelStr = treemodelStr.replace("|", " OR ");
       		treemodelStr = treemodelStr.replace("*****", "|");           
       	} else if (algo.equals("BFTree")) {
       		lastTrimIndex = modelstr.indexOf("Size of the Tree:");
       		treemodelStr = modelstr.substring(26, lastTrimIndex-2);
    	} else if (algo.equals("FT")) {
    		lastTrimIndex = modelstr.indexOf("Number of Leaves  :");
       		treemodelStr = modelstr.substring(29, lastTrimIndex-2);
       	} else if (algo.equals("LADTree")) {
            lastTrimIndex = modelstr.indexOf("Legend:");
            treemodelStr = modelstr.substring(49, lastTrimIndex-1);
       	} else if (algo.equals("RandomTree")) {
       		lastTrimIndex = modelstr.indexOf("Size of the tree :");
       		treemodelStr = modelstr.substring(24, lastTrimIndex-2);
       	} else if (algo.equals("REPTree")) {
       		lastTrimIndex = modelstr.indexOf("Size of the tree :");
       		treemodelStr = modelstr.substring(23, lastTrimIndex-2);
       	} else if (algo.equals("SimpleCart")) {
       		lastTrimIndex = modelstr.indexOf("Number of Leaf Nodes:");
       		treemodelStr = modelstr.substring(20, lastTrimIndex-2);
       	}
       
       
       String outputTxtFile = BASE_DIR + "treemodelFile.txt";
       PrintStream out = new PrintStream(new FileOutputStream(outputTxtFile));
       out.print(treemodelStr);out.close();
       
       File aTextfile = new File(outputTxtFile);
       String newtext="";
       BufferedReader reader = new BufferedReader(new FileReader(aTextfile));
       String line = "";
       while((line = reader.readLine()) != null)
       {
           String colonKeyword = ":";
           Boolean colonFound = Arrays.asList(line.split("")).contains(colonKeyword);
           if(colonFound){
               String[] lineArr = line.split(":");
               String tempConditionStr = lineArr[0];
               Boolean equalFound = Arrays.asList(tempConditionStr.split("")).contains("=");
               Boolean lessFound = Arrays.asList(tempConditionStr.split("")).contains("<");
               Boolean greaterFound = Arrays.asList(tempConditionStr.split("")).contains(">");
               if(!(equalFound | lessFound | greaterFound))
                   {
                   line = "RuleCondition = None : None";
                   }
               else{
                   String tempConclusionStr = lineArr[1];                     
                   String[] tempStrArr = tempConclusionStr.split("\\(");
                   tempConclusionStr = tempStrArr[0];
                   line = tempConditionStr + ":"+tempConclusionStr;
                   }
                
               }
        
           line = line.replaceAll("\\)\\|\\(", " OR_OPERATOR ");
           line = line.replaceAll("=\\(", " = \\(");
           line = line.replaceAll("\\! =", " !=");
  
           String orKeyword = "OR_OPERATOR";
           Boolean orFound = Arrays.asList(line.split(" ")).contains(orKeyword);
           if(orFound){          
               String condStr = line.substring(line.indexOf('('), line.indexOf(')')+1);
               String[] tempArr = condStr.split("OR_OPERATOR");
               String tempLeft = tempArr[0];
               tempLeft = tempLeft.trim();
               String tempRight = tempArr[1];
               tempRight = tempRight.trim();
               String replacedStr = tempLeft+"_OR_"+tempRight;
               line = line.replaceAll(condStr, replacedStr);
               line = line.replaceAll("\\(", "");
               line = line.replaceAll("\\)", "");
           } else{
               line = line.replaceAll("\\(", "");
               line = line.replaceAll("\\)", "");
           } 
           newtext += line + "\r\n";
       }
       reader.close();
       
       // XML model conversion 
       FileWriter writer = new FileWriter(aTextfile);
       writer.write(newtext);writer.close();
       
       String outputXMLFile = BASE_DIR + "treemodelFile.xml";
       File anXmlfile = new File(outputXMLFile);
       
       WekaTextfileToXMLTextfile xmlconversionObj = new WekaTextfileToXMLTextfile(aTextfile, anXmlfile, true, true);
       xmlconversionObj.writeXmlFromWekaText();
       
       String oldtext="";
       String newtextStr="";
       BufferedReader xmlReader = new BufferedReader(new FileReader(anXmlfile)); 
       String xmlLine = "";
       while((xmlLine = xmlReader.readLine()) != null)
           {
            oldtext += xmlLine + "\r\n";
           }
       xmlReader.close();
       // replace a word in a file
       newtextStr = oldtext.replaceAll("\"<", "\"&lt;");
       newtextStr = newtextStr.replaceAll(">\"", "&gt;\"");

       FileWriter xmlWriter = new FileWriter(outputXMLFile);
       xmlWriter.write(newtextStr);xmlWriter.close();
       
       String algoWriterFile = BASE_DIR + "selectedalgorithmFile.txt";
       FileWriter algoWriter = new FileWriter(algoWriterFile);
       algoWriter.write(algo);algoWriter.close();
      
       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
       DocumentBuilder builder = factory.newDocumentBuilder();
       Document source = builder.parse(new File(outputXMLFile));
       Node rootNode = source.getDocumentElement();
       Node currentNode=rootNode.getFirstChild();
       
       JSONArray jsonArr = new JSONArray();
            
       while (currentNode!=null) {
         // print node information
           if(currentNode.getNodeName().equals("Test")){
        	// print node information  
           }

         if ( currentNode.hasChildNodes()) {
           currentNode = currentNode.getFirstChild();
         }
         else {
             // leaf
             if(currentNode.getNodeName().equals("Output")){
  
            	 rulesCounter++;
                 String ruleConclusion = "";
                 ruleConclusion = decisionattribute+" = "+currentNode.getAttributes().getNamedItem("decision").getNodeValue();
           
                 int pathnodes_counter = 0;
                 String ruleCondition = " ";
                 String conditionAttribute = " ";
                 String conditionOperator = " ";
                 String conditionValue = " ";
                 String ruleConditions = " ";
                 Node pathNode = currentNode;

                 while(pathNode.getParentNode().getNodeName().equals("Test")){
                     pathnodes_counter++;
                     pathNode = pathNode.getParentNode();
                     }

                 pathNode = currentNode;
                 String ruleConditionsArr[] = new String[pathnodes_counter];
                 int arrIndex = pathnodes_counter-1;
                 
                 
                 while(pathNode.getParentNode().getNodeName().equals("Test")){
                     conditionAttribute = pathNode.getParentNode().getAttributes().getNamedItem("attribute").getNodeValue();
                     conditionOperator = pathNode.getParentNode().getAttributes().getNamedItem("operator").getNodeValue();
                     conditionValue = pathNode.getParentNode().getAttributes().getNamedItem("value").getNodeValue();
                     ruleCondition = conditionAttribute + " " + conditionOperator + " " + conditionValue;
                     ruleConditionsArr[arrIndex] = ruleCondition;
                     arrIndex--;
                     pathNode = pathNode.getParentNode();
                                          
                     }
                 
                 for(int i=0; i<pathnodes_counter; i++){
                     ruleConditions = ruleConditions.concat(ruleConditionsArr[i] + " AND ");
                     }

                 ruleConditions = ruleConditions.substring(0,ruleConditions.length()-5);
                 ruleConditions = ruleConditions.trim();

                 System.out.println(" \n RULE = "+Integer.toString(rulesCounter)+", Conditions = "+ruleConditions+", Conclusion = "+ruleConclusion);
                       
                 JSONObject jsonObj = new OrderedJSONObject();
               
                 jsonObj.put("ruleID", Integer.toString(rulesCounter));
                 jsonObj.put("ruleConditions", ruleConditions);
                 jsonObj.put("ruleConclusion", ruleConclusion);
          
                 jsonArr.put(jsonObj);
               
                 this.ruleConditions.add(ruleConditions);
                 this.ruleConclusions.add(ruleConclusion);
             } 
             
             // find the parent level
             while (currentNode.getNextSibling()==null && currentNode != rootNode){
            	 // use child-parent link to get to the parent level
            	 currentNode=currentNode.getParentNode();
             	 }

             currentNode = currentNode.getNextSibling();
         }
       }
                   
       JSONObject mainJsonObj = new JSONObject();
       mainJsonObj.put("decisiontreeRules", jsonArr);
	
    }
    
    
    public ArrayList<String> getRuleConditions() {
		return ruleConditions;
	}

	public void setRuleConditions(ArrayList<String> ruleConditions) {
		this.ruleConditions = ruleConditions;
	}
    
    
	public ArrayList<String> getRuleConclusions() {
		return ruleConclusions;
	}

	public void setRuleConclusions(ArrayList<String> ruleConclusions) {
		this.ruleConclusions = ruleConclusions;
	}
    
	
}


<|start_filename|>knowledge-curation-layer/DDKAT/src/main/java/org/uclab/mm/kcl/ddkat/dataselector/FeatureEvaluator.java<|end_filename|>
/**
 * Copyright [2017] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.mm.kcl.ddkat.dataselector;

import java.io.File;
import java.util.ArrayList;

import org.apache.commons.io.FileUtils;
import org.apache.wink.json4j.JSONArray;
import org.apache.wink.json4j.OrderedJSONObject;

import weka.attributeSelection.ChiSquaredAttributeEval;
import weka.attributeSelection.GainRatioAttributeEval;
import weka.attributeSelection.InfoGainAttributeEval;
import weka.attributeSelection.Ranker;
import weka.attributeSelection.SignificanceAttributeEval;
import weka.attributeSelection.SymmetricalUncertAttributeEval;
import weka.core.Instances;
import weka.core.converters.CSVLoader;

//TODO: Auto-generated Javadoc
/**
* This class computes the features' scores.
*/
public class FeatureEvaluator {
	
	/** The features titles list */
	private ArrayList<String> featureTitles;
	
	/** The features scores list */
	private ArrayList<Double> featureScores;
	
	/** The features weights list */
	private ArrayList<Double> featureWeights;
	
	/** The features priorities list */
	private ArrayList<Double> featurePriorities;
	
	/** base directory to store resource data files */
	private static final String BASE_DIR = System.getProperty("user.home") + "/DDKAT/resources/";

	/**
	 * Constructor to instantiate a new FeatureEvaluator object.
	 *
	 * @param json the data string
	 * @param data the data set
	 * @throws Exception the exception
	 */
	
	public FeatureEvaluator(String json, Instances data) throws Exception {
	//	public FeatureEvaluator(String json, Instances data, String filePath) throws Exception {
		
		this.featureTitles = new ArrayList<String>();
		this.featureScores = new ArrayList<Double>();
		this.featureWeights = new ArrayList<Double>();
		this.featurePriorities = new ArrayList<Double>();
		
		OrderedJSONObject jsonObject = new OrderedJSONObject(json.toString());
        JSONArray jsontokenArray = jsonObject.getJSONArray("unprocessed_data");
        String csvString="";
        String str;
        for(int i=0;i<jsontokenArray.length();i++){
        	str= jsontokenArray.get(i).toString();
            str = str.substring(1, str.length()-1);
            csvString += str +"\n";
            }
        
        String filePath = BASE_DIR + "FeaturesEvaluationDataSet.csv";
        File file=new File(filePath);
        // if file does not exists, then create it
        if (!file.exists()) 	
        	file.createNewFile();
                        
        FileUtils.writeStringToFile(file,csvString);
        
        CSVLoader loader=new CSVLoader();
        loader.setSource(new File(filePath));
        data=loader.getDataSet();
        
        if (data.classIndex() == -1)
            data.setClassIndex(data.numAttributes() - 1); 
           
        int numUnlabeledAttributes = data.numAttributes()-1;
        double[] minmaxValues = new double[2];
        double min, max;
           
        String[] options = new String[1];
        options[0] = "-T -1.7976931348623157E308 -N -1"; // confidenceFactor = 0.25, minNumObject = 2
        Ranker atrank = new Ranker();
        atrank.setOptions(options);   

        weka.attributeSelection.AttributeSelection atsel = new weka.attributeSelection.AttributeSelection();        

        //  Information Gain Attribute Evaluator
        InfoGainAttributeEval infoGainAttrEval = new InfoGainAttributeEval();
        atsel.setEvaluator(infoGainAttrEval);
        atsel.setSearch(atrank);
        atsel.SelectAttributes(data);
        double[] infoGainRanks = new double[numUnlabeledAttributes];
        for (int i = 0; i < numUnlabeledAttributes; i++) {
        	infoGainRanks[i] = Math.round(10000 * infoGainAttrEval.evaluateAttribute(i)) / 10000d;
         	}
        minmaxValues = computerMinMaxValues(infoGainRanks);
        min = minmaxValues[0];
        max = minmaxValues[1];
        double[] scaledInfoGainRanks = new double[numUnlabeledAttributes];
        for (int i = 0; i < numUnlabeledAttributes; i++) {
        	scaledInfoGainRanks[i] = Math.round(10000 * ((infoGainRanks[i]-min)/(max-min))) / 10000d;
        	}

        //  Gain Ratio Attribute Evaluator
        GainRatioAttributeEval gainRatioAttrEval = new GainRatioAttributeEval();
        atsel.setEvaluator(gainRatioAttrEval);
        atsel.setSearch(atrank);
        atsel.SelectAttributes(data);
        double[] gainRatioRanks = new double[numUnlabeledAttributes];
        for (int i = 0; i < numUnlabeledAttributes; i++) {
        	gainRatioRanks[i] = Math.round(10000 * gainRatioAttrEval.evaluateAttribute(i)) / 10000d;
        	}
        minmaxValues = computerMinMaxValues(gainRatioRanks);
        min = minmaxValues[0];
        max = minmaxValues[1];
        double[] scaledGainRatioRanks = new double[numUnlabeledAttributes];
        for (int i = 0; i < numUnlabeledAttributes; i++) {
        	scaledGainRatioRanks[i] = Math.round(10000 * ((gainRatioRanks[i]-min)/(max-min))) / 10000d;
        	}

        //  Chi Squared Attribute Evaluator
        ChiSquaredAttributeEval chiSquaredAttrEval = new ChiSquaredAttributeEval();
        atsel.setEvaluator(chiSquaredAttrEval);
        atsel.setSearch(atrank);
        atsel.SelectAttributes(data);
        double[] chiSquaredRanks = new double[numUnlabeledAttributes];
        for (int i = 0; i < numUnlabeledAttributes; i++) {
        	chiSquaredRanks[i] = Math.round(10000 * chiSquaredAttrEval.evaluateAttribute(i)) / 10000d;
        	}
        minmaxValues = computerMinMaxValues(chiSquaredRanks);
        min = minmaxValues[0];
        max = minmaxValues[1];
        double[] scaledChiSquaredRanks = new double[numUnlabeledAttributes];
        for (int i = 0; i < numUnlabeledAttributes; i++) {
        	scaledChiSquaredRanks[i] = Math.round(10000 * ((chiSquaredRanks[i]-min)/(max-min))) / 10000d;
        	}

        //  Symmetrical Uncert Attribute Evaluator
        SymmetricalUncertAttributeEval symmetricalUncertAttrEval = new SymmetricalUncertAttributeEval();
        atsel.setEvaluator(symmetricalUncertAttrEval);
        atsel.setSearch(atrank);
        atsel.SelectAttributes(data);
        double[] symmetricalUncertRanks = new double[numUnlabeledAttributes];
        for (int i = 0; i < numUnlabeledAttributes; i++) {
        	symmetricalUncertRanks[i] = Math.round(10000 * symmetricalUncertAttrEval.evaluateAttribute(i)) / 10000d;
        	}
        minmaxValues = computerMinMaxValues(symmetricalUncertRanks);
        min = minmaxValues[0];
        max = minmaxValues[1];
        double[] scaledSymmetricalUncertRanks = new double[numUnlabeledAttributes];
        for (int i = 0; i < numUnlabeledAttributes; i++) {
        	scaledSymmetricalUncertRanks[i] = Math.round(10000 * ((symmetricalUncertRanks[i]-min)/(max-min))) / 10000d;
        	}

        //  Significance Attribute Evaluator
        SignificanceAttributeEval significanceAttrEval = new SignificanceAttributeEval();
        atsel.setEvaluator(significanceAttrEval);
        atsel.setSearch(atrank);
        atsel.SelectAttributes(data);
        double[] significanceRanks = new double[numUnlabeledAttributes];
        for (int i = 0; i < numUnlabeledAttributes; i++) {
        	significanceRanks[i] = Math.round(10000 * significanceAttrEval.evaluateAttribute(i)) / 10000d;
        	}
        minmaxValues = computerMinMaxValues(significanceRanks);
        min = minmaxValues[0];
        max = minmaxValues[1];
        double[] scaledSignificanceRanks = new double[numUnlabeledAttributes];
        for (int i = 0; i < numUnlabeledAttributes; i++) {
        	scaledSignificanceRanks[i] = Math.round(10000 * ((significanceRanks[i]-min)/(max-min))) / 10000d;
        	}

        double attributeSum;

        double[] combinedRanks = new double[numUnlabeledAttributes]; 
        double combinedranksSum = 0;

        for (int i = 0; i < numUnlabeledAttributes; i++) {
        	attributeSum = scaledInfoGainRanks[i] + scaledGainRatioRanks[i] + scaledChiSquaredRanks[i] + scaledSymmetricalUncertRanks[i] + scaledSignificanceRanks[i]; 
        	combinedRanks[i] = Math.round(10000 * attributeSum) / 10000d;
        	combinedranksSum = combinedranksSum + combinedRanks[i];
        	}

        double[][] tempArray = new double[numUnlabeledAttributes][2];
        String[] attributesTitles = new String[numUnlabeledAttributes];
        double[] attributesScores = new double[numUnlabeledAttributes];
        double[] attributesWeights = new double[numUnlabeledAttributes];
        double[] attributesPriorities = new double[numUnlabeledAttributes];

        for (int j = 0; j < numUnlabeledAttributes; j++) {         
        	tempArray[j][0] = j;
        	tempArray[j][1] = combinedRanks[j];
        	}

        double temp;
        for(int i=0; i < numUnlabeledAttributes; i++){
        	for(int j=1; j < (numUnlabeledAttributes-i); j++){          
        		if(combinedRanks[j-1] < combinedRanks[j]){
        			//swap the elements!
        			temp = combinedRanks[j-1];
        			combinedRanks[j-1] = combinedRanks[j];
        			combinedRanks[j] = temp;
        			}
        		}
        	}         

        for (int j = 0; j < numUnlabeledAttributes; j++) { 
        	for (int k = 0; k < numUnlabeledAttributes; k++) { 
        		if (combinedRanks[j] == tempArray[k][1]){
        			attributesTitles[j] = data.attribute((int)tempArray[k][0]).toString();
        			String res[] = attributesTitles[j].split("\\s+");
                    attributesTitles[j] = res[1];
        
        			this.featureTitles.add(attributesTitles[j]);
        			break;
        			}
        		}
        	attributesScores[j] = Math.round(10000 * (combinedRanks[j]/9)) / 100d;
        	attributesWeights[j] = Math.round(10000 * (combinedRanks[j]/combinedranksSum)) / 100d;
        	attributesPriorities[j] = Math.round(attributesScores[j] * attributesWeights[j]) / 100d;
        	this.featureScores.add(attributesScores[j]);
        	this.featureWeights.add(attributesWeights[j]);
    		this.featurePriorities.add(attributesPriorities[j]);
          	
        	System.out.println(attributesTitles[j]+" is "+attributesScores[j]+" % Important");
       		}
		
	}
	
	public ArrayList<String> getFeatureTitles() {
		return featureTitles;
	}

	public void setFeatureTitles(ArrayList<String> featureTitles) {
		this.featureTitles = featureTitles;
	}

	public ArrayList<Double> getFeatureScores() {
		return featureScores;
	}

	public void setFeatureScores(ArrayList<Double> featureScores) {
		this.featureScores = featureScores;
	}
	
	public ArrayList<Double> getFeatureWeights() {
		return featureWeights;
	}

	public void setFeatureWeights(ArrayList<Double> featureWeights) {
		this.featureWeights = featureWeights;
	}
	
	public ArrayList<Double> getFeaturePriorities() {
		return featurePriorities;
	}

	public void setFeaturePriorities(ArrayList<Double> featurePriorities) {
		this.featurePriorities = featurePriorities;
	}
	

	protected double[] computerMinMaxValues(double dataArr[]) throws Exception {
        //assign first element of an array to largest and smallest
        double smallest = dataArr[0];
        double largetst = dataArr[0];

        for(int i=1; i< dataArr.length; i++){
            if(dataArr[i] > largetst)
                largetst = dataArr[i];
            else if(dataArr[i] < smallest)
                smallest = dataArr[i];
            }

        double minmaxArr[] = new double[2];
        minmaxArr[0] = smallest;
        minmaxArr[1] = largetst;

        return minmaxArr;
        }
	

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/ic/dataadapter/UserAccelerometerDataDataAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.ic.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.ic.UserAccelerometerData;
import org.uclab.mm.datamodel.ic.UserGPSData;

/**
 * This is UserDataAdapter class which implements the Data Access Interface for CRUD operations
 * @author Taqdir
 */
public class UserAccelerometerDataDataAdapter implements DataAccessInterface {

    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(UserAccelerometerDataDataAdapter.class);
    public UserAccelerometerDataDataAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving UserAccelerometerData. 
     * @param objUserAccelerometerData
     * @return List of String
     */
    @Override
    public List<String> Save(Object objUserAccelerometerData) {
        UserAccelerometerData objInnerUserAccelerometerData = new UserAccelerometerData();
        objInnerUserAccelerometerData =  (UserAccelerometerData) objUserAccelerometerData;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_UserAccelerometerData(?, ?, ?, ?, ?, ?)}");
            
            List<Float> arrX = objInnerUserAccelerometerData.getxCoordinate();
            List<Float> arrY =  objInnerUserAccelerometerData.getyCoordinate();
            List<Float> arrZ =  objInnerUserAccelerometerData.getzCoordinate();
            for(int i = 0; i < objInnerUserAccelerometerData.getxCoordinate().size(); i++)
            {
                objCallableStatement.setLong("UserDeviceID", objInnerUserAccelerometerData.getUserDeviceId());
                objCallableStatement.setFloat("XCoordinate", arrX.get(i));
                objCallableStatement.setFloat("YCoordinate", arrY.get(i));
                objCallableStatement.setFloat("ZCoordinate", arrZ.get(i));
                
                
                 SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss");	// updated
                Date dttimestamp =  sdf.parse(objInnerUserAccelerometerData.getTimeStamp());
                
                Timestamp tstimestamp = new Timestamp(dttimestamp.getYear(),dttimestamp.getMonth(), dttimestamp.getDate(), dttimestamp.getHours(), dttimestamp.getMinutes(), dttimestamp.getSeconds(), 00);
                objCallableStatement.setTimestamp("timestamp", tstimestamp);

                objCallableStatement.registerOutParameter("UserAccelerometerDataID", Types.BIGINT);
                objCallableStatement.execute();
            }
            
            Long intUserAccelerometerDataID = objCallableStatement.getLong("UserAccelerometerDataID");
            objDbResponse.add(String.valueOf(intUserAccelerometerDataID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Use rAccelerometer Data added successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in adding User Accelerometer Data");
        	objDbResponse.add("Error in adding User Accelerometer Data");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for saving UserAccelerometerData. 
     * Not Implemented
     * 
     */
    @Override
    public <T> List<String> Update(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for retrieving UserAccelerometerData. 
     * @param objUserAccelerometerData
     * @return List of UserAccelerometerData
     */
     @Override
    public List<UserAccelerometerData> RetriveData(Object objUserAccelerometerData) {
        UserAccelerometerData objOuterUserAccelerometerData = new UserAccelerometerData();
        List<UserAccelerometerData> objListInnerUserAccelerometerData = new ArrayList<UserAccelerometerData>();
        objOuterUserAccelerometerData =  (UserAccelerometerData) objUserAccelerometerData;
        
        try
        {
            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UserGPSDataByUserID(?, ?, ?)}");
            objCallableStatement.setLong("UserDeviceID", objOuterUserAccelerometerData.getUserDeviceId());
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
            Date dtStartTimeStamp = sdf.parse(objOuterUserAccelerometerData.getTimeStamp());
            
            Timestamp tsStartTimeStamp = new Timestamp(dtStartTimeStamp.getYear(),dtStartTimeStamp.getMonth(), dtStartTimeStamp.getDate(), dtStartTimeStamp.getHours(), dtStartTimeStamp.getMinutes(), dtStartTimeStamp.getSeconds(), 00);
            objCallableStatement.setTimestamp("StartTimeStamp", tsStartTimeStamp);
                
            Date dtEndTimeStamp = sdf.parse(objOuterUserAccelerometerData.getTimeStamp());//  updated
            Timestamp tsEndTimeStamp = new Timestamp(dtEndTimeStamp.getYear(),dtEndTimeStamp.getMonth(), dtEndTimeStamp.getDate(), dtEndTimeStamp.getHours(), dtEndTimeStamp.getMinutes(), dtEndTimeStamp.getSeconds(), 00);
            objCallableStatement.setTimestamp("EndTimeStamp", tsEndTimeStamp);
            
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                UserAccelerometerData objInnerUserAccelerometerData = new UserAccelerometerData();
                objInnerUserAccelerometerData.setUserAccelerometerDataId(objResultSet.getLong("UserGPSDataID"));
                objInnerUserAccelerometerData.setUserDeviceId(objResultSet.getLong("UserDeviceID"));
                Timestamp tstimestamp = objResultSet.getTimestamp("timestamp"); //updated
                objInnerUserAccelerometerData.setTimeStamp(tstimestamp.toString()); //updated
                objListInnerUserAccelerometerData.add(objInnerUserAccelerometerData);
            }
            objConn.close();
            logger.info("Use rAccelerometer Data loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading User Accelerometer Data");
        }   
        return objListInnerUserAccelerometerData;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/outputModel/RecModel/PhyActivityFacts.java<|end_filename|>
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.uclab.scl.outputModel.RecModel;

/**
 * 
 * @author User
 */
public class PhyActivityFacts {

  private String factDate;

  private long factID;

  private String factDescription;

  private long situationID;

  private String supportingLinks;

  private int factStatusID;

  private String factStatusDescription;

  public String getFactDate() {
    return factDate;
  }

  public void setFactDate(String factDate) {
    this.factDate = factDate;
  }

  public long getFactID() {
    return factID;
  }

  public void setFactID(long factID) {
    this.factID = factID;
  }

  public String getFactDescription() {
    return factDescription;
  }

  public void setFactDescription(String factDescription) {
    this.factDescription = factDescription;
  }

  public long getSituationID() {
    return situationID;
  }

  public void setSituationID(long situationID) {
    this.situationID = situationID;
  }

  public String getSupportingLinks() {
    return supportingLinks;
  }

  public void setSupportingLinks(String supportingLinks) {
    this.supportingLinks = supportingLinks;
  }

  public int getFactStatusID() {
    return factStatusID;
  }

  public void setFactStatusID(int factStatusID) {
    this.factStatusID = factStatusID;
  }

  public String getFactStatusDescription() {
    return factStatusDescription;
  }

  public void setFactStatusDescription(String factStatusDescription) {
    this.factStatusDescription = factStatusDescription;
  }

  @Override
  public String toString() {
    return "ClassPojo [factDate = " + factDate + ", factID = " + factID
        + ", factDescription = " + factDescription + ", situationID = "
        + situationID + ", supportingLinks = " + supportingLinks
        + ", factStatusID = " + factStatusID + ", factStatusDescription = "
        + factStatusDescription + "]";
  }

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/test/java/org/uclab/mm/datamodel/sl/dataadapter/testcases/ExpertReviewAdapterTest.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sl.dataadapter.testcases;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.uclab.mm.datamodel.AbstractDataBridge;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.DatabaseStorage;
import org.uclab.mm.datamodel.sl.ExpertReview;
import org.uclab.mm.datamodel.sl.dataadapter.ExpertReviewAdapter;

/**
 * This is a class for testing the insertion, fetching, and update of ExpertReview
 * @author <NAME>
 *
 */

public class ExpertReviewAdapterTest {

	/**
	 * This is function for testing the insertion, fetching, and update of ExpertReview 
	 */
	@Test
	public void test() {
		/* Preparing input object for insertion*/
		ExpertReview objOuterExpertReview = new ExpertReview();
		ExpertReview objInnerExpertReview = new ExpertReview();
		List<ExpertReview> objListExpertReview = new  ArrayList<ExpertReview>();
		
		objOuterExpertReview.setUserID(2L);
		objOuterExpertReview.setUserExpertID(35L);
		objOuterExpertReview.setReviewDescription("You are doing well");
		objOuterExpertReview.setReviewDate("2016 12 12 02:30:01");
		objOuterExpertReview.setReviewStatusID(1);
	
		/* Testing of insertion function*/
		 DataAccessInterface objDAInterface = new ExpertReviewAdapter();
         AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
         List<String> lstResponse = objADBridge.SaveExpertReview(objOuterExpertReview);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerExpertReview.setUserID(2L);
        	 objInnerExpertReview.setRequestType("ByUserID");
        	 DataAccessInterface objDAInterfaceRetrieval = new ExpertReviewAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListExpertReview = objADBridgeRetrieval.RetriveExpertReview(objInnerExpertReview);
        	 objInnerExpertReview = objListExpertReview.get(0);
         }
         
         assertEquals(objOuterExpertReview.getReviewDescription(), objInnerExpertReview.getReviewDescription());
         
         /* Testing of Update function*/
         objInnerExpertReview.setReviewStatusID(2);
         objInnerExpertReview.setReviewDate("2016 12 12 02:30:01");
         DataAccessInterface objDAInterfaceUpdate = new ExpertReviewAdapter();
         AbstractDataBridge objADBridgeUpdate = new DatabaseStorage(objDAInterfaceUpdate);
         lstResponse = objADBridgeUpdate.UpdateExpertReview(objInnerExpertReview);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerExpertReview.setUserID(2L);
        	 objInnerExpertReview.setRequestType("ByUserID");
        	 DataAccessInterface objDAInterfaceRetrieval = new ExpertReviewAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListExpertReview = objADBridgeRetrieval.RetriveExpertReview(objInnerExpertReview);
        	 objInnerExpertReview = objListExpertReview.get(0);
         }
         
         assertEquals(objInnerExpertReview.getReviewStatusID(), 2);
	}

}


<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/monitoring/PhysicalActivityMonitor.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */
package org.uclab.mm.dcl.llm.monitoring;

import java.sql.SQLException;
import java.sql.*;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.uclab.mm.dcl.llm.objectmodel.SituationConditions;
import org.uclab.mm.dcl.llm.objectmodel.SituationEvent;
import org.uclab.mm.dcl.llm.objectmodel.SituationNotification;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import org.uclab.mm.dcl.llm.objectmodel.SituationLog;
import org.apache.log4j.Logger;
import org.uclab.mm.dcl.llm.objectmodel.FoodLog;

/**
 *
 * @author Rizvi
 * This class is responsible to monitor the physical activities. It will not only monitor the activities but 
 * also perform all those actions which are required to share the monitored information with the 
 * wellness services. This class implements an interface of the monitoring strategy which has a declaration 
 * of monitoring functions. 
 */
public class PhysicalActivityMonitor implements MonitoringStrategy{

  static Logger log = Logger.getLogger(PhysicalActivityMonitor.class.getName());

  /**
   *
   * @param conn
   * @param a
   * @throws SQLException 
   * This method is the manager of the steps perform to manage the monitored activities. The stored procedure is used to 
   * filter out all those activities which have crossed the mentioned threshold by the expert.  This method after obtaining the 
   * monitored activity, build the object which consist of monitored activity and constraints related to that to 
   * communicate it with wellness services.
   * 
   */
  public void doMonitor(Connection conn, String a) throws SQLException{

    List<SituationConditions> objListSituationConditions = new ArrayList<SituationConditions>();
    SituationEvent objSituationEvent = new SituationEvent();
    SituationNotification objSituationNotification = new SituationNotification();
    SituationConditions objSituationConditionsMonitor = new SituationConditions();
    SituationConditions objSituationConditionsMeasuring = new SituationConditions();
    SituationConditions objSituationConditionsConstraints = new SituationConditions();
    SituationLog objSituationLog = new SituationLog();
    String situationLogID = null;
    RestServiceNotification objRestServiceNotification = null;

    CallableStatement callableStatement = conn.prepareCall("{call usp_PhysicalActivitiesMonitor()}");
    ResultSet rs = callableStatement.executeQuery();
    if (rs != null){

      while (rs.next()){

        String stActivity = rs.getString("Activity");
        String stActivityOperator = rs.getString("ActivityOperator");
        String stActivityValue = rs.getString("Activityvalue");
        String stActivityDataType = rs.getString("ActivityDataType");

        String stMeasuringMetric = rs.getString("MeasuringMetric");
        String stMeasuringOperator = rs.getString("MeasuringOperator");
        String stMeasuringTarget = rs.getString("MeasuringTargetValue");
        int scltime = Integer.parseInt(stMeasuringTarget);
        scltime = scltime / 60;
        String stMeasuringTargetValue = scltime + "h";
        String stMeasuringDataType = rs.getString("MeasuringDataType");

        String stUserID = rs.getString("UserID");
        String stActivityID = rs.getString("ActivityID");
        String stActivityTarget = rs.getString("ActivityTargetDuration");
        int sllogtime = Integer.parseInt(stActivityTarget);
        sllogtime = sllogtime / 60;

        String stActivityTargetDuration = sllogtime + "h"; //rs.getString("ActivityTargetDuration");
        String stSituationdate = rs.getString("Situationdate");// not using due to date format.

        String stConstraintKey = rs.getString("ConstraintKey");
        String stConstraintOperator = rs.getString("ConstraintOperator");
        String stConstraintValue = rs.getString("ConstraintValue");
        String stConstraintDataType = rs.getString("ConstraintDataType");

        objSituationLog.setUserID(stUserID);
        objSituationLog.setSituationCategoryID(stActivityID);
        objSituationLog.setSituationDescription(stActivityTargetDuration);
        objSituationLog.setSituationDate();
        // situationLogID=getSituationLog(objSituationLog);

        objSituationConditionsMonitor.setConditionKey(stActivity);
        objSituationConditionsMonitor.setConditionValue(stActivityValue);
        objSituationConditionsMonitor.setConditionValueOperator(stActivityOperator);
        objSituationConditionsMonitor.setConditionType(stActivityDataType);

        objSituationConditionsMeasuring.setConditionKey(stMeasuringMetric);
        objSituationConditionsMeasuring.setConditionValue(stMeasuringTargetValue);
        objSituationConditionsMeasuring.setConditionValueOperator(stMeasuringOperator);
        objSituationConditionsMeasuring.setConditionType(stMeasuringDataType);

        objSituationConditionsConstraints.setConditionKey(stConstraintKey);
        objSituationConditionsConstraints.setConditionValue(stConstraintValue);
        objSituationConditionsConstraints.setConditionValueOperator(stConstraintOperator);
        objSituationConditionsConstraints.setConditionType(stConstraintDataType);

        System.out.println("********** Situation Triggered **********");
        System.out.println("\t User Id:" + stUserID);
        System.out.println("\t Situation Details:");
        System.out.println("\t Current Activity:" + objSituationConditionsMonitor.getConditionValue());
        System.out.println("\t Activity Duration:" + objSituationConditionsMeasuring.getConditionValue());
        System.out.println("*****************************************\n");
        System.out.println("****** SCL Recomendation Response *******");

        objListSituationConditions.add(objSituationConditionsConstraints);
        objListSituationConditions.add(objSituationConditionsMonitor);
        objListSituationConditions.add(objSituationConditionsMeasuring);

        objSituationEvent.setListSConditions(objListSituationConditions);
        objSituationEvent.setSituationID(situationLogID);
        objSituationNotification.setSituationEvent(objSituationEvent);
        objSituationNotification.setUserID(stUserID);
        objRestServiceNotification = new RestServiceNotification();
        //objRestServiceNotification.notifyToRestService(objSituationNotification, "http://172.16.58.3:8080/SCLMiningMind2.5/webresources/SCLService/PushPARecommendation");

        log.debug(stUserID + " " + stMeasuringMetric + " " + stMeasuringTarget);
        //  path of log file C:/usr/home/log4j

        System.out.println(stUserID + " " + stMeasuringMetric + " " + stMeasuringTarget);
      }
    }
  }

  /**
   * 
   * @param objFoodLog 
   */
  public void doMonitor(FoodLog objFoodLog){

  }

  /**
   *
   * @param objSituationLog
   * @return This method is used to update the information in log to get the
   * respective logid for further usage of SCL for reasoning.
   */

  protected static String getSituationLog(SituationLog objSituationLog){
    String situationLogID = null;
    try{
      ClientConfig config = new DefaultClientConfig();
      config.getClasses().add(JacksonJsonProvider.class);
      Client client = Client.create(config);
      final String baseURI = "http://172.16.58.3:8080/MMDataCurationRestfulService/webresources/ServiceCuration/AddSituation";
      WebResource srv = client.resource(UriBuilder.fromUri(baseURI).build());
      ClientResponse serverResponse = srv.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, objSituationLog);
      situationLogID = serverResponse.getEntity(new GenericType<List<String>>(){
      }).get(0);
    } catch (Exception exp){
      String error = exp.getMessage();
      System.err.println(error + ": ");
      exp.printStackTrace();
    }
    return situationLogID;
  }

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/llm/LifelogMonitorActivity.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.llm;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author <NAME>
 */
@Entity
public class LifelogMonitorActivity implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    
    private Long userID;
    private String startTime;
    private String endTime;
    private int timeInterval;
    private int thrashold;
    private int activityID;
    private int totalTime;
    private String activityDescription;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof LifelogMonitorActivity)) {
            return false;
        }
        LifelogMonitorActivity other = (LifelogMonitorActivity) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.llm.LifelogMonitorActivity[ id=" + id + " ]";
    }

    /**
     * @return the userID
     */
    public Long getUserID() {
        return userID;
    }

    /**
     * @param userID the userID to set
     */
    public void setUserID(Long userID) {
        this.userID = userID;
    }

    /**
     * @return the startTime
     */
    public String getStartTime() {
        return startTime;
    }

    /**
     * @param startTime the startTime to set
     */
    public void setStartTime(String startTime) {
        this.startTime = startTime;
    }

    /**
     * @return the endTime
     */
    public String getEndTime() {
        return endTime;
    }

    /**
     * @param endTime the endTime to set
     */
    public void setEndTime(String endTime) {
        this.endTime = endTime;
    }

    /**
     * @return the timeInterval
     */
    public int getTimeInterval() {
        return timeInterval;
    }

    /**
     * @param timeInterval the timeInterval to set
     */
    public void setTimeInterval(int timeInterval) {
        this.timeInterval = timeInterval;
    }

    /**
     * @return the thrashold
     */
    public int getThrashold() {
        return thrashold;
    }

    /**
     * @param thrashold the thrashold to set
     */
    public void setThrashold(int thrashold) {
        this.thrashold = thrashold;
    }

    /**
     * @return the activityID
     */
    public int getActivityID() {
        return activityID;
    }

    /**
     * @param activityID the activityID to set
     */
    public void setActivityID(int activityID) {
        this.activityID = activityID;
    }

    /**
     * @return the totalTime
     */
    public int getTotalTime() {
        return totalTime;
    }

    /**
     * @param totalTime the totalTime to set
     */
    public void setTotalTime(int totalTime) {
        this.totalTime = totalTime;
    }

    /**
     * @return the activityDescription
     */
    public String getActivityDescription() {
        return activityDescription;
    }

    /**
     * @param activityDescription the activityDescription to set
     */
    public void setActivityDescription(String activityDescription) {
        this.activityDescription = activityDescription;
    }
    
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/test/java/org/uclab/mm/datamodel/sc/dataadapter/testcases/UserPreferredActivitiesAdapterTest.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc.dataadapter.testcases;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.uclab.mm.datamodel.AbstractDataBridge;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.DatabaseStorage;
import org.uclab.mm.datamodel.sc.UserPreferredActivities;
import org.uclab.mm.datamodel.sc.dataadapter.UserPreferredActivitiesAdapter;

/**
 * This is a class for testing the insertion, fetching, and update of UserPreferredActivities
 * @author <NAME>
 *
 */

public class UserPreferredActivitiesAdapterTest {

	/**
	 * This is function for testing the insertion, fetching, and update of UserPreferredActivities 
	 */
	@Test
	public void test() {
		/* Preparing input object for insertion*/
		UserPreferredActivities objOuterUserPreferredActivities = new UserPreferredActivities();
		UserPreferredActivities objInnerUserPreferredActivities = new UserPreferredActivities();
		List<UserPreferredActivities> objListUserPreferredActivities = new  ArrayList<UserPreferredActivities>();
		
		objOuterUserPreferredActivities.setUserId(2L);
		objOuterUserPreferredActivities.setActivityId(1);
		objOuterUserPreferredActivities.setPreferenceLevelId(1);
	
		/* Testing of insertion function*/
		 DataAccessInterface objDAInterface = new UserPreferredActivitiesAdapter();
         AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
         List<String> lstResponse = objADBridge.SaveUserPreferredActivities(objOuterUserPreferredActivities);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerUserPreferredActivities.setUserId(2L);
        	 DataAccessInterface objDAInterfaceRetrieval = new UserPreferredActivitiesAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListUserPreferredActivities = objADBridgeRetrieval.RetriveUserPreferredActivities(objInnerUserPreferredActivities);
        	 objInnerUserPreferredActivities = objListUserPreferredActivities.get(0);
         }
         
         assertEquals(objOuterUserPreferredActivities.getActivityId(), objInnerUserPreferredActivities.getActivityId());
         
         /* Testing of Update function*/
         objInnerUserPreferredActivities.setActivityId(3);
         DataAccessInterface objDAInterfaceUpdate = new UserPreferredActivitiesAdapter();
         AbstractDataBridge objADBridgeUpdate = new DatabaseStorage(objDAInterfaceUpdate);
         lstResponse = objADBridgeUpdate.UpdateUserPreferredActivities(objInnerUserPreferredActivities);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerUserPreferredActivities.setUserId(2L);
        	 DataAccessInterface objDAInterfaceRetrieval = new UserPreferredActivitiesAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListUserPreferredActivities = objADBridgeRetrieval.RetriveUserPreferredActivities(objInnerUserPreferredActivities);
        	 objInnerUserPreferredActivities = objListUserPreferredActivities.get(0);
         }
         
         assertEquals(objInnerUserPreferredActivities.getActivityId(), 3);
	}

}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/datamodel/SituationNotification.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.datamodel;

import java.io.Serializable;

import org.codehaus.jackson.annotate.JsonProperty;

/**
 * 
 * @author Rizvi
 */
public class SituationNotification implements Serializable{
  
  @JsonProperty("UserID")
  private String UserID;
  // private List<SituationConditions> ListSConditions = new
  // ArrayList<SituationConditions>();
  @JsonProperty("situationEvent")
  private SituationEvent situationEvent = new SituationEvent();

  /**
   * @return the SituationID
   */
  public String getUserID() {
    return UserID;
  }

  /**
   * @param SituationID
   *          the SituationID to set
   */
  public void setUserID(String UserID) {
    this.UserID = UserID;
  }

  /**
   * @return the ListSConditions
   */
  // public List<SituationConditions> getListSConditions() {
  // return ListSConditions;
  // }
  //
  // /**
  // * @param ListSConditions the ListSConditions to set
  // */
  // public void setListSConditions(List<SituationConditions> ListSConditions) {
  // this.ListSConditions = ListSConditions;
  // }

  /**
   * @return the situationEvent
   */
  public SituationEvent getSituationEvent() {
    return situationEvent;
  }

  /**
   * @param situationEvent
   *          the situationEvent to set
   */
  public void setSituationEvent(SituationEvent situationEvent) {
    this.situationEvent = situationEvent;
  }

  @Override
  public String toString() {
    String keyValue = "";
    keyValue += situationEvent.toString();

    return keyValue;
  }

}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/LLCManager/User.java<|end_filename|>
/*
Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.LLCManager;

import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.log4j.Logger;
import org.uclab.mm.icl.data.DeviceData;
import org.uclab.mm.icl.llc.LLCRecognizer.LLCRecognizer;
import org.uclab.mm.icl.llc.config.ContextType;
import org.uclab.mm.icl.llc.config.DeviceType;
import org.uclab.mm.icl.llc.config.RecognizerType;
import org.uclab.mm.icl.utils.TimeUtil;


/**
 * Note : this class is intended to be thread-safe
 * User class, which invokes independent recognizer threads for each registered recognizer,
 * and counter thread for each registered context
 * @author Nailbrainz
 */
public class User {
	private final static Logger logger = Logger.getLogger(User.class);
	private  ArrayList<AtomicReference<String> > curLabels = new ArrayList<AtomicReference<String>>();
	Long userID;
    MajorityVoting unifier;
    //AtomicBoolean isEatingFood = new AtomicBoolean(false);
    
    ExecutorService es;
    ArrayList<LLCRecognizer> recognizers = new ArrayList<LLCRecognizer>();
    ArrayList<AtomicBoolean> isContCounterRunning = new ArrayList<AtomicBoolean>();
    TimeUtil util = new TimeUtil();
    LLCNotifier notifier = new LLCNotifier();
    
    
    /**
     * Unique Constructor of user
     * @param userID user ID to generate
     * @param es Global executor service
     * @param bq Blocking queue for sending data to other layers
     */
    public User(Long userID, ExecutorService es/*, BlockingQueue<SendingItem> bq*/){
        this.userID = userID;
        
        //for each context type, initialize the counters and current labels
        for(int i = 0; i<ContextType.values().length; i++){
        	isContCounterRunning.add(new AtomicBoolean(false));
        	String[] labels = ContextType.values()[i].getLabels();
        	curLabels.add(new AtomicReference<String>(labels[labels.length-1])); // set to No(ContextName)
        }
        
        unifier = new MajorityVoting(/*bq,*/ userID, curLabels);
        this.es = es;
        
        //initialize each registered recognizers
        for(RecognizerType rec: RecognizerType.values()){
        	if(rec.isOn()){
        		recognizers.add(rec.getRecognizer(userID));
            	logger.info("recognizer added : " + rec.toString() + " of user " + userID);
        	}
        }
    }
    
    
    
   
    /**
     * With the data sent from Sensor, fill the buffer of each recognizers
     * @param it SensorType which sends the data
     * @param data data which is is sent from the SensorType
     * @param data_timeStamp timestamp of the data, designating the time when the data is sent from the device, in MM format.
     * @throws NullPointerException The data object could be null, if the program in the sensor is not well coded.
     */
	public void fillBuffer(DeviceType it, DeviceData data, String data_timeStamp) throws NullPointerException{ 
		
		//for each context, check whether the counter is running and run the counter if it is not running
		for(ContextType cont: ContextType.values()){
			if(!isContCounterRunning.get(cont.getValue()).get()){
				isContCounterRunning.get(cont.getValue()).set(true);
		    	es.execute(new LLCCounter(userID, data_timeStamp, es, unifier, notifier, cont, isContCounterRunning.get(cont.getValue())));
			}
        }
		
		/*
		for(RecognizerType rec: RecognizerType.values()){ //for each registered recognizers
			if(!rec.isOn())continue;
			LLCRecognizer curRec = recognizers.get(rec.getValue());
			curRec.ConsumeData(it, data); //consume the current sensor data
			if(curRec.isThresholdReached()) //if threashold reached, call the recognizer
			{
				es.execute(curRec.getRunnable(data_timeStamp, unifier));
			}
        }*/
		for(LLCRecognizer rec: recognizers){ //for each registered recognizers
			rec.ConsumeData(it, data); //consume the current sensor data
			if(rec.isThresholdReached()) //if threashold reached, call the recognizer
			{
				es.execute(rec.getRunnable(data_timeStamp, unifier));
			}
        }
    }
	
	
	
	
	
	
	
	
	
	public ArrayList<AtomicReference<String> > getcurLabels(){
		return curLabels;
	}
	
	
	
/**
 * Fillbuffer function for the demo (food) scenario
 * @param timeStamp timestamp of the food context
 * @param image food image
 * @param tag tag string, from manual user input
 */
    public void fillBufferDemo(String timeStamp, byte[] image, String tag){
    	
    	for(RecognizerType rec: RecognizerType.values()){
    		if(rec.isOn()){
    			if(rec.equals(RecognizerType.VAR))continue;
        	}
        }
    }
}


<|start_filename|>supporting-layer/uiux-authoring-tool/JavaDoc/org/uclab/mm/sl/uiux/analytics/dispatcher/Dispatcher.html<|end_filename|>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_76-release) on Fri Dec 23 12:26:59 KST 2016 -->
<title>Dispatcher</title>
<meta name="date" content="2016-12-23">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
    try {
        if (location.href.indexOf('is-external=true') == -1) {
            parent.document.title="Dispatcher";
        }
    }
    catch(err) {
    }
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10,"i6":9,"i7":9};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!--   -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!--   -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Dispatcher.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev&nbsp;Class</li>
<li><a href="../../../../../../../org/uclab/mm/sl/uiux/analytics/dispatcher/TrackerBulkURLWrapper.html" title="class in org.uclab.mm.sl.uiux.analytics.dispatcher"><span class="typeNameLink">Next&nbsp;Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/uclab/mm/sl/uiux/analytics/dispatcher/Dispatcher.html" target="_top">Frames</a></li>
<li><a href="Dispatcher.html" target="_top">No&nbsp;Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
  allClassesLink = document.getElementById("allclasses_navbar_top");
  if(window==top) {
    allClassesLink.style.display = "block";
  }
  else {
    allClassesLink.style.display = "none";
  }
  //-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary:&nbsp;</li>
<li>Nested&nbsp;|&nbsp;</li>
<li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li>
<li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail:&nbsp;</li>
<li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li>
<li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!--   -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.uclab.mm.sl.uiux.analytics.dispatcher</div>
<h2 title="Class Dispatcher" class="title">Class Dispatcher</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.uclab.mm.sl.uiux.analytics.dispatcher.Dispatcher</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="typeNameLabel">Dispatcher</span>
extends java.lang.Object</pre>
<div class="block">The type Dispatcher.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.summary">
<!--   -->
</a>
<h3>Field Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/uclab/mm/sl/uiux/analytics/dispatcher/Dispatcher.html#DEFAULT_CONNECTION_TIMEOUT">DEFAULT_CONNECTION_TIMEOUT</a></span></code>
<div class="block">The constant DEFAULT_CONNECTION_TIMEOUT.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static long</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/uclab/mm/sl/uiux/analytics/dispatcher/Dispatcher.html#DEFAULT_DISPATCH_INTERVAL">DEFAULT_DISPATCH_INTERVAL</a></span></code>
<div class="block">The constant DEFAULT_DISPATCH_INTERVAL.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!--   -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../../org/uclab/mm/sl/uiux/analytics/dispatcher/Dispatcher.html#Dispatcher-org.uclab.mm.sl.uiux.analytics.UIUXAnalytics-java.net.URL-java.lang.String-">Dispatcher</a></span>(<a href="../../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html" title="class in org.uclab.mm.sl.uiux.analytics">UIUXAnalytics</a>&nbsp;UIUXAnalytics,
          java.net.URL&nbsp;apiUrl,
          java.lang.String&nbsp;authToken)</code>
<div class="block">Instantiates a new Dispatcher.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!--   -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/uclab/mm/sl/uiux/analytics/dispatcher/Dispatcher.html#forceDispatch--">forceDispatch</a></span>()</code>
<div class="block">Starts the dispatcher for one cycle if it is currently not working.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/uclab/mm/sl/uiux/analytics/dispatcher/Dispatcher.html#getConnectionTimeOut--">getConnectionTimeOut</a></span>()</code>
<div class="block">Connection timeout in milliseconds</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>long</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/uclab/mm/sl/uiux/analytics/dispatcher/Dispatcher.html#getDispatchInterval--">getDispatchInterval</a></span>()</code>
<div class="block">Gets dispatch interval.</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/uclab/mm/sl/uiux/analytics/dispatcher/Dispatcher.html#setConnectionTimeOut-int-">setConnectionTimeOut</a></span>(int&nbsp;timeOut)</code>
<div class="block">Timeout when trying to establish connection and when trying to read a response.</div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/uclab/mm/sl/uiux/analytics/dispatcher/Dispatcher.html#setDispatchInterval-long-">setDispatchInterval</a></span>(long&nbsp;dispatchInterval)</code>
<div class="block">Packets are collected and dispatched in batches, this intervals sets the pause between batches.</div>
</td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/uclab/mm/sl/uiux/analytics/dispatcher/Dispatcher.html#submit-java.lang.String-">submit</a></span>(java.lang.String&nbsp;query)</code>
<div class="block">Submit.</div>
</td>
</tr>
<tr id="i6" class="altColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/uclab/mm/sl/uiux/analytics/dispatcher/Dispatcher.html#urlEncodeUTF8-java.util.Map-">urlEncodeUTF8</a></span>(java.util.Map&lt;java.lang.String,java.lang.String&gt;&nbsp;map)</code>
<div class="block">For bulk tracking purposes</div>
</td>
</tr>
<tr id="i7" class="rowColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/uclab/mm/sl/uiux/analytics/dispatcher/Dispatcher.html#urlEncodeUTF8-java.lang.String-">urlEncodeUTF8</a></span>(java.lang.String&nbsp;param)</code>
<div class="block">http://stackoverflow.com/q/4737841</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!--   -->
</a>
<h3>Methods inherited from class&nbsp;java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.detail">
<!--   -->
</a>
<h3>Field Detail</h3>
<a name="DEFAULT_CONNECTION_TIMEOUT">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>DEFAULT_CONNECTION_TIMEOUT</h4>
<pre>public static final&nbsp;int DEFAULT_CONNECTION_TIMEOUT</pre>
<div class="block">The constant DEFAULT_CONNECTION_TIMEOUT.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../../../../../constant-values.html#org.uclab.mm.sl.uiux.analytics.dispatcher.Dispatcher.DEFAULT_CONNECTION_TIMEOUT">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="DEFAULT_DISPATCH_INTERVAL">
<!--   -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>DEFAULT_DISPATCH_INTERVAL</h4>
<pre>public static final&nbsp;long DEFAULT_DISPATCH_INTERVAL</pre>
<div class="block">The constant DEFAULT_DISPATCH_INTERVAL.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../../../../../constant-values.html#org.uclab.mm.sl.uiux.analytics.dispatcher.Dispatcher.DEFAULT_DISPATCH_INTERVAL">Constant Field Values</a></dd>
</dl>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!--   -->
</a>
<h3>Constructor Detail</h3>
<a name="Dispatcher-org.uclab.mm.sl.uiux.analytics.UIUXAnalytics-java.net.URL-java.lang.String-">
<!--   -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>Dispatcher</h4>
<pre>public&nbsp;Dispatcher(<a href="../../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html" title="class in org.uclab.mm.sl.uiux.analytics">UIUXAnalytics</a>&nbsp;UIUXAnalytics,
                  java.net.URL&nbsp;apiUrl,
                  java.lang.String&nbsp;authToken)</pre>
<div class="block">Instantiates a new Dispatcher.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>UIUXAnalytics</code> - the uiux analytics</dd>
<dd><code>apiUrl</code> - the api url</dd>
<dd><code>authToken</code> - the auth token</dd>
</dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!--   -->
</a>
<h3>Method Detail</h3>
<a name="getConnectionTimeOut--">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getConnectionTimeOut</h4>
<pre>public&nbsp;int&nbsp;getConnectionTimeOut()</pre>
<div class="block">Connection timeout in milliseconds</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>timeout in milliseconds</dd>
</dl>
</li>
</ul>
<a name="setConnectionTimeOut-int-">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setConnectionTimeOut</h4>
<pre>public&nbsp;void&nbsp;setConnectionTimeOut(int&nbsp;timeOut)</pre>
<div class="block">Timeout when trying to establish connection and when trying to read a response.
 Values take effect on next dispatch.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>timeOut</code> - timeout in milliseconds</dd>
</dl>
</li>
</ul>
<a name="setDispatchInterval-long-">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setDispatchInterval</h4>
<pre>public&nbsp;void&nbsp;setDispatchInterval(long&nbsp;dispatchInterval)</pre>
<div class="block">Packets are collected and dispatched in batches, this intervals sets the pause between batches.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>dispatchInterval</code> - in milliseconds</dd>
</dl>
</li>
</ul>
<a name="getDispatchInterval--">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getDispatchInterval</h4>
<pre>public&nbsp;long&nbsp;getDispatchInterval()</pre>
<div class="block">Gets dispatch interval.</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the dispatch interval</dd>
</dl>
</li>
</ul>
<a name="forceDispatch--">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>forceDispatch</h4>
<pre>public&nbsp;boolean&nbsp;forceDispatch()</pre>
<div class="block">Starts the dispatcher for one cycle if it is currently not working.
 If the dispatcher is working it will skip the dispatch interval once.</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the boolean</dd>
</dl>
</li>
</ul>
<a name="submit-java.lang.String-">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>submit</h4>
<pre>public&nbsp;void&nbsp;submit(java.lang.String&nbsp;query)</pre>
<div class="block">Submit.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>query</code> - the query</dd>
</dl>
</li>
</ul>
<a name="urlEncodeUTF8-java.lang.String-">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>urlEncodeUTF8</h4>
<pre>public static&nbsp;java.lang.String&nbsp;urlEncodeUTF8(java.lang.String&nbsp;param)</pre>
<div class="block">http://stackoverflow.com/q/4737841</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>param</code> - raw data</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>encoded string</dd>
</dl>
</li>
</ul>
<a name="urlEncodeUTF8-java.util.Map-">
<!--   -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>urlEncodeUTF8</h4>
<pre>public static&nbsp;java.lang.String&nbsp;urlEncodeUTF8(java.util.Map&lt;java.lang.String,java.lang.String&gt;&nbsp;map)</pre>
<div class="block">For bulk tracking purposes</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>map</code> - query map</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>String "?idsite=1&url=http://example.org&action_name=Test bulk log view&rec=1"</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!--   -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!--   -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Dispatcher.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev&nbsp;Class</li>
<li><a href="../../../../../../../org/uclab/mm/sl/uiux/analytics/dispatcher/TrackerBulkURLWrapper.html" title="class in org.uclab.mm.sl.uiux.analytics.dispatcher"><span class="typeNameLink">Next&nbsp;Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/uclab/mm/sl/uiux/analytics/dispatcher/Dispatcher.html" target="_top">Frames</a></li>
<li><a href="Dispatcher.html" target="_top">No&nbsp;Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
  allClassesLink = document.getElementById("allclasses_navbar_bottom");
  if(window==top) {
    allClassesLink.style.display = "block";
  }
  else {
    allClassesLink.style.display = "none";
  }
  //-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary:&nbsp;</li>
<li>Nested&nbsp;|&nbsp;</li>
<li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li>
<li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail:&nbsp;</li>
<li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li>
<li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!--   -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/framework/recbuilder/PatternMatcher.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.framework.recbuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.uclab.scl.Utilities.UtilityFacade;
import org.uclab.scl.datamodel.Conclusion;
import org.uclab.scl.datamodel.FiredRule;

/**
 * PatternMatcher
 * An implementation for the org.uclab.scl.framework.recbuilder.AbstractPatternMatcher
 * <p>
 * PatternMatcher uses forward chaining strategy to select all applicable rules for the particular situation.
 *  
 * @author Sadiq
 * @version 2.5
 * @since july 2014
 *
 */
public class PatternMatcher extends AbstractPatternMatcher{
  private static Logger LOG = LogManager.getRootLogger();
  
  /**
   * fires rule for a specific situation after reasoning
   * <p>
   * 
   * @param conditionsValue
   * @param rules
   * @return listOfMatchedRules
   * @throws UnsupportedTypeException 
   */
  @SuppressWarnings("unchecked")
  @Override
  public List<FiredRule> fireRule(Map<String, Object> conditionsValue, List<Map<String, Object>> rules) throws UnsupportedTypeException {
    List<FiredRule> firedRules = new ArrayList<FiredRule>();

    for (Map<String, Object> rule : rules) {
      List<Map<String, Object>> conditionsKeyList = (List<Map<String, Object>>) rule.get("conditionList");
      if (matchRule(conditionsValue, conditionsKeyList)) {
        List<Map<String, Object>> conclusionsList = (ArrayList<Map<String, Object>>) rule.get("conclusionList");
        int numberOfConditions = ((List<Map<String, Object>>) rule.get("conditionList")).size();
        FiredRule firedRule = new FiredRule(rule.get("ruleID").toString());
        firedRule.setRuleConclusion(rule.get("ruleConclusion").toString());
        firedRule.setConditionsKey(numberOfConditions);
        for (Map<String, Object> conclusionMap : conclusionsList) {
          Conclusion conclusion = new Conclusion(conclusionMap.get("conclusionKey").toString());
          conclusion.setConclusionValue(conclusionMap.get("conclusionValue").toString());
          conclusion.setConclusionOperator(conclusionMap.get("conclusionOperator").toString());
          firedRule.addConclusion(conclusion);
        }
        firedRules.add(firedRule);
      }
    }
    return firedRules;
  }
  
  /**
   * returns true if all conditions matched false other wise
   * 
   * @param conditionsValue
   * @param conditionsKeyList
   * @return boolean
   * @throws UnsupportedTypeException 
   */
  private boolean matchRule(Map<String, Object> conditionsValue, List<Map<String, Object>> conditionsKeyList) throws UnsupportedTypeException {
    boolean CONDITION_MATCHED = false;
    for (Map<String, Object> conditionsKey : conditionsKeyList) {
      CONDITION_MATCHED = false;
      for (String FactKey : conditionsValue.keySet()) {
        if (matchCondition(FactKey, conditionsValue.get(FactKey), conditionsKey)) {
          CONDITION_MATCHED = true;
          break;
        }
      }
      if (!CONDITION_MATCHED) {
        return false;
      }
    }
    return true;
  }

  /**
   * returns TRUE if FactValue and RuleValue matched according to the operator
   * defined in the rule, FALSE elsewhere.
   * 
   * @param factKey
   * @param factValue
   * @param condition
   * @return boolean
   */
  private boolean matchCondition(String factKey, Object factValue, Map<String, Object> condition) throws UnsupportedTypeException{
    Boolean matched = false;
    try {
      if(!factKey.equalsIgnoreCase(condition.get("conditionKey").toString()))
        return false;
      
      String conditionType = null;
      try {
        conditionType = condition.get("conditionType").toString();
      } catch (Exception ex) {
        LOG.error("ConditionType is null! Setting to 'String'");
        conditionType = "String";
      }
      
      switch (conditionType) {
      case "string":
      case "String":
        matched = TypeComparator.compare(factValue.toString(), condition.get("conditionValue").toString(), condition.get("conditionValueOperator").toString());
      break;
      case "Integer":
      case "integer":
      case "Int":
      case "int":
        matched = TypeComparator.compare(Integer.parseInt(factValue.toString()), Integer.parseInt(condition.get("conditionValue").toString()), condition.get("conditionValueOperator").toString());
      break;
      case "boolean":
      case "Boolean":
        matched = TypeComparator.compare((boolean) factValue.toString().equalsIgnoreCase("yes"), (boolean) condition.get("conditionValue").toString().equalsIgnoreCase("yes"), condition.get("conditionValueOperator").toString());
      break;
      case "Time":
      case "time":
        int factTimeSec = UtilityFacade.getComputationUtility().timeToSec(factValue.toString());
        int ruleTimeSec = UtilityFacade.getComputationUtility().timeToSec(condition.get("conditionValue").toString());
        matched = TypeComparator.compare(factTimeSec, ruleTimeSec, condition.get("conditionValueOperator").toString());
      break;
      default:
        //. LOG.error("Type: " + condition.get("conditionType") + " is not defined!");
        throw new UnsupportedTypeException("Type[" + conditionType.toString()+"] is not supported!");
      }
    } catch (Exception ex) {
      matched = false;
      LOG.error("Invalid type conversion " + ex.getMessage());
    }

    return matched;
  }
}


<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/dataaccess/SituationEventDAO.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */
package org.uclab.mm.dcl.llm.dataaccess;

import org.uclab.mm.dcl.llm.objectmodel.SituationEvents;

/**
 * This interface is to provide the specification for store and retrieve methods.
 * @author Rizvi
 */
public interface SituationEventDAO{
 /**
  * The method specification for persistently storage of situation provided by experts.
  * @param objSituationEvents 
  */
  public void persistentSituation(SituationEvents objSituationEvents);
/**
 * The method specification for retrieval of situation details provided by experts.
 * @return 
 */
  public SituationEvents retriveSituationEvents();

}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/rest/RestClients.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.rest;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;

import org.json.JSONArray;
import org.json.JSONObject;
/**
 * RestClient: 
 * Rest Services to connect MiningMinds DCL Layer.
 * 
 * @author Nailbrainz
 * @version 2.5
 * @since 2015-11-06
 */

import mm.icl.utils.*;

public class RestClients {
	
	RestClients(){
		
	}
	                               
	public static String[] labels = {"Jumping","Boredom","Running","Walking","Sitting","Subway","Bus","Cycling","LyingDown","Standing", "Jogging", "Hiking" ,"Climbing", "Descending"," Stretching", "Dancing", "Sweeping", "Eating" ,"Escalator", "Elevator", "Resting", "NoActivity"};
	
	public static synchronized int getIndex(String str)  {
		int ret = -1;
		for(int i = 0; i<labels.length; i++){
			if(labels[i].equals(str)){
				return i+1;
			}
		}
		return ret;
	}
	
	public static synchronized String addUserRecognizedHLC(long userID, String hlcdesc, String StartTime) throws Exception{
		URL url = new URL("http://192.168.127.12:8080/MMDataCurationRestfulService/webresources/InformationCuration/AddUserRecognizedHLC");
		URLConnection connection = url.openConnection();
		connection.setDoOutput(true);
		connection.setRequestProperty("Content-Type", "application/json");
		connection.setConnectTimeout(5000);
		connection.setReadTimeout(5000);
		
		OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
		
		JSONObject json = new JSONObject();
		
		
		JSONArray ary1 = new JSONArray();
		JSONObject item = new JSONObject();
		
		json.put("userId", Long.toString(userID));
		json.put("hLCLabel", hlcdesc);
		json.put("startTime", StartTime);
		out.write(json.toString());
		out.close();

		BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		String str = in.readLine();
		return str;
	}
	
	
	
	public static synchronized String sendDemo(String act, String emo, String loc, String con, String timeStamp) throws Exception{
		String ret = "";
		if(!act.equals("no"))actG = act;
		if(!emo.equals("no"))emoG = emo;
		if(!loc.equals("no"))locG = loc;
		if(!con.equals("no"))conG = con;
		
		
		TimeUtil tutil = new TimeUtil();
		timeStamp = tutil.toDemoStr(tutil.parseString(timeStamp));
		String query = "?time="+timeStamp+"&act="+act+"&emo="+emo+"&loc="+loc+"&con="+con;
		
		 String ENDPOINT ="http://1192.168.3.11/gathering.php";
        String url = ENDPOINT;
         String charset = "UTF-8";
         java.net.URLConnection connection = new URL(url + query).openConnection();
         connection.setRequestProperty("Accept-Charset", charset);
         
         if ( connection instanceof HttpURLConnection)
         {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            ret = httpConnection.getResponseCode() + " " + httpConnection.getResponseMessage();
         }
         else
         {
            return ("error!");
         }
		
		return ret;
	}
	
	static String actG = "no";
	static String emoG = "no";
	static String locG = "no";
	static String conG = "no";
	
	static{
		Thread t = new Thread(new Counter());
		t.start();
	}
	
	static class Counter implements Runnable{
		@Override
		public synchronized void run() {
			try {
				wait(1500);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
				while(true){
					try {
						wait(3000);
						TimeUtil tutil = new TimeUtil();
						String timeStamp = tutil.toDemoStr(Calendar.getInstance());
						String query = "?time="+timeStamp+"&act="+actG+"&emo="+emoG+"&loc="+locG+"&con="+conG;
						System.out.println("query is " + query);
						 String ENDPOINT ="http://163.180.116.210/gathering.php";
				         String charset = "UTF-8";
				         java.net.URLConnection connection = new URL(ENDPOINT + query).openConnection();
				         connection.setRequestProperty("Accept-Charset", charset);
				         if ( connection instanceof HttpURLConnection)   
				         {
				            HttpURLConnection httpConnection = (HttpURLConnection) connection;
				            System.out.println("RestClients.java"+ httpConnection.getResponseCode() + " " + httpConnection.getResponseMessage());
				         }
				         else
				         {
				        	 System.out.println("error!");
				         }
					} catch (Exception e) {
						e.printStackTrace();
					}
					
				}
				
			}
		}
}


<|start_filename|>knowledge-curation-layer/DDKAT/target/DDKAT/index.jsp<|end_filename|>
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    

<HTML><HEAD><TITLE>Data Driven Knowledge Acquisition</TITLE>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="css/ddka-interface.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/bootstrap.min.js" ></script>
<script type="text/javascript" src="js/jquery-1.8.0.min.js" ></script>
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css">

<script language="javascript">

$(document).ready(function(){
		
	$("#start_btn").click(function () {
    	document.forms['indexForm'].submit() ;
	    });
	
	});

</script>

</HEAD>
<BODY>
<TABLE id=header cellPadding=0 style="width: 100%">
  <TBODY>
  <TR>
    <TD align="left" class="style1">
	<img border="0" src="images/banner.jpg" height="106"></TD>
    <TD align="right" style="width: 30%">
	<img border="0" src="images/MM_logo.png" height="106"></TD>
    </TR></TBODY></TABLE>
<TABLE cellPadding=0>
  <TBODY>
  <TR>
    <TD id=tran1></TD></TR>
  <TR>
    <TD id=tran2 height="171"></TD></TR></TBODY></TABLE>
<TABLE id=menubar cellPadding=0>
  <TBODY>
  <TR>
    <TD>
     <TABLE style="WIDTH: 100%" cellSpacing=0 cellPadding=0 border=0>
        <TBODY>
        <TR>
          <TD align=right>
          <a href="index.jsp">
		  <img border="0" src="images/main.gif" height="21"></a>
          </TD>
		  </TR></TBODY></TABLE></TD></TR></TBODY></TABLE>
		  
		  
<TABLE id=main cellPadding=0 width="777" style="width: 100%">
  <TBODY>
  <TR>
    <TD id=leftMenu width="654" rowspan="2">
                 &nbsp;</TD>
    </TR></TBODY></TABLE>
    
    <TABLE align=center border=2 borderColor=#39597d width="82%">
              <TBODY>
              <TR>
                <TD>
        <br><br>
		<div align="center">
		     	<font size="5" color="#004584"><b>Data Driven Knowledge Acquisition Tool </b></font><br><br>&nbsp;
		     	
		     	<div class="row">
		     	<div class="col-md-8 col-md-offset-1" align="left" ><b>Data Driven Knowledge Acquisition Tool</b> 
						(DDKAT) is an web-based application that curates the knowledge using data-driven approach. This tool is designed for Mining Minds (MM) Platform and covers the data-driven part for Knowledge Curation Layer (KCL).<br><br>
						DDKAT acquires the data, preprocesses it, selects the appropriate decision trees algorithm, generates the classification model, and finally, produces the production rules. The main features include <b>Data Selection</b>, <b>Basic Preprocessing</b>, <b>Appropriate Algorithm Selection</b>, <b>Generation of Classification Model</b>, and <b>Creation of Shareable Production Rules</b>.</div>
				
				<div class="col-md-1" align="center" >
				<form method="POST" name='indexForm' action="dataselectionview">
					<button id="start_btn" class="btn btn-primary" type="button"><span class="glyphicon glyphicon-play"></span> Click to Start</button> 
   				</form>
				</div>
				</div>
				<br><br>
				<div class="row">		
				<div class="col-md-1 col-md-offset-1" align="center" ><img border="0" src="images/DD1.png" height="150"></div>
				<div class="col-md-1 col-md-offset-1" align="center" ><img border="0" src="images/FS.png" height="150"></div>
				<div class="col-md-1" align="center" ><img border="0" src="images/arrow.png" height="150"></div>
				<div class="col-md-2" align="center" ><img border="0" src="images/DT.png" height="150"></div>
				<div class="col-md-1" align="center" ><img border="0" src="images/arrow.png" height="150"></div>
				<div class="col-md-1" align="center" ><img border="0" src="images/DD.png" height="150"></div>
				</div>
				
				<br><br>
				   </div>
                    </TD></TR></TBODY></TABLE>
    <table align="center" style="width: 100%">
           <tr>
		<td style="width: 100%; text-align:center">
		<font size="1" color="#39597B">
        <script language="JavaScript">
            copyright = new Date();
            currentYear = copyright.getFullYear();
            document.write("" + currentYear + " Ubiquitous Computing Lab., Dept. of Computer Engg.");
            </script></font></td>
	</tr>
	<tr>
		<td style="width: 100%; text-align:center">
		<font size="1" color="#39597B">Kyung Hee University, Korea</font></td>
	</tr>
	      
                </table>
</BODY>

</HTML>

<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/datamodel/contextMapper/LocationMapper.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.datamodel.contextMapper;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class LocationMapper {
  private static Logger LOG = LogManager.getRootLogger();
  
  static HashMap<String, String> mapLocation = new HashMap<>();
  private static final String locatoinPath = "Location.txt";
  private static Scanner scanFile;
  
  public LocationMapper() {
    try {
      scanFile = new Scanner(this.getClass().getClassLoader().getResourceAsStream(locatoinPath));
    } catch (Exception exp) {
      LOG.debug(exp.getMessage());
    }
  }

  public HashMap locationMapper() throws FileNotFoundException {
    String readFile = null;
    String key = null;
    String value = "";
    int flag = 0;
    while (scanFile.hasNextLine()) {
      readFile = scanFile.nextLine();
      String array[] = readFile.split(",");
      key = array[0];
      while (flag < array.length) {
        if (flag == 0) {
          flag += 1;
        } else if (flag == 1) {
          value = array[flag];
          flag += 1;
        } else {
          value = value + "," + array[flag];
          flag += 1;
        }
        mapLocation.put(key, value);
      } // inner-while
      flag = 0;
      key = null;
      value = "";
    } // outer-while
    scanFile.close();
    return mapLocation;
  }// main
}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/interpreterdatamodel/Conclusion.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.interpreterdatamodel;
/**
 * @version MM v2.5
 * @author Afzal
 *
 */
public class Conclusion {
  String conclusionKey;
  String conclusionValue;
  String conclusionOperator;

  public Conclusion() {
  }

  public Conclusion(String conclusionKey) {
    this.conclusionKey = conclusionKey;
  }

  public String getConclusionKey() {
    return conclusionKey;
  }

  public void setConclusionKey(String conclusionKey) {
    this.conclusionKey = conclusionKey;
  }

  public String getConclusionValue() {
    return conclusionValue;
  }

  public void setConclusionValue(String conclusionValue) {
    this.conclusionValue = conclusionValue;
  }

  public String getConclusionOperator() {
    return conclusionOperator;
  }

  public void setConclusionOperator(String conclusionOperator) {
    this.conclusionOperator = conclusionOperator;
  }

}


<|start_filename|>supporting-layer/descriptive-analytics/src/assets/js/weeklyactivites.js<|end_filename|>
AmCharts.makeChart("weeklychartdiv",
				{
					"type": "serial",
					"pathToImages": "http://cdn.amcharts.com/lib/3/images/",
					"categoryField": "date",
					"dataDateFormat": "YYYY-MM-DD",
					"categoryAxis": {
						"autoRotateCount": 0,
						"parseDates": true,
						"startOnAxis": true
					},
					"chartCursor": {},
					"chartScrollbar": {},
					"trendLines": [
						{
							"finalDate": "2014-03-20",
							"finalValue": 7,
							"id": "TrendLine-1",
							"initialDate": "2014-03-01",
							"initialValue": 7,
							"lineAlpha": 0.43,
							"lineColor": "#CC0000",
							"lineThickness": 3
						}
					],
					"graphs": [
						{
							"bullet": "round",
							"id": "AmGraph-1",
							"title": "Walking",
							"valueField": "Walking"
						},
						{
							"bullet": "round",
							"columnWidth": 0,
							"id": "AmGraph-2",
							"title": "Running",
							"valueField": "Running"
						},
						{
							"bullet": "round",
							"id": "AmGraph-3",
							"title": "Standing",
							"valueField": "Standing"
						}
					],
					"guides": [],
					"valueAxes": [
						{
							"id": "durations",
							"title": "Minutes"
						}
					],
					"allLabels": [],
					"balloon": {},
					"legend": {
						"periodValueText": "Total : [[value.sum]]",
						"useGraphSettings": true,
						"valueAlign": "left"
					},
					"dataProvider": [
						{
							"date": "2014-03-01",
							"Walking": 8,
							"Running": 5,
							"Standing": 4
						},
						{
							"date": "2014-03-02",
							"Walking": 6,
							"Running": 7,
							"Standing": 5
						},
						{
							"date": "2014-03-03",
							"Walking": 2,
							"Running": 3,
							"Standing": 1
						},
						{
							"date": "2014-03-04",
							"Walking": 1,
							"Running": 3,
							"Standing": 3
						},
						{
							"date": "2014-03-05",
							"Walking": 2,
							"Running": 1,
							"Standing": 10
						},
						{
							"date": "2014-03-06",
							"Walking": 3,
							"Running": 2,
							"Standing": 1
						},
						{
							"date": "2014-03-07",
							"Walking": 6,
							"Running": 8,
							"Standing": 6
						}
					]
				}
			);

<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/test/java/org/uclab/mm/datamodel/ic/dataadapter/testcases/UserRecognizedHLCAdapterTest.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.ic.dataadapter.testcases;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.uclab.mm.datamodel.AbstractDataBridge;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.DatabaseStorage;
import org.uclab.mm.datamodel.ic.UserRecognizedHLC;
import org.uclab.mm.datamodel.ic.dataadapter.UserRecognizedHLCAdapter;

/**
 * This is a class for testing the insertion, fetching, and update of UserRecognizedHLC
 * @author <NAME>
 *
 */
public class UserRecognizedHLCAdapterTest {

	/**
	 * This is function for testing the insertion, fetching, and update of UserRecognizedHLC 
	 */
	@Test
	public void test() {
		
		/* Preparing input object for insertion*/
		UserRecognizedHLC objOuterUserRecognizedHLC = new UserRecognizedHLC();
		UserRecognizedHLC objInnerUserRecognizedHLC = new UserRecognizedHLC();
		List<UserRecognizedHLC> objListUserRecognizedHLC = new  ArrayList<UserRecognizedHLC>();
		
		objOuterUserRecognizedHLC.setUserId(2L);
		objOuterUserRecognizedHLC.sethLCLabel("Dinner");
		objOuterUserRecognizedHLC.setStartTime("2016 12 12 02:45:05");
	
		/* Testing of insertion function*/
		 DataAccessInterface objDAInterface = new UserRecognizedHLCAdapter();
         AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
         List<String> lstResponse = objADBridge.SaveUserRecognizedHLC(objOuterUserRecognizedHLC);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerUserRecognizedHLC.setUserId(2L);
        	 objInnerUserRecognizedHLC.setRequestType("LatestByUser");
        	 DataAccessInterface objDAInterfaceRetrieval = new UserRecognizedHLCAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListUserRecognizedHLC = objADBridgeRetrieval.RetriveUserRecognizedHLC(objInnerUserRecognizedHLC);
        	 objInnerUserRecognizedHLC = objListUserRecognizedHLC.get(0);
         }
         
         assertEquals(objOuterUserRecognizedHLC.gethLCLabel(), objInnerUserRecognizedHLC.gethLCLabel());
	}

}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/ContextOntologyManager/OntologyModelManager.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.ContextOntologyManager;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.query.ReadWrite;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.tdb.TDBFactory;
import mm.icl.hlc.OntologyTools.ContextOntology;
import mm.icl.hlc.OntologyTools.HLCA;
/**
 * Ontology Model Manager: Subcomponent of the Context Ontology Manager which
 * manages the Context Ontology persisted in the Context Ontology Storage.
 * 
 * @author <NAME> and <NAME>
 * @version 2.5
 * @since 2015-10-28
 */
public class OntologyModelManager {
	/**
	 * Collection of Context Instances and Context Ontology stored in the
	 * Context Ontology Storage.
	 */
	private static Dataset dataset;
	/**
	 * Method to initialize the Ontology Model Manager.
	 * 
	 * @param directory
	 *            Path to the directory where the Context Ontology Storage is
	 *            deployed.
	 */
	public static void initialize(String directory) {
		dataset = TDBFactory.createDataset(directory);
	}
	/**
	 * Method to load a Context Ontology, which represents the Mining Minds
	 * Context Model, to the Context Ontology Storage.
	 * 
	 * @param uri
	 *            Namespace of the Context Ontology.
	 * @param model
	 *            OntModel representation of the Context Ontology.
	 */
	private static void loadContextOntology(String uri, OntModel model) {
		dataset.begin(ReadWrite.WRITE);
		// Store context Ontology model to DB
		dataset.addNamedModel(uri, model);
		dataset.commit();
		dataset.end();
	}
	/**
	 * Method to load a Context Ontology to the Context Ontology Storage.
	 *
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 */
	public static void loadContextOntology(ContextOntology ont) {
		loadContextOntology(HLCA.ns, ont.getCtxModel());
	}
	/**
	 * Method to retrieve from the Context Ontology Storage the Context Ontology
	 * which represents the Mining Minds Context Model.
	 *
	 * @return OntModel representation of the Context Ontology.
	 */
	public static OntModel retrieveContextOntology() {
		dataset.begin(ReadWrite.READ);
		Model inst = dataset.getNamedModel(HLCA.ns);
		dataset.end();
		if (inst.isEmpty())
			return null;
		return ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, inst);
	}
}


<|start_filename|>knowledge-curation-layer/i-kat/src/main/java/org/uclab/mm/kcl/edkat/datamodel/dclcommunication/SituationConditions.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.kcl.edkat.datamodel.dclcommunication;

import java.io.Serializable;

public class SituationConditions implements Serializable {

	private String conditionKey;
    private String ConditionValueOperator;
    private String ConditionValue;
    private String ConditionType;
    
	public String getConditionKey() {
		return conditionKey;
	}
	public void setConditionKey(String conditionKey) {
		this.conditionKey = conditionKey;
	}
	public String getConditionValueOperator() {
		return ConditionValueOperator;
	}
	public void setConditionValueOperator(String conditionValueOperator) {
		ConditionValueOperator = conditionValueOperator;
	}
	public String getConditionValue() {
		return ConditionValue;
	}
	public void setConditionValue(String conditionValue) {
		ConditionValue = conditionValue;
	}
	public String getConditionType() {
		return ConditionType;
	}
	public void setConditionType(String conditionType) {
		ConditionType = conditionType;
	}
    
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/dc/LookupTables.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.dc;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author <NAME>
 */
@Entity
public class LookupTables implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof LookupTables)) {
            return false;
        }
        LookupTables other = (LookupTables) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.dc.LookupTables[ id=" + id + " ]";
    }
    
}


<|start_filename|>data-curation-layer/passive-data-reader/src/main/java/com/uclab/dcl/LifelogDataModel.java<|end_filename|>
package com.uclab.dcl;

import java.util.ArrayList;
/**
 * processing the request from other Module
 * this module required for make result to JSON Format
 * @author CSHSC
 *
 */
public class LifelogDataModel {

	private final String data_id;
	private final String data_name;
	private final ArrayList<Object> data_attributes;
	private final ArrayList<Object> data_values;

	public LifelogDataModel(String data_id, String data_name, ArrayList<Object> data_attributes,
			ArrayList<Object> data_values) {
		this.data_id = data_id;
		this.data_name = data_name;
		this.data_attributes = data_attributes;
		this.data_values = data_values;
	}

	public String getData_id() {
		return data_id;
	}

	public String getData_name() {
		return data_name;
	}

	public ArrayList<Object> getData_attributes() {
		return data_attributes;
	}

	public ArrayList<Object> getData_values() {
		return data_values;
	}

}


<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/monitoring/MonitoringContext.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */
package org.uclab.mm.dcl.llm.monitoring;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * This class provides the contextual information that the various Strategy implementations need.
 * @author Rizvi
 */
public class MonitoringContext{

  private MonitoringStrategy objMonitoringStrategy;
/**
 * This method is used to set the context of the monitoring strategy.
 * @param objMonitoringStrategy 
 */
  public MonitoringContext(MonitoringStrategy objMonitoringStrategy){
    this.objMonitoringStrategy = objMonitoringStrategy;
  }
/**
 * This method is used to execute the appropriate monitoring strategy
 * @param conn
 * @param objString
 * @throws SQLException 
 */
  public void executeStrategy(Connection conn, String objString) throws SQLException{
    objMonitoringStrategy.doMonitor(conn, objString);
  }

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/llm/SituationConditions.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.llm;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author Maqbool
 */
@XmlRootElement()
public class SituationConditions implements Serializable{

    private String conditionKey;
    private String ConditionValueOperator;
    private String ConditionValue;
    private String ConditionType;

    public SituationConditions()
    {
        
    }
    /**
     * @return the conditionKey
     */
    public String getConditionKey() {
        return conditionKey;
    }

    /**
     * @param conditionKey the conditionKey to set
     */
    public void setConditionKey(String conditionKey) {
        this.conditionKey = conditionKey;
    }

    /**
     * @return the ConditionValueOperator
     */
    public String getConditionValueOperator() {
        return ConditionValueOperator;
    }

    /**
     * @param ConditionValueOperator the ConditionValueOperator to set
     */
    public void setConditionValueOperator(String ConditionValueOperator) {
        this.ConditionValueOperator = ConditionValueOperator;
    }

    /**
     * @return the ConditionValue
     */
    public String getConditionValue() {
        return ConditionValue;
    }

    /**
     * @param ConditionValue the ConditionValue to set
     */
    public void setConditionValue(String ConditionValue) {
        this.ConditionValue = ConditionValue;
    }

    /**
     * @return the ConditionType
     */
    public String getConditionType() {
        return ConditionType;
    }

    /**
     * @param ConditionType the ConditionType to set
     */
    public void setConditionType(String ConditionType) {
        this.ConditionType = ConditionType;
    }


}


<|start_filename|>information-curation-layer/low-level-context-awareness/WebContent/WEB-INF/classes/iclconfig.json<|end_filename|>
"WindowConfig":{"Activity":6,"Emotion":9,"Location":12},"HLCAddress":"http://localhost:8080/icl_whole/icl/llc/","DCLAddress":"http://172.16.17.32:8080/MMDataCurationRestfulService/webresources/InformationCuration/","HLCDelay":20,"LLCAddress":"http://localhost:8080/icl_whole/icl/llc/","ActiveRecognizers":{"EmotionJH":true,"LocSan":true,"ARSang":true,"VARThien":true,"EmotionVUI":true}}

<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/framework/RecInterpreter/InterpreterPacket.java<|end_filename|>
/* Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.scl.framework.RecInterpreter;

import java.util.List;

import org.uclab.scl.interpreterdatamodel.InterpretationIngredients;
import org.uclab.scl.framework.AbstractInterpreterPacket;
import org.uclab.scl.outputModel.InterpretationModel.InterpretedRecommendations;

public class InterpreterPacket extends AbstractInterpreterPacket<InterpretationIngredients, List<InterpretedRecommendations>> {

  @Override
  public InterpretationIngredients getRecommendationInput() {
    return this.interpretationIngredients;
  }

  @Override
  public void setRecommendationInput(InterpretationIngredients recommendationInput) {
    this.interpretationIngredients = recommendationInput;
  }

  @Override
  public List<InterpretedRecommendations> getRecommendationOutput() {
    return this.InterpretedRecommendations;
  }

  @Override
  public void setRecommendationOutput(List<InterpretedRecommendations> recommendationOutput) {
    this.InterpretedRecommendations = recommendationOutput;
  }

}


<|start_filename|>supporting-layer/uiux-authoring-tool/analytics/templates/analytics/home.html<|end_filename|>
{% extends "base.html" %}

{% block content %}

<div class="right_col" role="main">
<div class="row">
              <div class="col-md-12 col-sm-12 col-xs-12">
                <div class="dashboard_graph x_panel">
                  <div class="row x_title">
                    <div class="col-md-6">
                      <h3> Applications list</h3>
                    </div>
                  </div>
                  <div class="x_content">
                    <div class="demo-container" style="height:250px">
                      <div id="placeholder3xx3" class="demo-placeholder" style="width: 100%; height:250px;">

                     {% for apps in app_list %}

                      <li> {{apps.app_name }}</li>

                      {% endfor%}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
 </div>
</div>
{% endblock %}

<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/HLCBuilder/ContextSynchronizer.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.HLCBuilder;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import org.apache.log4j.Logger;
import com.hp.hpl.jena.datatypes.xsd.XSDDateTime;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.ModelFactory;

import mm.icl.hlc.ContextOntologyManager.ContextHandler;
import mm.icl.hlc.HLCNotifier.HLCNotifier;
import mm.icl.hlc.HLCReasoner.HLCReasoner;
import mm.icl.hlc.OntologyTools.ContextOntology;
import mm.icl.hlc.OntologyTools.LowLevelContext;
import mm.icl.hlc.OntologyTools.NutritionContext;
import mm.icl.hlc.OntologyTools.PhysicalActivityContext;
import mm.icl.hlc.OntologyTools.ClinicalContext;
import mm.icl.rest.RestClients;
import mm.icl.utils.FileUtil;
/**
 * Context Synchronizer: Subcomponent of the HLC Builder which aligns concurrent
 * low-level contexts of the same user.
 * 
 * @author <NAME> and <NAME>
 * @version 2.5
 * @since 2015-11-06
 */
public class ContextSynchronizer {
	private static Logger logger = Logger.getLogger(ContextSynchronizer.class);
	
	/**
	 * Context Ontology which represents the Mining Minds Context Model.
	 */
	private ContextOntology ont;
	HLCReasoner r;
	HLCNotifier n;
	ExecutorService es;
	
	private ContextHandler contextHandler = ContextHandler.getContextHandler();
	
	/**
	 * Context Instantiator which is which is in charge of generating the
	 * unclassified HLC instances.
	 */
	private ContextInstantiator instantiator;
	/**
	 * Constructor of a new Context Synchronizer.
	 * 
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @param instantiator
	 *            Context Instantiator which is in charge of generating the
	 *            unclassified HLC instances.
	 * 
	 */
	public ContextSynchronizer(ContextOntology ont, ContextInstantiator instantiator, HLCReasoner r, HLCNotifier n, ExecutorService es) {
		this.ont = ont;
		this.instantiator = instantiator;
		this.r = r;
		this.n = n;
	}
	/**
	 * Method to align concurrent LLC in a given time window.
	 * 
	 * @param windowStart
	 *            Calendar representing the start time of the window.
	 * @param windowEnd
	 *            Calendar representing the end time of the window.
	 */
	public void synchronizeLlcInWindow(Calendar windowStart, Calendar windowEnd) {
		OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);
		Literal start = model.createTypedLiteral(windowStart);
		Literal end = model.createTypedLiteral(windowEnd);
		synchronizeLlcInWindow(start, end);
	}
	/**
	 * Method to align concurrent LLC in a given time window.
	 * 
	 * @param windowStart
	 *            xsd:dateTime typed Literal representing the start time of the
	 *            window
	 * @param windowEnd
	 *            xsd:dateTime typed Literal representing the start time of the
	 *            window
	 */
	private void runReasonerNotifier(PhysicalActivityContext hlc){
		es.execute(new Runnable(){
			@Override
			public void run() {
				PhysicalActivityContext classifiedHlc = r.inferHlc(hlc);
				n.notify(classifiedHlc);
			}
		});
	}
	private void runReasonerNotifier(NutritionContext Nuthlc){
		es.execute(new Runnable(){
			@Override
			public void run() {
				NutritionContext     classifiedNutHlc = r.inferHlc(Nuthlc);		 
				n.notify(classifiedNutHlc);						
			}
		});
	}
	private void runReasonerNotifier(ClinicalContext Clihlc){
		es.execute(new Runnable(){
			@Override
			public void run() {
				ClinicalContext     classifiedCliHlc = r.inferHlc(Clihlc);		 
				n.notify(classifiedCliHlc);						
			}
		});
	}
	private void synchronizeLlcInWindow(Literal windowStart, Literal windowEnd) {
		List<LowLevelContext> llcStartList = contextHandler.retrieveLlcStartingWithinWindow(windowStart, windowEnd);
		List<LowLevelContext> llcEndList = contextHandler.retrieveLlcEndingWithinWindow(windowStart, windowEnd);
		Iterator<LowLevelContext> itStart = llcStartList.iterator();
		Iterator<LowLevelContext> itEnd = llcEndList.iterator();
		if (itStart.hasNext() && itEnd.hasNext()) {
			LowLevelContext llcStart = itStart.next();
			Date dateStart = ((XSDDateTime) llcStart.getDataPropertyValue(ont.getStartTimeProp()).getValue())
					.asCalendar().getTime();
			LowLevelContext llcEnd = itEnd.next();
			Date dateEnd = ((XSDDateTime) llcEnd.getDataPropertyValue(ont.getEndTimeProp()).getValue()).asCalendar()
					.getTime();
			boolean finished = false;
			while (!finished) {
				if (!dateStart.after(dateEnd)) {
					Literal endTimeLlcStart = llcStart.getDataPropertyValue(ont.getEndTimeProp());
					if (endTimeLlcStart == null
							|| !dateStart.equals(((XSDDateTime) endTimeLlcStart.getValue()).asCalendar().getTime())) {
						List<LowLevelContext> listLlcConc = contextHandler.retrieveConcurrentLlcAtStartTime(llcStart);
						PhysicalActivityContext hlc = instantiator.instantiateNewHlcDueToLlcStart(llcStart, listLlcConc);
						NutritionContext Nuthlc =  instantiator.instantiateNewNutHlcDueToLlcStart(llcStart, listLlcConc);   
						ClinicalContext Clihlc =  instantiator.instantiateNewCliHlcDueToLlcStart(llcStart, listLlcConc);
						runReasonerNotifier(hlc);
						runReasonerNotifier(Nuthlc);  
						runReasonerNotifier(Clihlc);
					}
					if (itStart.hasNext()) {
						llcStart = itStart.next();
						dateStart = ((XSDDateTime) llcStart.getDataPropertyValue(ont.getStartTimeProp()).getValue())
								.asCalendar().getTime();
					} else {
						List<LowLevelContext> listLlcConc = contextHandler.retrieveConcurrentLlcAtEndTime(llcEnd);
						PhysicalActivityContext hlc = instantiator.instantiateNewHlcDueToLlcEnd(llcEnd, listLlcConc);
						NutritionContext Nuthlc  =  instantiator.instantiateNewNutHlcDueToLlcEnd(llcEnd, listLlcConc);
						ClinicalContext Clihlc  =  instantiator.instantiateNewCliHlcDueToLlcEnd(llcEnd, listLlcConc);
						runReasonerNotifier(hlc);
						runReasonerNotifier(Nuthlc);
						runReasonerNotifier(Clihlc);
						finished = true;
					}
				}
				else {
					List<LowLevelContext> listLlcConc = contextHandler.retrieveConcurrentLlcAtEndTime(llcEnd);
					PhysicalActivityContext hlc = instantiator.instantiateNewHlcDueToLlcEnd(llcEnd, listLlcConc);
					NutritionContext Nuthlc  = instantiator.instantiateNewNutHlcDueToLlcEnd(llcEnd, listLlcConc);    
					ClinicalContext Clihlc  = instantiator.instantiateNewCliHlcDueToLlcEnd(llcEnd, listLlcConc);
					runReasonerNotifier(hlc);
					runReasonerNotifier(Nuthlc);   
					runReasonerNotifier(Clihlc);
					if (itEnd.hasNext()) {
						llcEnd = itEnd.next();
						dateEnd = ((XSDDateTime) llcEnd.getDataPropertyValue(ont.getEndTimeProp()).getValue())
								.asCalendar().getTime();
					} else {
						Literal endTimeLlcStart = llcStart.getDataPropertyValue(ont.getEndTimeProp());
						if (endTimeLlcStart == null || !dateStart
								.equals(((XSDDateTime) endTimeLlcStart.getValue()).asCalendar().getTime())) {
							listLlcConc = contextHandler.retrieveConcurrentLlcAtStartTime(llcStart);
							hlc = instantiator.instantiateNewHlcDueToLlcStart(llcStart, listLlcConc);
							Nuthlc = instantiator.instantiateNewNutHlcDueToLlcStart(llcStart, listLlcConc);  
							Clihlc = instantiator.instantiateNewCliHlcDueToLlcStart(llcStart, listLlcConc);
							runReasonerNotifier(hlc);
							runReasonerNotifier(Nuthlc);   
							runReasonerNotifier(Clihlc);
						}
						finished = true;
					}
				}
			}
		}
		while (itStart.hasNext()) {
			LowLevelContext llcStart = itStart.next();
			Date dateStart = ((XSDDateTime) llcStart.getDataPropertyValue(ont.getStartTimeProp()).getValue())
					.asCalendar().getTime();
			Literal endTimeLlcStart = llcStart.getDataPropertyValue(ont.getEndTimeProp());
			if (endTimeLlcStart == null
					|| !dateStart.equals(((XSDDateTime) endTimeLlcStart.getValue()).asCalendar().getTime())) {
				List<LowLevelContext> listLlcConc = contextHandler.retrieveConcurrentLlcAtStartTime(llcStart);
				PhysicalActivityContext hlc = instantiator.instantiateNewHlcDueToLlcStart(llcStart, listLlcConc);
				NutritionContext Nuthlc = instantiator.instantiateNewNutHlcDueToLlcStart(llcStart, listLlcConc); 
				ClinicalContext Clihlc = instantiator.instantiateNewCliHlcDueToLlcStart(llcStart, listLlcConc); 
				runReasonerNotifier(hlc);
				runReasonerNotifier(Nuthlc);   
				runReasonerNotifier(Clihlc);   
			}
		}
		while (itEnd.hasNext()) {
			LowLevelContext llcEnd = itEnd.next();
			List<LowLevelContext> listLlcConc = contextHandler.retrieveConcurrentLlcAtEndTime(llcEnd);
			PhysicalActivityContext hlc = instantiator.instantiateNewHlcDueToLlcEnd(llcEnd, listLlcConc);
			NutritionContext Nuthlc =  instantiator.instantiateNewNutHlcDueToLlcEnd(llcEnd, listLlcConc);
			ClinicalContext Clihlc =  instantiator.instantiateNewCliHlcDueToLlcEnd(llcEnd, listLlcConc);
			runReasonerNotifier(hlc);
			runReasonerNotifier(Nuthlc);  
			runReasonerNotifier(Clihlc);
		}
	}
	/**
	 * Test method that applies the same business logic than
	 * synchronizeLlcInWindow but prints messages through the standard output
	 * stream.
	 * 
	 * @param windowStart
	 *            Calendar representing the start time of the window.
	 * @param windowEnd
	 *            Calendar representing the end time of the window.
	 * @param r
	 *            PhysicalActivity and Nutrition Reasoner.
	 * @param n
	 *            PhysicalActivity and Nutrition Context Notifier.
	 */
	public void synchronizeTest(Calendar windowStart, Calendar windowEnd, HLCReasoner r, HLCNotifier n) {
		OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);
		Literal start = model.createTypedLiteral(windowStart);
		Literal end = model.createTypedLiteral(windowEnd);
		synchronizeTest(start, end, r, n);
	}
	/**
	 * Test method that applies the same business logic than
	 * synchronizeLlcInWindow but prints messages through the standard output
	 * stream.
	 * 
	 * @param windowStart
	 *            xsd:dateTime typed Literal representing the start time of the
	 *            window
	 * @param windowEnd
	 *            xsd:dateTime typed Literal representing the start time of the
	 *            window
	 * @param r
	 *            PhysicalActivity and Nutrition Context Reasoner.
	 * @param n
	 *            PhysicalActivity and Nutrition Context Notifier.
	 */
	private void synchronizeTest(Literal windowStart, Literal windowEnd, HLCReasoner r, HLCNotifier n) {
		List<LowLevelContext> llcStartList = null;
		List<LowLevelContext> llcEndList = null;
		try{
			if(contextHandler == null){
				logger.info("======================== NULL============");
			}
			llcStartList = contextHandler.retrieveLlcStartingWithinWindow(windowStart, windowEnd);
			llcEndList = contextHandler.retrieveLlcEndingWithinWindow(windowStart, windowEnd);
		}catch(Exception e){
			PrintWriter writer;
			try {
				writer = new PrintWriter("E:/ICL_LOG/errlog.txt", "UTF-8");
				writer.println(e.getMessage());
				writer.println(windowStart.toString() + " and " + windowEnd);
				e.printStackTrace(writer);
				writer.close();
				logger.error("Failed to synchornize HLC with following err.  Message: " + e.getMessage());
				e.printStackTrace();
				return;
			} catch (FileNotFoundException | UnsupportedEncodingException e1) {
					logger.error("Error while Synchronizing.  Message: " + e1.getMessage());
					e1.printStackTrace();
				}

		}
		Iterator<LowLevelContext> itStart = llcStartList.iterator();
		Iterator<LowLevelContext> itEnd = llcEndList.iterator();
		if (itStart.hasNext() && itEnd.hasNext()) {
			LowLevelContext llcStart = itStart.next();
			Date dateStart = ((XSDDateTime) llcStart.getDataPropertyValue(ont.getStartTimeProp()).getValue())
					.asCalendar().getTime();
			LowLevelContext llcEnd = itEnd.next();
			Date dateEnd = ((XSDDateTime) llcEnd.getDataPropertyValue(ont.getEndTimeProp()).getValue()).asCalendar()
					.getTime();
			boolean finished = false;
			while (!finished) {
				if (!dateStart.after(dateEnd)) {
					Literal endTimeLlcStart = llcStart.getDataPropertyValue(ont.getEndTimeProp());
					if (endTimeLlcStart == null
							|| !dateStart.equals(((XSDDateTime) endTimeLlcStart.getValue()).asCalendar().getTime())) {
						List<LowLevelContext> listLlcConc = contextHandler.retrieveConcurrentLlcAtStartTime(llcStart);
						Iterator<LowLevelContext> itConc = listLlcConc.iterator();
						String concurrent = "";
						while (itConc.hasNext()) {
							LowLevelContext llcConc = itConc.next();
							concurrent += llcConc.getCtxInstanceLocalName();
							concurrent += " ";
						}
/*						logger.info("------------------------------------------------------------");
						logger.info("[Context Synchronizer] Instantiate new HLC for "
								+ llcStart.getObjectPropertyValue(ont.getContextOfProp()).getLocalName()
						+ ". Trigger: start of " + llcStart.getCtxInstanceLocalName() + " at " + dateStart
								+ ". Concurrent LLC: " + concurrent);
						logger.info("");
						logger.info("[Context Synchronizer] Instantiate new HLC for "
								+ llcStart.getObjectPropertyValue(ont.getContextOfProp()).getLocalName()
								+ ". Trigger: start of " + llcStart.getCtxInstanceLocalName() + " at " + dateStart
								+ ". Concurrent LLC: " + concurrent);*/
						
						
						PhysicalActivityContext hlc = instantiator.instantiateNewHlcDueToLlcStart(llcStart, listLlcConc);
						NutritionContext Nuthlc = instantiator.instantiateNewNutHlcDueToLlcStart(llcStart, listLlcConc);
						ClinicalContext Clihlc = instantiator.instantiateNewCliHlcDueToLlcStart(llcStart, listLlcConc);  

						PhysicalActivityContext classifiedHlc = r.inferTest(hlc);
						NutritionContext  classifiedNutHlc = r.inferTest(Nuthlc);											 
						ClinicalContext  classifiedCliHlc = r.inferTest(Clihlc);
						n.notifyTest(classifiedHlc);
						n.notifyTest(classifiedNutHlc);
						n.notifyTest(classifiedCliHlc);
					} else {
/*						logger.info("");
						logger.info("[Context Synchronizer] Do not instantiate a new HLC for "
								+ llcStart.getObjectPropertyValue(ont.getContextOfProp()).getLocalName()
								+ " due to the start of " + llcStart.getCtxInstanceLocalName() + " at " + dateStart
								+ ". This LLC has equal start and end time.");
						logger.info("------------------------------------------------------------");
						logger.info("[Context Synchronizer] Do not instantiate a new HLC for "
								+ llcStart.getObjectPropertyValue(ont.getContextOfProp()).getLocalName()
								+ " due to the start of " + llcStart.getCtxInstanceLocalName() + " at " + dateStart
								+ ". This LLC has equal start and end time.");*/
					}
					if (itStart.hasNext()) {
						llcStart = itStart.next();
						dateStart = ((XSDDateTime) llcStart.getDataPropertyValue(ont.getStartTimeProp()).getValue())
								.asCalendar().getTime();
					} else {
						List<LowLevelContext> listLlcConc = contextHandler.retrieveConcurrentLlcAtEndTime(llcEnd);
						Iterator<LowLevelContext> itConc = listLlcConc.iterator();
						String concurrent = "";
						while (itConc.hasNext()) {
							LowLevelContext llcConc = itConc.next();
							concurrent += llcConc.getCtxInstanceLocalName();
							concurrent += " ";
						}
/*						logger.info("");
						logger.info("[Context Synchronizer] Instantiate new HLC for "
								+ llcEnd.getObjectPropertyValue(ont.getContextOfProp()).getLocalName()
								+ ". Trigger: end of " + llcEnd.getCtxInstanceLocalName() + " at " + dateEnd
								+ ". Concurrent LLC: " + concurrent);
						logger.info("------------------------------------------------------------");
						logger.info("[Context Synchronizer] Instantiate new HLC for "
								+ llcEnd.getObjectPropertyValue(ont.getContextOfProp()).getLocalName() +  " ("+ llcStart.getCtxTypeName() +") "  
								+ ". Trigger: end of " + llcEnd.getCtxInstanceLocalName() + " at " + dateEnd
								+ ". Concurrent LLC: " + concurrent);*/
						PhysicalActivityContext hlc = instantiator.instantiateNewHlcDueToLlcEnd(llcEnd, listLlcConc);
						NutritionContext Nuthlc = instantiator.instantiateNewNutHlcDueToLlcEnd(llcEnd, listLlcConc);     
						ClinicalContext Clihlc = instantiator.instantiateNewCliHlcDueToLlcEnd(llcEnd, listLlcConc);
						// Invoke HLC Reasoner and Notifier
						PhysicalActivityContext classifiedHlc = r.inferTest(hlc);
						NutritionContext classifiedNutHlc = r.inferTest(Nuthlc);      
						ClinicalContext classifiedCliHlc = r.inferTest(Clihlc);
						n.notifyTest(classifiedHlc);
						n.notifyTest(classifiedNutHlc);		
						n.notifyTest(classifiedCliHlc);
						finished = true;
					}
				}
				else {
					List<LowLevelContext> listLlcConc = contextHandler.retrieveConcurrentLlcAtEndTime(llcEnd);
					Iterator<LowLevelContext> itConc = listLlcConc.iterator();
					String concurrent = "";
					while (itConc.hasNext()) {
						LowLevelContext llcConc = itConc.next();
						concurrent += llcConc.getCtxInstanceLocalName();
						concurrent += " ";
					}
/*					logger.info("");
					logger.info("[Context Synchronizer] Instantiate new HLC for "
							+ llcEnd.getObjectPropertyValue(ont.getContextOfProp()).getLocalName()
							+ ". Trigger: end of " + llcEnd.getCtxInstanceLocalName() + " at " + dateEnd
							+ ". Concurrent LLC: " + concurrent);
					logger.info("------------------------------------------------------------");
					logger.info("[Context Synchronizer] Instantiate new HLC for "
							+ llcEnd.getObjectPropertyValue(ont.getContextOfProp()).getLocalName() +  " ("+ llcStart.getCtxTypeName() +") "   
							+ ". Trigger: end of " + llcEnd.getCtxInstanceLocalName() + " at " + dateEnd
							+ ". Concurrent LLC: " + concurrent);*/
					PhysicalActivityContext hlc = instantiator.instantiateNewHlcDueToLlcEnd   (llcEnd, listLlcConc);
					NutritionContext Nuthlc     = instantiator.instantiateNewNutHlcDueToLlcEnd(llcEnd, listLlcConc);     
					ClinicalContext Clihlc     = instantiator.instantiateNewCliHlcDueToLlcEnd(llcEnd, listLlcConc);
					// Invoke HLC Reasoner and Notifier
					PhysicalActivityContext classifiedHlc = r.inferTest(hlc);
					NutritionContext classifiedNutHlc = r.inferTest(Nuthlc);     
					ClinicalContext classifiedCliHlc = r.inferTest(Clihlc);
					n.notifyTest(classifiedHlc);
					n.notifyTest(classifiedNutHlc);			
					n.notifyTest(classifiedCliHlc);
					if (itEnd.hasNext()) {
						llcEnd = itEnd.next();
						dateEnd = ((XSDDateTime) llcEnd.getDataPropertyValue(ont.getEndTimeProp()).getValue())
								.asCalendar().getTime();
					} else {
						Literal endTimeLlcStart = llcStart.getDataPropertyValue(ont.getEndTimeProp());
						if (endTimeLlcStart == null || !dateStart
								.equals(((XSDDateTime) endTimeLlcStart.getValue()).asCalendar().getTime())) {
							listLlcConc = contextHandler.retrieveConcurrentLlcAtStartTime(llcStart);
							itConc = listLlcConc.iterator();
							concurrent = "";
							while (itConc.hasNext()) {
								LowLevelContext llcConc = itConc.next();
								concurrent += llcConc.getCtxInstanceLocalName();
								concurrent += " ";
							}
/*							logger.info("");
							logger.info("[Context Synchronizer] Instantiate new HLC for "
									+ llcStart.getObjectPropertyValue(ont.getContextOfProp()).getLocalName()
									+ ". Trigger: start of " + llcStart.getCtxInstanceLocalName() + " at " + dateStart
									+ ". Concurrent LLC: " + concurrent);
							logger.info("------------------------------------------------------------");
							logger.info("[Context Synchronizer] Instantiate new HLC for "
									+ llcStart.getObjectPropertyValue(ont.getContextOfProp()).getLocalName() +  " ("+ llcStart.getCtxTypeName() +") "  
									+ ". Trigger: start of " + llcStart.getCtxInstanceLocalName() + " at " + dateStart
									+ ". Concurrent LLC: " + concurrent);*/
							hlc = instantiator.instantiateNewHlcDueToLlcStart(llcStart, listLlcConc);
							Nuthlc = instantiator.instantiateNewNutHlcDueToLlcStart(llcStart, listLlcConc);      
							Clihlc = instantiator.instantiateNewCliHlcDueToLlcStart(llcStart, listLlcConc);
							classifiedHlc = r.inferTest(hlc);
							classifiedNutHlc = r.inferTest(Nuthlc);
							classifiedCliHlc = r.inferTest(Clihlc);
							n.notifyTest(classifiedHlc);
							n.notifyTest(classifiedNutHlc);	
							n.notifyTest(classifiedCliHlc);
						}
						else {
/*							logger.info("");
							logger.info("[Context Synchronizer] Do not instantiate a new HLC for "
									+ llcStart.getObjectPropertyValue(ont.getContextOfProp()).getLocalName()
									+ " due to the start of " + llcStart.getCtxInstanceLocalName() + " at " + dateStart
									+ ". This LLC has equal start and end time.");
							logger.info("------------------------------------------------------------");
							logger.info("[Context Synchronizer] Do not instantiate a new HLC for "
									+ llcStart.getObjectPropertyValue(ont.getContextOfProp()).getLocalName() +  " ("+ llcStart.getCtxTypeName() +") "  
									+ " due to the start of " + llcStart.getCtxInstanceLocalName() + " at " + dateStart
									+ ". This LLC has equal start and end time.");*/
						}
						finished = true;
					}
				}
			}
		}
		while (itStart.hasNext()) {
			LowLevelContext llcStart = itStart.next();
			Date dateStart = ((XSDDateTime) llcStart.getDataPropertyValue(ont.getStartTimeProp()).getValue())
					.asCalendar().getTime();
			Literal endTimeLlcStart = llcStart.getDataPropertyValue(ont.getEndTimeProp());
			if (endTimeLlcStart == null
					|| !dateStart.equals(((XSDDateTime) endTimeLlcStart.getValue()).asCalendar().getTime())) {
				List<LowLevelContext> listLlcConc = contextHandler.retrieveConcurrentLlcAtStartTime(llcStart);
				Iterator<LowLevelContext> itConc = listLlcConc.iterator();
				String concurrent = "";
				String   llc_Conc_Value = ""; 
    			String newLine = System.getProperty("line.separator");
				while (itConc.hasNext()) {
					LowLevelContext llcConc = itConc.next();
					concurrent += llcConc.getCtxInstanceLocalName();
					concurrent += " ";
				llc_Conc_Value += llcConc.getCtxTypeLocalName(); 
				llc_Conc_Value += " ";                         
				}
/*				logger.info("");
				logger.info("[Context Synchronizer] Instantiate new HLC for "
						+ llcStart.getObjectPropertyValue(ont.getContextOfProp()).getLocalName()
						+ ". Trigger: start of " + llcStart.getCtxInstanceLocalName() + " at " + dateStart
						+ ". Concurrent LLC: " + concurrent);
				logger.info("------------------------------------------------------------");
				logger.info("[Context Synchronizer ] Trigger: start of " + llcStart.getCtxInstanceLocalName()  
				+ " & Concurrent LLC: " + concurrent );   
				logger.info("[Context Synchronizer ] Trigger: start of " + llcStart.getCtxTypeLocalName()  
				+ " & Concurrent LLC: " + llc_Conc_Value + newLine); */  
				PhysicalActivityContext hlc = instantiator.instantiateNewHlcDueToLlcStart(llcStart, listLlcConc); 
				NutritionContext Nuthlc = instantiator.instantiateNewNutHlcDueToLlcStart(llcStart, listLlcConc);   
				ClinicalContext Clihlc = instantiator.instantiateNewCliHlcDueToLlcStart(llcStart, listLlcConc);
				// Invoke HLC Reasoner and Notifier
				PhysicalActivityContext classifiedHlc = r.inferTest(hlc);
				NutritionContext classifiedNutHlc = r.inferTest(Nuthlc);   
				ClinicalContext classifiedCliHlc = r.inferTest(Clihlc);
				n.notifyTest(classifiedHlc);								
				n.notifyTest(classifiedNutHlc);
				n.notifyTest(classifiedCliHlc);
			} else {
/*				logger.info("");
				logger.info("[Context Synchronizer] Do not instantiate a new HLC for "
						+ llcStart.getObjectPropertyValue(ont.getContextOfProp()).getLocalName()
						+ " due to the start of " + llcStart.getCtxInstanceLocalName() + " at " + dateStart
						+ ". This LLC has equal start and end time.");
				logger.info("------------------------------------------------------------");
				logger.info("[Context Synchronizer] Do not instantiate a new HLC for "
						+ llcStart.getObjectPropertyValue(ont.getContextOfProp()).getLocalName() +  " ("+ llcStart.getCtxTypeName() +") "    
						+ " due to the start of " + llcStart.getCtxInstanceLocalName() + " at " + dateStart 
						+ ". This LLC has equal start and end time.");*/
			}
		}
		while (itEnd.hasNext()) {
			LowLevelContext llcEnd = itEnd.next();
			List<LowLevelContext> listLlcConc = contextHandler.retrieveConcurrentLlcAtEndTime(llcEnd);
			Date dateEnd = ((XSDDateTime) llcEnd.getDataPropertyValue(ont.getEndTimeProp()).getValue()).asCalendar()
					.getTime();
			Iterator<LowLevelContext> itConc = listLlcConc.iterator();
			String concurrent = "";
			while (itConc.hasNext()) {
				LowLevelContext llcConc = itConc.next();
				concurrent += llcConc.getCtxInstanceLocalName();
				concurrent += " ";
			}
/*			logger.info("");
			logger.info("Instantiate new HLC for "
					+ llcEnd.getObjectPropertyValue(ont.getContextOfProp()).getLocalName() + ". Trigger: end of "
					+ llcEnd.getCtxInstanceLocalName() + " at " + dateEnd + ". Concurrent LLC: " + concurrent);
			logger.info("------------------------------------------------------------");
			logger.info("Instantiate new HLC for "
					+ llcEnd.getObjectPropertyValue(ont.getContextOfProp()).getLocalName() + ". Trigger: end of "
					+ llcEnd.getCtxInstanceLocalName() + " at " + dateEnd + ". Concurrent LLC: " + concurrent);*/
			PhysicalActivityContext hlc = instantiator.instantiateNewHlcDueToLlcEnd(llcEnd, listLlcConc);
			NutritionContext Nuthlc = instantiator.instantiateNewNutHlcDueToLlcEnd(llcEnd, listLlcConc);    
			ClinicalContext Clihlc = instantiator.instantiateNewCliHlcDueToLlcEnd(llcEnd, listLlcConc);
			
			PhysicalActivityContext classifiedHlc = r.inferTest(hlc);
			NutritionContext     classifiedNutHlc = r.inferTest(Nuthlc);    
			ClinicalContext     classifiedCliHlc = r.inferTest(Clihlc);
			n.notifyTest(classifiedHlc);
			n.notifyTest(classifiedNutHlc);
			n.notifyTest(classifiedCliHlc);
		}
	}
	
	public ContextHandler getContextHandler() {
		return contextHandler;
	}
	public void setContextHandler(ContextHandler contextHandler) {
		this.contextHandler = contextHandler;
	}
}


<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/monitoring/SCLSituationNotification.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */
package org.uclab.mm.dcl.llm.monitoring;

import org.uclab.mm.dcl.llm.objectmodel.SituationNotification;

/**
 * This is the concrete class for the implementation of situation notification.  
 * @author Rizvi
 */
public class SCLSituationNotification extends NotifyService{

  private SituationNotification objSituationNotification;
  private String serviceName;
/**
 * Constructor of the class SCLSitatuionNotification.
 * @param objSituationNotification
 * @param serviceName
 * @param objServiceNotification 
 */
  public SCLSituationNotification(SituationNotification objSituationNotification, String serviceName, ServiceNotificationChannel objServiceNotification){
    super(objServiceNotification);
    this.objSituationNotification = objSituationNotification;
    this.serviceName = serviceName;

  }
/**
 * The concrete implementation of sendNotification function of Abstract NotifyService class.
 */
  @Override
  public void sendNotification(){
    objServiceNotification.notifyToRestService(objSituationNotification, serviceName);
  }

}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/LLCManager/LLCNotifier.java<|end_filename|>
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.uclab.mm.icl.llc.LLCManager;

import java.util.ArrayList;
import org.uclab.mm.icl.llc.config.ContextType;
import org.uclab.mm.icl.llc.restservices.RestClients;
/*
Copyright [2016] [<NAME>, Kang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
 * Notifier class to DCL
 * @author Nailbrainz
 */
public class LLCNotifier {
	
	
	public static final String noActivity = "NoActivity";
	public static final String noEmotion = "NoEmotion";
	public static final String noLocation = "NoLocation";
	public static final String noFood = "NoFood";
	public static final String noHLC = "NoHLC";
	public static final String noCat = "NoFoodCate";
	
	ArrayList<String> prevContext = new ArrayList<String>();
	
	public LLCNotifier(){
		for(int i = 0; i<ContextType.values().length; i++){
			prevContext.add(" ");
		}
	}
	
	
	
	/**
	 * Notify activity context to DCL
	 * @param act activity to notify
	 */
	public void Notify(ContextLabel llc, ContextType ct){
		String prevLabel = prevContext.get(ct.getValue());
		System.err.println(prevLabel + " VS " + llc.getLabel());
		if(!prevLabel.equals(llc.getLabel())){
			try {
				//RestClients.sendDemo(""+act.getUserID(), act.getLabel(), noEmotion, noLocation, noFood, noHLC, noCat, act.getTimeStamp());
				RestClients.notifyChange(llc.getLabel(), llc.getUserID(), llc.getTimeStamp());
				prevContext.set(ct.getValue(), llc.getLabel());
				//ct.notifyLLCToDCL(llc);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/llm/dataadapter/DBConnection.java<|end_filename|>
/*
 Copyright [2016] [Taqdir Ali]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.llm.dataadapter;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *
 * @author Rizvi
 */
public class DBConnection {
    private static Connection conn = null;
    
    private DBConnection() {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            //Taqdir DB
           conn = DriverManager.getConnection("jdbc:sqlserver://192.168.3.11:1433;instance=SQLEXPRESS;databaseName=DBMiningMindsV1_5;user=sa;password=<PASSWORD>");
            // end of Taqdir DB
            
            //Local Bilal DB
           //conn = DriverManager.getConnection("jdbc:sqlserver://163.180.173.135:1433;databaseName=MMV2;user=sa;password=<PASSWORD>");
             //end of Local DB
              //Local Usman DB
          //conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=DBMiningMindsV1_5;user=usman;password=<PASSWORD>;");
              //end of Local DB
        }catch(SQLException | ClassNotFoundException exp)
        { 
            StringWriter errors = new StringWriter();
            exp.printStackTrace(new PrintWriter(errors));
            
        }
    }
    
    public Connection getConnection()
    {
        return conn;
    }
    
    public static DBConnection getDBConnection() {
        return DBConnectionHolder.INSTANCE;
    }
    
    private static class DBConnectionHolder {

        private static final DBConnection INSTANCE = new DBConnection();
    }
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sl/dataadapter/ExpertReviewAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sl.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.sl.ExpertReview;

/**
 * This is ExpertReviewAdapter class which implements the Data Access Interface for CRUD operations
 * @author <NAME>
 */
public class ExpertReviewAdapter implements DataAccessInterface {
    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(ExpertReviewAdapter.class);
    public ExpertReviewAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving ExpertReview. 
     * @param objExpertReview
     * @return List of String
     */
    @Override
    public List<String> Save(Object objExpertReview) {
        ExpertReview objInnerExpertReview = new ExpertReview();
        objInnerExpertReview =  (ExpertReview) objExpertReview;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_ExpertReview(?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserID", objInnerExpertReview.getUserID());
            objCallableStatement.setLong("UserExpertID", objInnerExpertReview.getUserExpertID());
            objCallableStatement.setString("ReviewDescription", objInnerExpertReview.getReviewDescription());
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
            Date dtDate = sdf.parse(objInnerExpertReview.getReviewDate());
            
            Timestamp tsDate = new Timestamp(dtDate.getYear(),dtDate.getMonth(), dtDate.getDate(), dtDate.getHours(), dtDate.getMinutes(), dtDate.getSeconds(), 00);
            objCallableStatement.setTimestamp("ReviewDate", tsDate);
            
            objCallableStatement.setInt("ReviewStatusID", objInnerExpertReview.getReviewStatusID());
            
            objCallableStatement.registerOutParameter("ExpertReviewID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intExpertReviewID = objCallableStatement.getLong("ExpertReviewID");
            objDbResponse.add(String.valueOf(intExpertReviewID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Expert Review saved successfully, Expert Review Details="+objExpertReview);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding Expert Review");
        	objDbResponse.add("Error in adding Expert Review");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for updating ExpertReview. 
     * @param objExpertReview
     * @return List of String
     */
    @Override
    public List<String> Update(Object objExpertReview) {
        ExpertReview objInnerExpertReview = new ExpertReview();
        objInnerExpertReview =  (ExpertReview) objExpertReview;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_ExpertReview(?, ?)}");
            
            objCallableStatement.setLong("ExpertReviewID", objInnerExpertReview.getExpertReviewID());
            objCallableStatement.setInt("ReviewStatusID", objInnerExpertReview.getReviewStatusID());
                        
            objCallableStatement.execute();
            
            Long intExpertReviewID = objInnerExpertReview.getExpertReviewID();
            objDbResponse.add(String.valueOf(intExpertReviewID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Expert Review updated successfully, Expert Review Details="+objExpertReview);
        }
        catch (Exception e)
        {
        	logger.info("Error in updating Expert Review");
        	objDbResponse.add("Error in updating Expert Review");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for retrieving ExpertReview. 
     * @param objExpertReview
     * @return List of ExpertReview
     */
    @Override
    public List<ExpertReview> RetriveData(Object objExpertReview) {
        ExpertReview objOuterExpertReview = new ExpertReview();
        List<ExpertReview> objListInnerExpertReview = new ArrayList<ExpertReview>();
        objOuterExpertReview =  (ExpertReview) objExpertReview;
        
        try
        {
            CallableStatement objCallableStatement = null;
            if( objOuterExpertReview.getRequestType() == "ByUserID")
             {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_ExpertReviewByUserID(?)}");
                objCallableStatement.setLong("UserID", objOuterExpertReview.getUserID());
             }
             else if(objOuterExpertReview.getRequestType() == "ByUserAndDate")
             {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_ExpertReviewByUserIDDate(?, ?, ?)}");

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
                Date dtStartDate = sdf.parse( objOuterExpertReview.getStartDate());
                Timestamp tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);

                Date dtEndDate =sdf.parse(objOuterExpertReview.getEndDate()); //.getTime();
                Timestamp tsEndDate = new Timestamp(dtEndDate.getYear(),dtEndDate.getMonth(), dtEndDate.getDate(), dtEndDate.getHours(), dtEndDate.getMinutes(),dtEndDate.getSeconds(),0);

                objCallableStatement.setLong("UserID", objOuterExpertReview.getUserID());
                objCallableStatement.setTimestamp("StartTime", tsStartDate);
                objCallableStatement.setTimestamp("EndTime", tsEndDate);
                
             }
            
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                ExpertReview objInnerExpertReview = new ExpertReview();
                
                objInnerExpertReview.setExpertReviewID(objResultSet.getLong("ExpertReviewID"));
                objInnerExpertReview.setUserID(objResultSet.getLong("UserID"));
                objInnerExpertReview.setUserExpertID(objResultSet.getLong("UserExpertID"));
                objInnerExpertReview.setReviewDescription(objResultSet.getString("ReviewDescription"));
                
                 if(objResultSet.getTimestamp("ReviewDate") != null)
                {
                    Timestamp tsReviewDate = objResultSet.getTimestamp("ReviewDate");
                    objInnerExpertReview.setReviewDate(tsReviewDate.toString());
                }
                objInnerExpertReview.setReviewStatusID(objResultSet.getInt("ReviewStatusID"));
                objListInnerExpertReview.add(objInnerExpertReview);
            }
            objConn.close();
            logger.info("Expert Review loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading Expert Review");
        }   
        return objListInnerExpertReview;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/ic/dataadapter/UserDeviceAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.ic.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.ic.Device;
import org.uclab.mm.datamodel.ic.UserDevice;

/**
 * This is UserDeviceAdapter class which implements the Data Access Interface for CRUD operations
 * @author Taqdir
 */
public class UserDeviceAdapter implements  DataAccessInterface {

    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(UserDeviceAdapter.class);
    public UserDeviceAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving UserDevice. 
     * @param objUserDevice
     * @return List of String
     */
    @Override
    public List<String> Save(Object objUserDevice) {
        UserDevice objInnerUserDevice = new UserDevice();
        objInnerUserDevice =  (UserDevice) objUserDevice;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_UserDevice(?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserID", objInnerUserDevice.getUserID());
            objCallableStatement.setLong("DeviceID", objInnerUserDevice.getDeviceID());
            objCallableStatement.setInt("SubscriptionStatusID", objInnerUserDevice.getSubscriptionStatusID());
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
            Date dtRegisterDate = sdf.parse(objInnerUserDevice.getRegisterDate());
            Timestamp tsRegisterDate = new Timestamp(dtRegisterDate.getYear(),dtRegisterDate.getMonth(), dtRegisterDate.getDate(), 00, 00, 00, 00);
            objCallableStatement.setTimestamp("RegisterDate", tsRegisterDate);
                       
            objCallableStatement.registerOutParameter("UserDeviceID", Types.BIGINT);
            objCallableStatement.execute();
            
            int intUserDeviceID = objCallableStatement.getInt("UserDeviceID");
            objDbResponse.add(String.valueOf(intUserDeviceID));
            objDbResponse.add("No Error");
            
            objConn.close();
            logger.info("Device loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in registering Device");
        	objDbResponse.add("Error in registering Device");
        }   
        
        return objDbResponse;
    }

    /**
     * This is implementation function for updating UserDevice. 
     * @param objUserDevice
     * @return List of UserDevice
     */
    @Override
    public List<String> Update(Object objUserDevice) {
        
        UserDevice objInnerUserDevice = new UserDevice();
        objInnerUserDevice =  (UserDevice) objUserDevice;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_UserDevice(?, ?, ?)}");
            
            objCallableStatement.setLong("UserID", objInnerUserDevice.getUserID());
            objCallableStatement.setLong("DeviceID", objInnerUserDevice.getDeviceID());
            objCallableStatement.setInt("SubscriptionStatusID", objInnerUserDevice.getSubscriptionStatusID());
                       
            objCallableStatement.execute();
            
            objDbResponse.add("No Error");
            
            objConn.close();
            logger.info("Sensor updated successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in subscribing sensor");
        	objDbResponse.add("Error in subscribing sensor");
        }   
        
        return objDbResponse;
        
    }

    /**
     * This is implementation function for retrieving UserDevice. 
     * @param objUserDevice
     * @return List of String
     */
    @Override
    public List<UserDevice> RetriveData(Object objUserDevice) {
        UserDevice objOuterUserDevice = new UserDevice();
        List<UserDevice> objListInnerUserDevice = new ArrayList<UserDevice>();
        objOuterUserDevice =  (UserDevice) objUserDevice;
        
        try
        {
            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UserDeviceByID(?)}");
            objCallableStatement.setLong("UserDeviceID", objOuterUserDevice.getUserDeviceID());
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                UserDevice objInnerUserDevice = new UserDevice();
                objInnerUserDevice.setUserDeviceID(objResultSet.getLong("UserDeviceID"));
                objInnerUserDevice.setUserID(objResultSet.getLong("UserID"));
                objInnerUserDevice.setDeviceID(objResultSet.getLong("DeviceID"));
                objInnerUserDevice.setSubscriptionStatusID(objResultSet.getInt("SubscriptionStatusID"));
                
                if(objResultSet.getTimestamp("RegisterDate") != null)
                {
                     Timestamp tsRegisterDate = objResultSet.getTimestamp("RegisterDate");
                     objInnerUserDevice.setRegisterDate(tsRegisterDate.toString());
                }
                objListInnerUserDevice.add(objInnerUserDevice);
            }
            objConn.close();
            logger.info("Device loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in Device loadeding");
        }   
        return objListInnerUserDevice;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }


    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/MachineLearningTools/Segmentation.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Bang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.MachineLearningTools;

/**
 * 
 * @author Nailbrainz
 * @param <InputType> Input data type for segmentation
 * @param <OutputType> segmented output data
 */
public abstract class Segmentation <InputType, OutputType> {
    
    /**
     * 
     * @param input input data to segment
     * @return segmented data
     */
    abstract public OutputType segmentation(InputType input);
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/MachineLearningTools/FilterBankPreprocessing.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Bang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.MachineLearningTools;

import java.io.IOException;
import java.util.Vector;

import javax.sound.sampled.AudioInputStream;

import org.uclab.mm.icl.llc.AER.jh.ConvertAudioData;
import org.uclab.mm.icl.llc.AER.jh.TransMFCC;
import org.uclab.mm.icl.llc.AER.jh.jAudioPreProcessing;

import mm.icl.llc.MachineLearningTools.Preprocessing;


/***
 * This class extract computable data with Filter-Bank Algorithms such as LPC, MFCC, Spectrums
 * @author <NAME>
 *
 */
public class FilterBankPreprocessing extends Preprocessing {
	TransMFCC tmfcc = new TransMFCC();
	jAudioPreProcessing jap = new jAudioPreProcessing();
	ConvertAudioData cad = new ConvertAudioData();
	/***
	 * Extract Power Spectrum by jAudio
	 * @param ais
	 * @return double[]
	 * @throws Exception
	 */
	
	public double[] getPowerSpectrum(AudioInputStream ais) throws Exception {
		double[] result = jap.getPowerSpectrum(ais);
		return result;
	}
	/***
	 * Extract LPC by jAudio
	 * @param ais
	 * @return double[]
	 * @throws Exception
	 */
	

	public double[] getLPC(AudioInputStream ais) throws Exception {
		double[] result = jap.getLPC(ais);
		return result;
	}
	/***
	 * Extract Magnitude Spectrum by jAudio
	 * @param ais
	 * @return double[]
	 * @throws Exception
	 */
	

	public double[] getMagnitudeSpectrum(AudioInputStream ais) throws Exception {
		double[] result = jap.getMagnitudeSpectrum(ais);
		return result;
	}
	/***
	 * Extract Real Value by jAudio
	 * @param ais
	 * @return double[]
	 * @throws Exception
	 */

	public double[] getRealValue(AudioInputStream ais) throws Exception {
		double[] result = jap.getRealValue(ais);
		return result;
	}
	/**
	 * Extract MFCC by Comirva
	 * @param ais
	 * @return double[][]
	 * @throws IOException
	 */
	public double[][] getMfcc(AudioInputStream ais) throws IOException{
		Vector<double[]> mfcc = tmfcc.getMFCC(ais, 1024, 14, true);
		double[][] result = tmfcc.getSingleFileFeatures(mfcc);
		return result;
	}
	/**
	 * No Define
	 */

	@Override
	public Object preprocessing(Object input) {
		// TODO Auto-generated method stub
		return null;
	}

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sl/dataadapter/FactsFeedbackAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sl.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.sl.FactsFeedback;

/**
 * This is FactsFeedbackAdapter class which implements the Data Access Interface for CRUD operations
 * @author <NAME>
 */
public class FactsFeedbackAdapter implements DataAccessInterface {

     private Connection objConn;
     private static final Logger logger = LoggerFactory.getLogger(FactsFeedbackAdapter.class);
    public FactsFeedbackAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving FactsFeedback. 
     * @param objFactsFeedback
     * @return List of String
     */
    @Override
    public List<String> Save(Object objFactsFeedback) {
        FactsFeedback objInnerFactsFeedback = new FactsFeedback();
        objInnerFactsFeedback =  (FactsFeedback) objFactsFeedback;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_FactsFeedback(?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("FactID", objInnerFactsFeedback.getFactID());
            objCallableStatement.setLong("UserID", objInnerFactsFeedback.getUserID());
            objCallableStatement.setInt("Rate", objInnerFactsFeedback.getRate());
            objCallableStatement.setString("Reason", objInnerFactsFeedback.getReason());
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
            Date dtDate = sdf.parse(objInnerFactsFeedback.getFeedbackDate());
            
            Timestamp tsDate = new Timestamp(dtDate.getYear(),dtDate.getMonth(), dtDate.getDate(), dtDate.getHours(), dtDate.getMinutes(), dtDate.getSeconds(), 00);
            objCallableStatement.setTimestamp("FeedbackDate", tsDate);
            
                        
            objCallableStatement.registerOutParameter("FactsFeedbackID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intFactsFeedbackID = objCallableStatement.getLong("FactsFeedbackID");
            objDbResponse.add(String.valueOf(intFactsFeedbackID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Facts Feedback saved successfully, Facts Feedback Details="+objFactsFeedback);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding Facts Feedback");
        	objDbResponse.add("Error in adding Facts Feedback");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for updating FactsFeedback. 
     * @param objFactsFeedback
     * @return List of String
     */
    @Override
    public List<String> Update(Object objFactsFeedback) {
        FactsFeedback objInnerFactsFeedback = new FactsFeedback();
        objInnerFactsFeedback =  (FactsFeedback) objFactsFeedback;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_FactsFeedback(?, ?, ?, ?, ?, ?)}");
            objCallableStatement.setLong("FactsFeedbackID", objInnerFactsFeedback.getFactsFeedbackID());
            objCallableStatement.setLong("FactID", objInnerFactsFeedback.getFactID());
            objCallableStatement.setLong("UserID", objInnerFactsFeedback.getUserID());
            objCallableStatement.setInt("Rate", objInnerFactsFeedback.getRate());
            objCallableStatement.setString("Reason", objInnerFactsFeedback.getReason());
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
            Date dtDate = sdf.parse(objInnerFactsFeedback.getFeedbackDate());
            
            Timestamp tsDate = new Timestamp(dtDate.getYear(),dtDate.getMonth(), dtDate.getDate(), dtDate.getHours(), dtDate.getMinutes(), dtDate.getSeconds(), 00);
            objCallableStatement.setTimestamp("FeedbackDate", tsDate);
                        
            objCallableStatement.execute();
            
            Long intFactsFeedbackID = objInnerFactsFeedback.getFactsFeedbackID();
            objDbResponse.add(String.valueOf(intFactsFeedbackID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Facts Feedback saved successfully, Facts Feedback Details="+objFactsFeedback);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding Facts Feedback");
        	objDbResponse.add("Error in adding Facts Feedback");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for retrieving FactsFeedback.
     * @param objFactsFeedback
     * @return List of FactsFeedback 
     */
    @Override
    public List<FactsFeedback> RetriveData(Object objFactsFeedback) {
        FactsFeedback objOuterFactsFeedback = new FactsFeedback();
        List<FactsFeedback> objListInnerFactsFeedback = new ArrayList<FactsFeedback>();
        objOuterFactsFeedback =  (FactsFeedback) objFactsFeedback;
        
        try
        {
            CallableStatement objCallableStatement = null;
            if(objOuterFactsFeedback.getRequestType() == "ByFactID")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_FactsFeedbackByFactID(?)}");
                objCallableStatement.setLong("FactID", objOuterFactsFeedback.getFactID());
            }
            else if(objOuterFactsFeedback.getRequestType() == "ByUserID")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_FactsFeedbackByUserID(?)}");
                objCallableStatement.setLong("UserID", objOuterFactsFeedback.getUserID());
            }
            
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                FactsFeedback objInnerFactsFeedback = new FactsFeedback();
                
                objInnerFactsFeedback.setFactsFeedbackID(objResultSet.getLong("FactsFeedbackID"));
                objInnerFactsFeedback.setFactID(objResultSet.getLong("FactID"));
                objInnerFactsFeedback.setUserID(objResultSet.getLong("UserID"));
                objInnerFactsFeedback.setRate(objResultSet.getInt("Rate"));
                objInnerFactsFeedback.setReason(objResultSet.getString("Reason"));
                
                 if(objResultSet.getTimestamp("FeedbackDate") != null)
                {
                    Timestamp tsFeedbackDate = objResultSet.getTimestamp("FeedbackDate");
                    objInnerFactsFeedback.setFeedbackDate(tsFeedbackDate.toString());
                }
                 
                objInnerFactsFeedback.setSituationCategoryID(objResultSet.getInt("SituationCategoryID"));
                objInnerFactsFeedback.setSituationCategoryDescription(objResultSet.getString("SituationCategoryDescription"));
                 
                objListInnerFactsFeedback.add(objInnerFactsFeedback);
            }
            objConn.close();
            logger.info("Facts Feedback loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading Facts Feedback");
        }   
        return objListInnerFactsFeedback;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet."); 
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/dataadapter/FactsAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.sc.Facts;
import org.uclab.mm.datamodel.sc.Situation;

/**
 * This is FactsAdapter class which implements the Data Access Interface for CRUD operations
 * @author <NAME>
 */
public class FactsAdapter implements DataAccessInterface {
    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(FactsAdapter.class);
    public FactsAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving Facts. 
     * @param objFacts
     * @return List of String
     */
    @Override
    public List<String> Save(Object objFacts) {
        Facts objInnerFacts = new Facts();
        objInnerFacts =  (Facts) objFacts;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_Facts(?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("SituationID", objInnerFacts.getSituationID());
            objCallableStatement.setString("FactDescription", objInnerFacts.getFactDescription());
            objCallableStatement.setString("SupportingLinks", objInnerFacts.getSupportingLinks());
            
            if(objInnerFacts.getFactDate() != null)
            {
               SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
               Date dtDate = sdf.parse(objInnerFacts.getFactDate());

               Timestamp tsDate = new Timestamp(dtDate.getYear(),dtDate.getMonth(), dtDate.getDate(), dtDate.getHours(), dtDate.getMinutes(), dtDate.getSeconds(), 00);
               objCallableStatement.setTimestamp("FactDate", tsDate);
            }
            objCallableStatement.setInt("FactStatusID", objInnerFacts.getFactStatusID());
            
            
            objCallableStatement.registerOutParameter("FactID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intFactID = objCallableStatement.getLong("FactID");
            objDbResponse.add(String.valueOf(intFactID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Facts saved successfully, Facts Feedback Details="+objFacts);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding Facts");
        	objDbResponse.add("Error in adding Facts");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for updating Facts. 
     * @param objFacts
     * @return List of String
     */
    @Override
    public List<String> Update(Object objFacts) {
        Facts objInnerFacts = new Facts();
        objInnerFacts =  (Facts) objFacts;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_Facts(?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("FactID", objInnerFacts.getFactID());
            objCallableStatement.setLong("SituationID", objInnerFacts.getSituationID());
            objCallableStatement.setString("FactDescription", objInnerFacts.getFactDescription());
            objCallableStatement.setString("SupportingLinks", objInnerFacts.getSupportingLinks());
            
            if(objInnerFacts.getFactDate() != null)
            {
               SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
               Date dtDate = sdf.parse(objInnerFacts.getFactDate());

               Timestamp tsDate = new Timestamp(dtDate.getYear(),dtDate.getMonth(), dtDate.getDate(), dtDate.getHours(), dtDate.getMinutes(), dtDate.getSeconds(), 00);
               objCallableStatement.setTimestamp("FactDate", tsDate);
            }
            objCallableStatement.setInt("FactStatusID", objInnerFacts.getFactStatusID());
            
            objCallableStatement.execute();
            
            Long intFactID = objInnerFacts.getFactID();
            objDbResponse.add(String.valueOf(intFactID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Facts updated successfully, Facts Details="+objFacts);
        }
        catch (Exception e)
        {
        	logger.info("Error in updating Facts");
        	objDbResponse.add("Error in updating Facts");
        } 
        return objDbResponse;
    }
    
    /**
     * This is implementation function for retrieving Facts. 
     * @param objFacts
     * @return List of Facts
     */
    @Override
    public List<Facts> RetriveData(Object objFacts) {
        Facts objOuterFacts = new Facts();
        List<Facts> objListInnerFacts = new ArrayList<Facts>();
        objOuterFacts =  (Facts) objFacts;
        
        try
        {
            CallableStatement objCallableStatement = null;
            if(objOuterFacts.getRequestType() == "ByUserOnly")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_FactsByUser(?)}");
                objCallableStatement.setLong("UserID", objOuterFacts.getUserID());
            }
            else if(objOuterFacts.getRequestType() == "ByUserandDate")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_FactsByUserIDDate(?, ?, ?)}");
                
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
               Date dtStartDate = sdf.parse(objOuterFacts.getStartDate());
               Timestamp tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);

               Date dtEndDate =sdf.parse( objOuterFacts.getEndDate()); //.getTime();
               Timestamp tsEndDate = new Timestamp(dtEndDate.getYear(),dtEndDate.getMonth(), dtEndDate.getDate(), dtEndDate.getHours(), dtEndDate.getMinutes(),dtEndDate.getSeconds(),0);
            
                objCallableStatement.setLong("UserID", objOuterFacts.getUserID());
                objCallableStatement.setTimestamp("StartTime", tsStartDate);
                objCallableStatement.setTimestamp("EndTime", tsEndDate);
            }
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                Facts objInnerFacts = new Facts();
                objInnerFacts.setFactID(objResultSet.getLong("FactID"));
                objInnerFacts.setSituationID(objResultSet.getLong("SituationID"));
                objInnerFacts.setFactDescription(objResultSet.getString("FactDescription"));
                objInnerFacts.setSupportingLinks(objResultSet.getString("SupportingLinks"));
                
                if(objResultSet.getTimestamp("FactDate") != null)
                {
                    Timestamp tsFactDate = objResultSet.getTimestamp("FactDate");
                    objInnerFacts.setFactDate(tsFactDate.toString());
                }
                   
               objInnerFacts.setFactStatusID(objResultSet.getInt("FactStatusID"));
               objInnerFacts.setFactStatusDescription(objResultSet.getString("RecommendationStatusDescription"));
               
               objListInnerFacts.add(objInnerFacts);
            }
            objConn.close();
            logger.info("Facts loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading Facts");
        }   
        return objListInnerFacts;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/interpreterdatamodel/LifeLogData.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.interpreterdatamodel;

/**
 * @version MM v2.5
 * @author Afzal
 *
 */
public class LifeLogData {

  private int activityId;

  private long duration;

  private String activityDescription;

  private long userId;

  private String activityDate;

  private String userRecognizedActivityAccumulateID;

  public int getActivityId() {
    return activityId;
  }

  public void setActivityId(int activityId) {
    this.activityId = activityId;
  }

  public long getDuration() {
    return duration;
  }

  public void setDuration(long duration) {
    this.duration = duration;
  }

  public String getActivityDescription() {
    return activityDescription;
  }

  public void setActivityDescription(String activityDescription) {
    this.activityDescription = activityDescription;
  }

  public long getUserId() {
    return userId;
  }

  public void setUserId(long userId) {
    this.userId = userId;
  }

  public String getActivityDate() {
    return activityDate;
  }

  public void setActivityDate(String activityDate) {
    this.activityDate = activityDate;
  }

  public String getUserRecognizedActivityAccumulateID() {
    return userRecognizedActivityAccumulateID;
  }

  public void setUserRecognizedActivityAccumulateID(
      String userRecognizedActivityAccumulateID) {
    this.userRecognizedActivityAccumulateID = userRecognizedActivityAccumulateID;
  }

  @Override
  public String toString() {
    return "ClassPojo [activityId = " + activityId + ", duration = " + duration
        + ", activityDescription = " + activityDescription + ", userId = "
        + userId + ", activityDate = " + activityDate
        + ", userRecognizedActivityAccumulateID = "
        + userRecognizedActivityAccumulateID + "]";
  }
}


<|start_filename|>data-curation-layer/active-data-reader/src/main/java/org/uclab/mm/dcl/adr/HomeController.java<|end_filename|>
/*
 * Copyright (C) 2016 <NAME>.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Home Controller are responsible for mapping
 *  the the HTTP request with the Methods. 
  */
package org.uclab.mm.dcl.adr;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.uclab.mm.dcl.adr.model.SLDataModel;

// TODO: Auto-generated Javadoc
/**
 * Handles requests mapping to data access object with the service.
 * 
 * Indicates that an annotated class is a "Controller" (e.g. a web controller).
 * 
 * @Controller annotation indicates that a particular class serves the role of a
 *             controller
 */
@Controller
public class HomeController {

	/**
	 * LoggerFactory: Return a logger named corresponding to the class passed as
	 * parameter, In case the class parameter differs from the name of the
	 * caller as computed internally by SLF4J, a logger name mismatch warning
	 * will be printed but only if the slf4j.detectLoggerNameMismatch system
	 * property is set to true.
	 */
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

	/**
	 * If the org.apache.hive.jdbc.HiveDriver does not recognize the check the
	 * pom.xml. We have added the Apache Hive version 1.2.1.
	 */
	private static String driverName = "org.apache.hive.jdbc.HiveDriver";

	/**
	 * Simply selects the home view to render by returning its name.
	 *
	 * @param locale
	 *            the locale
	 * @param model
	 *            the model
	 * @return the string
	 * 
	 * @RequestMapping: Annotation for mapping web requests onto specific
	 *                  handler classes and/or handler methods. Purpose: The
	 *                  main purpose of this method is to return the display on
	 *                  the home page and it serve as a static HomePage.
	 */

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);

		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

		String formattedDate = dateFormat.format(date);

		model.addAttribute("serverTime", formattedDate);

		return "home";
	}

	/**
	 * Location.
	 *
	 * @param userid the userid
	 * @return This method will return the location count that are stored in the
	 *         Apache Hive
	 * @throws SQLException the SQL exception
	 * @RequestMapping: Annotation for mapping web requests onto location method
	 *                  Usage: after starting the service goto the Rest Client
	 *                  and type www.localhost:8080/analytics/location?userid=0.
	 *                  This serves as a Get Request.
	 */
	@RequestMapping(value = "/location")
	public @ResponseBody SLDataModel location(@RequestParam(value = "userid") String userid) throws SQLException {

		try {
			Class.forName(driverName);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.exit(1);
		}

		/**
		 * The main connection String. We have added the JDBC connection setting
		 * inside spring.xml. Just replace the JDBC url with your own setting.
		 * You must enable the thrift Apache Hive post to interact with.
		 */
		Connection con = DriverManager.getConnection("jdbc:hive2://172.16.58.3:10000/test1", "hive", "hive");
		Statement stmt = con.createStatement();
		String tableName = "detectedlocation1";
		String sql = "show tables '" + tableName + "'";
		String data_name = "SCLData";
		String data_id = "1";
		System.out.println("Running: " + sql);
		ResultSet res = stmt.executeQuery(sql);
		ResultSetMetaData rsmd;

		if (res.next()) {
			System.out.println(res.getString(1));
		}

		ArrayList<Object> data_attributes = new ArrayList<Object>();
		ArrayList<Object> data_values = new ArrayList<Object>();
		LinkedHashMap<String, String> data_array = new LinkedHashMap<String, String>();

		/**
		 * This service will map the user id. Get the Id = 0 and calculate the
		 * number of label from the Big Data Storage.
		 */

		if (userid.equals("0")) {
			sql = "select * from detectedlocation1";
			res = stmt.executeQuery(sql);

			int home = 0;
			int office = 0;
			int yard = 0;
			int gym = 0;
			int mall = 0;
			int restaurant = 0;
			int outdoors = 0;
			int transport = 0;
			LinkedHashMap<String, String> attributes = new LinkedHashMap<String, String>();

			attributes.put("attribute_name", "Count of Location");
			data_attributes.add(attributes);
			while (res.next()) {
				if (res.getString(3).equals("Home")) {
					home++;
				} else if (res.getString(3).equals("Office")) {
					office++;
				} else if (res.getString(3).equals("Yard")) {
					yard++;
				} else if (res.getString(3).equals("Gym")) {
					gym++;
				} else if (res.getString(3).equals("Mall")) {
					mall++;
				} else if (res.getString(3).equals("Restaurant")) {
					restaurant++;
				} else if (res.getString(3).equals("Outdoors")) {
					outdoors++;
				} else if (res.getString(3).equals("Transport")) {
					transport++;
				}
			}

			String home_count = "Home:" + home;
			String office_count = "Office:" + office;
			String yard_count = "Yard:" + yard;
			String gym_count = "Gym:" + gym;
			String mall_count = "Mall:" + mall;
			String restaurant_count = "Restaurant:" + restaurant;
			String outdoors_count = "Outdoors:" + outdoors;
			String transport_count = "Transport:" + transport;

			data_values.add(home_count);
			data_values.add(office_count);
			data_values.add(yard_count);
			data_values.add(gym_count);
			data_values.add(mall_count);
			data_values.add(restaurant_count);
			data_values.add(outdoors_count);
			data_values.add(transport_count);

			data_array.put("Home", String.valueOf(home));
			data_array.put("Office", String.valueOf(office));
			data_array.put("Yard", String.valueOf(yard));
			data_array.put("Mall", String.valueOf(mall));
			data_array.put("Restaurant", String.valueOf(restaurant));
			data_array.put("Outdoors", String.valueOf(outdoors));
			data_array.put("Transport", String.valueOf(transport));

		}
		/**
		 * Other then the userid=0 this will search the label inside the Apache
		 * Hive and send the results.
		 */

		else {
			sql = "select * from detectedlocation where userid=" + userid;
			ResultSet resultSet = res = stmt.executeQuery(sql);
			System.out.println("Running: " + sql);

			rsmd = res.getMetaData();
			int colcount = rsmd.getColumnCount();

			for (int j = 1; j <= colcount; j++) {

				{
					LinkedHashMap<String, String> attributes = new LinkedHashMap<String, String>();
					String attribute_name = rsmd.getColumnLabel(j).split("\\.")[1];
					attributes.put("attribute_name", attribute_name);
					String attribute_type = rsmd.getColumnTypeName(j);
					attributes.put("Attribute_type", attribute_type);
					data_attributes.add(attributes);

				}
			}
			while (res.next()) {

				{
					ArrayList<Object> values = new ArrayList<Object>();

					for (int j = 1; j <= colcount; j++) {

						values.add(res.getString(j));

					}
					data_values.add(values);
				}
			}

		}
		/**
		 * Display the userid in the terminal.
		 */
		String line = "incoming userid = " + userid;

		System.out.println(line);

		/**
		 * Finally the result is send back to the model.
		 */
		return new SLDataModel(data_id, data_name, data_attributes, data_array);
	}

}


<|start_filename|>data-curation-layer/data-persistence/DPServer.js.html<|end_filename|>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JSDoc: Source: DPServer.js</title>

    <script src="scripts/prettify/prettify.js"> </script>
    <script src="scripts/prettify/lang-css.js"> </script>
    <!--[if lt IE 9]>
      <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>

<body>

<div id="main">

    <h1 class="page-title">Source: DPServer.js</h1>

    



    
    <section>
        <article>
            <pre class="prettyprint source linenums"><code>

/**
 * @author <NAME>
 * @since 2016.11.21
 * @version 0.1
 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at

 *   http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


//DPServer.js - nodejs server for Datapersistence

/**
 * @example
 * Usage:
 * 	node DPServer.js
 */

/**
 * @description Run all of the modules.
 * @description If local file size is going to enough to store, then start sendHDFS module.
 */

//modules in node_modules.
var express		=require('express');
var bodyParser  =require('body-parser');
var requestify  =require('requestify');
var util = require('util');
var nodeProcess = require('process');
var fs = require('fs');

//modules in local.
var manu = require('./DataManufacture');
var fileio = require('./LocalFileManagement');
var store = require('./sendHDFS');
var config = require('./config.json');

//public value
var cnt;
var port = config.port;
/*Server initialization***********************************************************************************************/
var app	=express();
app.use(bodyParser.json());
var urlencodedParser = bodyParser.urlencoded({ extended: true })
/*Server initialization***********************************************************************************************/     

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
//Post request.
app.post('/saveData', urlencodedParser,  function (req,res)
{
	var result = manu.dmf(req); //data sorting
    	cnt = fileio.lfm(result[0], result[1], result[2]);
	if(cnt != -1)
	{
		console.log("cnt is not -1");
		store.wc(cnt);
	}
	res.json({response:0});
});

//Use the PORT environment variable
app.listen('8083', function (){
	console.log('Server is running');
});
</code></pre>
        </article>
    </section>




</div>

<nav>
    <h2><a href="index.html">Home</a></h2><h3>Global</h3><ul><li><a href="global.html#express">express</a></li></ul>
</nav>

<br class="clear">

<footer>
    Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.4.3</a> on Sat Dec 24 2016 10:14:52 GMT+0900 (KST)
</footer>

<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/datamodel/Situations.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.datamodel;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

public class Situations implements Serializable {

  /**
	 * 
	 */
  private static final long serialVersionUID = 7222498736081149676L;
  private String situationID;
  private String situationDescription;
  private Set<SituationConditions> listSConditions = new HashSet<SituationConditions>();

  public Situations() {

  }

  public Situations(String situationID) {
    this.situationID = situationID;
  }

  public String getSituationID() {
    return situationID;
  }

  public void setSituationID(String situationID) {
    this.situationID = situationID;
  }

  public String getSituationDescription() {
    return situationDescription;
  }

  public void setSituationDescription(String situationDescription) {
    this.situationDescription = situationDescription;
  }

  public Set<SituationConditions> getListSConditions() {
    return listSConditions;
  }

  public void setListSConditions(Set<SituationConditions> listSConditions) {
    this.listSConditions = listSConditions;
  }

  public void addSituationCondition(SituationConditions situationCondition) {
    this.listSConditions.add(situationCondition);
  }

}


<|start_filename|>data-curation-layer/data-persistence/DataManufacture.js.html<|end_filename|>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JSDoc: Source: DataManufacture.js</title>

    <script src="scripts/prettify/prettify.js"> </script>
    <script src="scripts/prettify/lang-css.js"> </script>
    <!--[if lt IE 9]>
      <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>

<body>

<div id="main">

    <h1 class="page-title">Source: DataManufacture.js</h1>

    



    
    <section>
        <article>
            <pre class="prettyprint source linenums"><code>/**
 * @author <NAME>
 * @since 2016.11.21
 * @version 0.1
 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at

 *   http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var bodyParser  =require('body-parser');

/**
 * @description Sorting a data object
 * @description Extract data in object using by index 
 * @module dmf(DataManufacture) 
 * @param {JSON} req - The JSON format data recieved by Syncronization module
 * @return {object} result - This module returns object which has 3 factor{
 * obj[index[0]] => contentBody
 * obj[index[1]] => timestamp
 * obj[index[2]] => userID
 * }
 */
exports.dmf = function(req){ 


var index = []; //Array for index
var obj = new Object(); //Create a object
obj = req.body;
for(var x in obj)
{
	index.push(x);
}

index.sort(function (a, b) {    
   return a == b ? 0 : (a > b ? 1 : -1); 
}); 


var result = [];
result[0] = obj[index[2]];
result[1] = obj[index[1]];
result[2] = obj[index[0]]

return result;
};

</code></pre>
        </article>
    </section>




</div>

<nav>
    <h2><a href="index.html">Home</a></h2><h3>Modules</h3><ul><li><a href="dmf.html">dmf</a></li></ul><h3>Global</h3><ul><li><a href="global.html#bodyParser">bodyParser</a></li></ul>
</nav>

<br class="clear">

<footer>
    Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.4.3</a> on Sat Dec 24 2016 10:13:28 GMT+0900 (KST)
</footer>

<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>


<|start_filename|>supporting-layer/uiux-authoring-tool/JavaDoc/org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html<|end_filename|>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_76-release) on Fri Dec 23 12:27:01 KST 2016 -->
<title>UIUXAnalytics</title>
<meta name="date" content="2016-12-23">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
    try {
        if (location.href.indexOf('is-external=true') == -1) {
            parent.document.title="UIUXAnalytics";
        }
    }
    catch(err) {
    }
//-->
var methods = {"i0":10,"i1":9,"i2":10,"i3":10,"i4":10,"i5":10,"i6":42,"i7":10,"i8":10};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"],32:["t6","Deprecated Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!--   -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!--   -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/UIUXAnalytics.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackMe.html" title="class in org.uclab.mm.sl.uiux.analytics"><span class="typeNameLink">Prev&nbsp;Class</span></a></li>
<li><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXApplication.html" title="class in org.uclab.mm.sl.uiux.analytics"><span class="typeNameLink">Next&nbsp;Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html" target="_top">Frames</a></li>
<li><a href="UIUXAnalytics.html" target="_top">No&nbsp;Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
  allClassesLink = document.getElementById("allclasses_navbar_top");
  if(window==top) {
    allClassesLink.style.display = "block";
  }
  else {
    allClassesLink.style.display = "none";
  }
  //-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary:&nbsp;</li>
<li>Nested&nbsp;|&nbsp;</li>
<li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li>
<li>Constr&nbsp;|&nbsp;</li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail:&nbsp;</li>
<li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li>
<li>Constr&nbsp;|&nbsp;</li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!--   -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.uclab.mm.sl.uiux.analytics</div>
<h2 title="Class UIUXAnalytics" class="title">Class UIUXAnalytics</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.uclab.mm.sl.uiux.analytics.UIUXAnalytics</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="typeNameLabel">UIUXAnalytics</span>
extends java.lang.Object</pre>
<div class="block">The type Uiux analytics.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.summary">
<!--   -->
</a>
<h3>Field Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html#LOGGER_PREFIX">LOGGER_PREFIX</a></span></code>
<div class="block">The constant LOGGER_PREFIX.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html#PREFERENCE_FILE_NAME">PREFERENCE_FILE_NAME</a></span></code>
<div class="block">The constant PREFERENCE_FILE_NAME.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html#PREFERENCE_KEY_OPTOUT">PREFERENCE_KEY_OPTOUT</a></span></code>
<div class="block">The constant PREFERENCE_KEY_OPTOUT.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!--   -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t6" class="tableTab"><span><a href="javascript:show(32);">Deprecated Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html#getApplicationDomain--">getApplicationDomain</a></span>()</code>
<div class="block">Gets application domain.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html" title="class in org.uclab.mm.sl.uiux.analytics">UIUXAnalytics</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html#getInstance-android.content.Context-">getInstance</a></span>(android.content.Context&nbsp;context)</code>
<div class="block">Gets instance.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>android.content.SharedPreferences</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html#getSharedPreferences--">getSharedPreferences</a></span>()</code>
<div class="block">Returns the shared preferences used by UIUXAnalytics that are stored under <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html#PREFERENCE_FILE_NAME"><code>PREFERENCE_FILE_NAME</code></a></div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html#isDryRun--">isDryRun</a></span>()</code>
<div class="block">Is dry run boolean.</div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html#isOptOut--">isOptOut</a></span>()</code>
<div class="block">Is opt out boolean.</div>
</td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/Tracker.html" title="class in org.uclab.mm.sl.uiux.analytics">Tracker</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html#newTracker-java.lang.String-int-">newTracker</a></span>(java.lang.String&nbsp;trackerUrl,
          int&nbsp;siteId)</code>
<div class="block">New tracker tracker.</div>
</td>
</tr>
<tr id="i6" class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/Tracker.html" title="class in org.uclab.mm.sl.uiux.analytics">Tracker</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html#newTracker-java.lang.String-int-java.lang.String-">newTracker</a></span>(java.lang.String&nbsp;trackerUrl,
          int&nbsp;siteId,
          java.lang.String&nbsp;authToken)</code>
<div class="block"><span class="deprecatedLabel">Deprecated.</span>&nbsp;
<div class="block"><span class="deprecationComment">Use <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html#newTracker-java.lang.String-int-"><code>newTracker(String, int)</code></a> as there are security concerns over the authToken.</span></div>
</div>
</td>
</tr>
<tr id="i7" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html#setDryRun-boolean-">setDryRun</a></span>(boolean&nbsp;dryRun)</code>
<div class="block">The dryRun flag set to true prevents any data from being sent to UIUXAnalytics.</div>
</td>
</tr>
<tr id="i8" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html#setOptOut-boolean-">setOptOut</a></span>(boolean&nbsp;optOut)</code>
<div class="block">Use this to disable UIUXAnalytics, e.g.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!--   -->
</a>
<h3>Methods inherited from class&nbsp;java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.detail">
<!--   -->
</a>
<h3>Field Detail</h3>
<a name="LOGGER_PREFIX">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>LOGGER_PREFIX</h4>
<pre>public static final&nbsp;java.lang.String LOGGER_PREFIX</pre>
<div class="block">The constant LOGGER_PREFIX.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../../../../constant-values.html#org.uclab.mm.sl.uiux.analytics.UIUXAnalytics.LOGGER_PREFIX">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="PREFERENCE_FILE_NAME">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>PREFERENCE_FILE_NAME</h4>
<pre>public static final&nbsp;java.lang.String PREFERENCE_FILE_NAME</pre>
<div class="block">The constant PREFERENCE_FILE_NAME.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../../../../constant-values.html#org.uclab.mm.sl.uiux.analytics.UIUXAnalytics.PREFERENCE_FILE_NAME">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="PREFERENCE_KEY_OPTOUT">
<!--   -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>PREFERENCE_KEY_OPTOUT</h4>
<pre>public static final&nbsp;java.lang.String PREFERENCE_KEY_OPTOUT</pre>
<div class="block">The constant PREFERENCE_KEY_OPTOUT.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../../../../constant-values.html#org.uclab.mm.sl.uiux.analytics.UIUXAnalytics.PREFERENCE_KEY_OPTOUT">Constant Field Values</a></dd>
</dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!--   -->
</a>
<h3>Method Detail</h3>
<a name="getInstance-android.content.Context-">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getInstance</h4>
<pre>public static&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html" title="class in org.uclab.mm.sl.uiux.analytics">UIUXAnalytics</a>&nbsp;getInstance(android.content.Context&nbsp;context)</pre>
<div class="block">Gets instance.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>context</code> - the context</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the instance</dd>
</dl>
</li>
</ul>
<a name="newTracker-java.lang.String-int-java.lang.String-">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>newTracker</h4>
<pre>@Deprecated
public&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/Tracker.html" title="class in org.uclab.mm.sl.uiux.analytics">Tracker</a>&nbsp;newTracker(@NonNull
                                       java.lang.String&nbsp;trackerUrl,
                                       int&nbsp;siteId,
                                       java.lang.String&nbsp;authToken)
                                throws java.net.MalformedURLException</pre>
<div class="block"><span class="deprecatedLabel">Deprecated.</span>&nbsp;<span class="deprecationComment">Use <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html#newTracker-java.lang.String-int-"><code>newTracker(String, int)</code></a> as there are security concerns over the authToken.</span></div>
<div class="block">New tracker tracker.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>trackerUrl</code> - (required) Tracking HTTP API endpoint, for example, http://your-piwik-domain.tld/piwik.php</dd>
<dd><code>siteId</code> - (required) id of site</dd>
<dd><code>authToken</code> - (optional) could be null or valid auth token.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>Tracker object</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.net.MalformedURLException</code> - the malformed url exception</dd>
</dl>
</li>
</ul>
<a name="newTracker-java.lang.String-int-">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>newTracker</h4>
<pre>public&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/Tracker.html" title="class in org.uclab.mm.sl.uiux.analytics">Tracker</a>&nbsp;newTracker(@NonNull
                          java.lang.String&nbsp;trackerUrl,
                          int&nbsp;siteId)
                   throws java.net.MalformedURLException</pre>
<div class="block">New tracker tracker.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>trackerUrl</code> - (required) Tracking HTTP API endpoint</dd>
<dd><code>siteId</code> - (required) id of site</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>Tracker object</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.net.MalformedURLException</code> - the malformed url exception</dd>
</dl>
</li>
</ul>
<a name="setOptOut-boolean-">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setOptOut</h4>
<pre>public&nbsp;void&nbsp;setOptOut(boolean&nbsp;optOut)</pre>
<div class="block">Use this to disable UIUXAnalytics, e.g. if the user opted out of tracking.
 UIUXAnalytics will persist the choice and remain disable on next instance creation.</p>
 The choice is stored in <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html#PREFERENCE_FILE_NAME"><code>PREFERENCE_FILE_NAME</code></a> under the key <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html#PREFERENCE_KEY_OPTOUT"><code>PREFERENCE_KEY_OPTOUT</code></a>.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>optOut</code> - true to disable reporting</dd>
</dl>
</li>
</ul>
<a name="isOptOut--">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isOptOut</h4>
<pre>public&nbsp;boolean&nbsp;isOptOut()</pre>
<div class="block">Is opt out boolean.</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>true if UIUXAnalytics is currently disabled</dd>
</dl>
</li>
</ul>
<a name="isDryRun--">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isDryRun</h4>
<pre>public&nbsp;boolean&nbsp;isDryRun()</pre>
<div class="block">Is dry run boolean.</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the boolean</dd>
</dl>
</li>
</ul>
<a name="setDryRun-boolean-">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setDryRun</h4>
<pre>public&nbsp;void&nbsp;setDryRun(boolean&nbsp;dryRun)</pre>
<div class="block">The dryRun flag set to true prevents any data from being sent to UIUXAnalytics.
 The dryRun flag should be set whenever you are testing or debugging an implementation and do not want
 test data to appear in your UIUXAnalytics reports. To set the dry run flag, use:</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>dryRun</code> - true if you don't want to send any data to uxe</dd>
</dl>
</li>
</ul>
<a name="getApplicationDomain--">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getApplicationDomain</h4>
<pre>public&nbsp;java.lang.String&nbsp;getApplicationDomain()</pre>
<div class="block">Gets application domain.</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the application domain</dd>
</dl>
</li>
</ul>
<a name="getSharedPreferences--">
<!--   -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getSharedPreferences</h4>
<pre>public&nbsp;android.content.SharedPreferences&nbsp;getSharedPreferences()</pre>
<div class="block">Returns the shared preferences used by UIUXAnalytics that are stored under <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html#PREFERENCE_FILE_NAME"><code>PREFERENCE_FILE_NAME</code></a></div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>UIUXAnalytics 's SharedPreferences instance</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!--   -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!--   -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/UIUXAnalytics.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackMe.html" title="class in org.uclab.mm.sl.uiux.analytics"><span class="typeNameLink">Prev&nbsp;Class</span></a></li>
<li><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/UIUXApplication.html" title="class in org.uclab.mm.sl.uiux.analytics"><span class="typeNameLink">Next&nbsp;Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html" target="_top">Frames</a></li>
<li><a href="UIUXAnalytics.html" target="_top">No&nbsp;Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
  allClassesLink = document.getElementById("allclasses_navbar_bottom");
  if(window==top) {
    allClassesLink.style.display = "block";
  }
  else {
    allClassesLink.style.display = "none";
  }
  //-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary:&nbsp;</li>
<li>Nested&nbsp;|&nbsp;</li>
<li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li>
<li>Constr&nbsp;|&nbsp;</li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail:&nbsp;</li>
<li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li>
<li>Constr&nbsp;|&nbsp;</li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!--   -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/framework/RecInterpreter/PARecommender/SingleRecEvaluator.java<|end_filename|>
/* Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.scl.framework.RecInterpreter.PARecommender;

import java.io.FileNotFoundException;
import java.util.HashMap;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.uclab.scl.datamodel.contextMapper.RecommendationMapper;
import org.uclab.scl.framework.RecInterpreter.AbstractRecEvaluator;

public class SingleRecEvaluator extends AbstractRecEvaluator {
  private static Logger LOG = LogManager.getRootLogger();
  
	static HashMap<String, String> mapWeatherRec = new HashMap<>();
	static HashMap<String, String> mapDisableRec = new HashMap<>();
	static HashMap<String, String> mapRec = new HashMap<>();

	@SuppressWarnings("unchecked")
	public static int[] evalRecommendations(String rec, String userid, String context) throws Exception {
		return null;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	
	public int[] evaluate(String rec, String userid, String context) {
		RecommendationMapper recommendationMapper = new RecommendationMapper();
		// String context_string = "Office,OfficeWork,Rainy,Neutral,No";
		LOG.debug("Context String: " + context);
		try {
			mapRec = recommendationMapper.recMapper();
		} catch (FileNotFoundException e) {
		//	LOG.debug(e.printStackTrace);
		}
		int[] matResultVector = null;
		try {
			matResultVector = ContextEvaluator.generateContextMatrix(context);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// Reading data from HashMap
		String temp = mapRec.containsKey(rec) ? mapRec.get(rec)	: mapRec.get(null);
		int index = 0;
		if (temp != null)
			index = Integer.parseInt(temp);
		else {
		  LOG.debug("Recommendation NOT FOUND in the repository");
		  LOG.debug("Default case applied");
			index = Integer.parseInt(mapRec.get("D"));
		}
		// Data Retrieval complete
		int sumArrVec = 0;
		int sumPrefVec = 0;
		for (int i = 0; i < matResultVector.length; i++) {
			sumArrVec += matResultVector[i];
		}

		int[] tempFinalRec = new int[matResultVector.length];
		java.util.Arrays.fill(tempFinalRec, 0);
		if (matResultVector[index] == 0) {
			LOG.debug("Alternative Rec needed for " + rec);
			if (sumArrVec > 1) { // PREFERENCE CHKING
				//LOG.debug("okay now we have multiple alternative rec; now Preference check needed");
				int[] ARPref = null;
				try {
					ARPref = PreferenceTesting.mainPrefTest(matResultVector, userid, context);
				} catch (Exception e) {
					e.printStackTrace();
				}
				System.out.print("ARP_List ");
				for (int i = 0; i < ARPref.length; i++) {
					LOG.debug(ARPref[i] + " ");
					sumPrefVec += ARPref[i];
				}

				if (sumPrefVec == 0) {
				//	LOG.debug("Well ARP is 0 because Preference chk made it so, GO BACK TO AR !!!");
					System.arraycopy(matResultVector, 0, tempFinalRec, 0, matResultVector.length); // forward aggregate vector
				} else if ((sumPrefVec > 1)) {
				//	LOG.debug("now we got multiple preference based recommendations, forwarding");
					System.arraycopy(ARPref, 0, tempFinalRec, 0, ARPref.length);
					//for enforcing some other constraints
				} else {
				//	LOG.debug("after Preference chk left with only 1 recommendation, forwarding");
					System.arraycopy(ARPref, 0, tempFinalRec, 0, ARPref.length);
				}
			} else
				LOG.debug("we have only one alternative rec, so forward that to Explanation Generator");
		}
		// Alternative Rec code here
		else {
			LOG.debug("Recommendation is Fine as per the current context; Forward to Explanation Generator");
			// Forward code to explanation generator
			java.util.Arrays.fill(tempFinalRec, 0);
			tempFinalRec[index] = 1;
			//System.arraycopy(matResultVector, 0, tempFinalRec, 0,	matResultVector.length);
		}
		// Finalize Rec Processing
		int[] finalRec = new int[mapRec.size() - 1];
		boolean flag = true;
		for (int i = 0; i < tempFinalRec.length; i++) {
			if ((tempFinalRec[i] == 1) && (flag == true)) {
				finalRec[i] = 1;
				flag = false;
			} else
				finalRec[i] = 0;
		}
		return finalRec;
	}
}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/framework/Reasoner.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.framework;

import org.uclab.scl.framework.recbuilder.ConflictResolver;
import org.uclab.scl.framework.recbuilder.PatternMatcher;
import org.uclab.scl.framework.recbuilder.RecBuilder;

public class Reasoner {

  private AbstractRecBuilder abstractRecBuilder = null;

  private Reasoner() {
  }
  
  public static Reasoner getRuleBaseReasoner() {
    return ReasonerHolder.INSTANCE;
  }

  private static class ReasonerHolder {
    private static final Reasoner INSTANCE = new Reasoner();
  }
  
  /**
   * 
   * @param reasonerEnum
   * @return recommendationBuilder
   */
  public ISCLFramework getMatchedRules(ReasonerEnum reasonerEnum) {
    switch (reasonerEnum) {
    case SITUATION_PAREASONER:
      abstractRecBuilder = new RecBuilder(new PatternMatcher(), new ConflictResolver());
      break;
    }
    return abstractRecBuilder;
  }
}


<|start_filename|>knowledge-curation-layer/DDKAT/target/DDKAT/WEB-INF/views/preprocessor.jsp<|end_filename|>
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  
<HTML><HEAD><TITLE>Data Driven Knowledge Acquisition</TITLE>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="https://code.jquery.com/jquery-1.12.0.js"></script>
<link href="css/ddka-interface.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/bootstrap.min.js" ></script>
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"> 

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.11/css/jquery.dataTables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script>

<script language="javascript">

$(document).ready(function(){
	
	document.getElementById("dataconverter_btn").disabled = true;
	document.getElementById("missingvaluehandler_btn").disabled = true;
	document.getElementById("outlierhandler_btn").disabled = true;
	document.getElementById("discretizer_btn").disabled = true;
	document.getElementById("featureselector_btn").disabled = true;
	document.getElementById("modellearner_btn").disabled = true;
	
	var jsonString ="";
		
	$("#loaddata_btn").click(function () {
				
		var query = $("#loadingdataQueryId").val();
		
		$.ajaxSetup({
			contentType: "application/json; charset=utf-8"
			});
		
		// Send the data using post
		$.ajax({ 
			url: "http://private-673d5-data11.apiary-mock.com/data?kcldataquery="+query,
		    type: 'POST',
		    success: function(data) {

		    	var emptyTemp;
		    	
		    	jsonString = "{\"unprocessed_data\": [";
	    	
		    	console.log(data);
		    
		    	var tabletitleHTML='<b>Data Title : <font size="4" color="#004584">'+data.data_name+ '</font></b><br/><br/>';
			   	var tempVar="";
			  	var hrow = document.getElementById("myHeaderRow");
		    	   			   	
				var columncounter = 0;
		    	jsonString += "[";
			   	while(columncounter < data.data_attributes.length){
			   		var headerCell = document.createElement("TH");
			   		headerCell.innerHTML = data.data_attributes[columncounter].attribute_name.toUpperCase();
			   		hrow.appendChild(headerCell);
			   		jsonString += "\""+data.data_attributes[columncounter].attribute_name +"\""+",";
			   		columncounter++;
			   		}
			   	jsonString = jsonString.substring(0, jsonString.length-1);
			   	jsonString += "],";		    	
		    	
		    	var dataSet = "[";
		     	var rowcounter = 0;
			   	while(rowcounter < data.data_values.length){
			   		jsonString += "[";
			   		dataSet += "[";
			   		columncounter = 0;
			   		while(columncounter < data.data_attributes.length){
   						tempVar = data.data_values[rowcounter][columncounter];
			   			if (tempVar==0){   
			   			    tempVar = "";
			   			 	jsonString += "\""+ data.data_values[rowcounter][columncounter] + "\",";
			   			 	dataSet += "\""+ data.data_values[rowcounter][columncounter] + "\",";
			   				}
			   			else{
			   				jsonString += "\""+ tempVar +"\",";
			   				dataSet += "\""+ tempVar +"\",";
			   				}
			   			columncounter++;
				   		}
			   		jsonString = jsonString.substring(0, jsonString.length-1);
			   		dataSet = dataSet.substring(0, dataSet.length-1);
				   	jsonString += "],";
				   	dataSet += "],";
			   		rowcounter++;
			   		}
			   	jsonString = jsonString.substring(0, jsonString.length-1);
			   	dataSet = dataSet.substring(0, dataSet.length-1);
		    	jsonString += "]}";
		    	dataSet += "]";
 			   				   	
		 	   	$("#myTable").DataTable( {
		 	   	"columnDefs": [
		 	   	           { className: "my_class", "targets": [ 0 ] }
		 	   	         ],
		 		 	   		
			        data: JSON.parse(dataSet)
			    } );
		
		    	},
		        error: function(errorThrown){
		            alert(errorThrown);
		            alert("There is an error with AJAX!");
		        }        
		    
			});
		
		document.getElementById("dataconverter_btn").disabled = false;
		});
	
	
	$("#dataconverter_btn").click(function () {
		
		var jsonData = jsonString;
		var request = $.ajax({
			url: "dataconverter",
			type: "POST",
			data: jsonData,
			dataType: "text",
			success : function(response) {
				console.log(response);
				var messageHTML='<font size="3" color="#004584"><b>' + response + ' </b></font>';
				document.getElementById("StorageMessageDiv").innerHTML = messageHTML; 
  		    	},
  		        error: function(errorThrown){
  		            alert("There is an error with Input Data File!");
  		        }     
			});	
		document.getElementById("missingvaluehandler_btn").disabled = false;
		document.getElementById("outlierhandler_btn").disabled = false;
		document.getElementById("discretizer_btn").disabled = false;
		document.getElementById("featureselector_btn").disabled = false;
	    });
	
	$("#missingvaluehandler_btn").click(function () {
		var request = $.ajax({
			url: "missingvaluehandler",
			type: "POST",
			dataType: "json",
			success : function(response) {
				console.log(response);
	            var processConfirmation = response.confirmationMessage[0];
	            console.log(processConfirmation);
	            var messageHTML='<font size="3" color="#004584"><b>' + processConfirmation + '</b></font>';
				document.getElementById("MessageDiv").innerHTML = messageHTML; 
  		    	},
  		        error: function(errorThrown){
  		            alert("There is an error with Input Data File!");
  		        }     
        	});
		document.getElementById("modellearner_btn").disabled = false;
	    });
	
	$("#outlierhandler_btn").click(function () {
		var request = $.ajax({
			url: "outlierhandler",
			type: "POST",
			dataType: "json",
			success : function(response) {
				console.log(response);
	            var messageHTML='<font size="3" color="#004584"><b>' + response + ' </b></font>';
				document.getElementById("MessageDiv").innerHTML = messageHTML; 
  		    	},
  		        error: function(errorThrown){
  		            alert("There is an error with Input Data File!");
  		        }     
			});	
		document.getElementById("modellearner_btn").disabled = false;
	    });
		
	$("#discretizer_btn").click(function () {
		var request = $.ajax({
			url: "datadiscretizer",
			type: "POST",
			dataType: "json",
			success : function(response) {
				console.log(response);
	            var processConfirmation = response.confirmationMessage[0];
	            console.log(processConfirmation);
	            var messageHTML='<font size="3" color="#004584"><b>' + processConfirmation + '</b></font>';
	            document.getElementById("MessageDiv").innerHTML = messageHTML; 
  		    	},
  		        error: function(errorThrown){
  		            alert("There is an error with Input Data File!");
  		        }     
        	});
		document.getElementById("modellearner_btn").disabled = false;
	    });
	
	
	$("#featureselector_btn").click(function () {
		var request = $.ajax({
			url: "featuresselector",
			type: "POST",
			dataType: "json",
			success : function(response) {
				console.log(response);
	            var processConfirmation = response.confirmationMessage[0];
	            console.log(processConfirmation);
	            var messageHTML='<font size="3" color="#004584"><b>' + processConfirmation + '</b></font>';
	            document.getElementById("MessageDiv").innerHTML = messageHTML; 
  		    	},
  		        error: function(errorThrown){
  		            alert("There is an error with Input Data File!");
  		        }     
        	});
		document.getElementById("modellearner_btn").disabled = false;
	    });

		
	$("#modellearner_btn").click(function () {
		$("#communicationVariable").val("Communication Test");
		document.forms['modellearnerForm'].submit() ;
	});	
});

</script>	

</HEAD>
<BODY>
<TABLE id=header cellPadding=0 style="width: 100%">
  <TBODY>
  <TR>
    <TD align="left" style="width: 100%" >
	<img border="0" src="images/banner.jpg" height="106"></TD>
    <TD align="right" style="width: 30%">
	<img border="0" src="images/MM_logo.png" height="106" ></TD>
    </TR></TBODY></TABLE>
<TABLE cellPadding=0>
  <TBODY>
  <TR>
    <TD id=tran1></TD></TR>
  <TR>
    <TD id=tran2 height="171"></TD></TR></TBODY></TABLE>
<TABLE id=menubar cellPadding=0>
  <TBODY>
  <TR>
    <TD>
     <TABLE style="WIDTH: 100%" cellSpacing=0 cellPadding=0 border=0>
        <TBODY>
        <TR>
          <TD align=right>
          <a href="index.jsp">
		  <img border="0" src="images/main.gif" height="21"></a>
          </TD>
		  </TR></TBODY></TABLE></TD></TR></TBODY></TABLE>
		  
		  
<TABLE id=main cellPadding=0 style="width: 100%">
  <TBODY>
  <TR>
    <TD id=leftMenu width="100%" rowspan="2">
                 &nbsp;</TD>
    </TR></TBODY></TABLE>
    
    <TABLE align=center border=2 borderColor=#39597d width="100%">
              <TBODY>
              <TR>
                <TD>
        <br><br>
        <div align="center">    
		     	<font size="5" color="#004584"><b>Data Preprocessor </b></font><br><br><br>
		 <p class="bg-info"><b>For loading of the data from an external source, click <font color="#004584"><i>'Load Data'</i></font> button.</b></p>
				<br>  
		     	<button id="loaddata_btn" class="btn btn-primary" type="button"><span class="glyphicon glyphicon-cloud-download"></span> Load Data</button>
                </div>                          
                <textarea id="loadingdataQueryId" style="visibility: hidden">${loadingdataQueryId}</textarea>
        <table id="myTable" class="display" width="80%">
  		<thead align="center">
            <tr id="myHeaderRow" >
            </tr>
        </thead>
        <tbody align="center"></tbody>
  		</table>
 		<br>
		<br>
		<div align="center">
		<p class="bg-info"><b>To start data preprocessing tasks, click <font color="#004584"><i>'Save External Data'</i></font> button to store the data into your local machine.</b></p>
			<br>  
			<button id="dataconverter_btn" class="btn btn-primary" type="button"><span class="glyphicon glyphicon-floppy-disk"></span> Save External Data</button>
  		<br><br>
  		<div id="StorageMessageDiv" align="center" style="border: 0px #d3d3d3 solid;"><br/></div><br/>
		<br>
  		<p class="bg-info"><b>Preprocessor Panel</b></p>
			<br>  
  		    <button id="missingvaluehandler_btn" class="btn btn-primary" type="button"><span class="glyphicon glyphicon-star-empty"></span> Fill Missing Values</button>
  		    <button id="outlierhandler_btn" class="btn btn-primary" type="button"><span class="glyphicon glyphicon-trash"></span> Remove Outliers</button>
  		    <button id="discretizer_btn" class="btn btn-primary" type="button"><span class="glyphicon glyphicon-retweet"></span> Invoke Data Transformation</button>
  		    <button id="featureselector_btn" class="btn btn-primary" type="button"><span class="glyphicon glyphicon-filter"></span> Invoke Features Selection</button>
	<br><br><br>
	<div id="MessageDiv" align="center" style="border: 0px #d3d3d3 solid;"><br/></div><br/>
  
		<p class="bg-info"><b>For creating Classification Model, click <font color="#004584"><i>'Model Learner'</i></font> button.</b></p>
			<br> 
		<form method="POST" name='modellearnerForm' action="modellearner">
			<button id="modellearner_btn" class="btn btn-primary" type="button"><span class="glyphicon glyphicon-cog"></span> Model Learner </button>
			<input type="hidden" id="communicationVariable" name="communicationVariable" />
  		</form>
  		  </div>
	<br><br>

               </TD></TR></TBODY></TABLE>
    <table align="center" style="width: 100%">
           <tr>
		<td style="width: 100%; text-align:center">
		<font size="1" color="#39597B">
        <script language="JavaScript">
            copyright = new Date();
            currentYear = copyright.getFullYear();
            document.write("�" + currentYear + "Ubiquitous Computing Lab., Dept. of Computer Engg.");
            </script></font></td>
	</tr>
	<tr>
		<td style="width: 100%; text-align:center">
		<font size="1" color="#39597B">Kyung Hee University, Korea</font></td>
	</tr>
	      
                </table>
                </BODY>

</HTML>

<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/ProfileData.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc;

import java.io.Serializable;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author Taqdir
 */
@Entity
public class ProfileData implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
     private Long userID;
    // private GregorianCalendar dateOfBirth;
      private String dateOfBirth;
     private int genderId;
     private String genderDescription;
     private int activityLevelId;
     private String activityLevelDescription;
    private float weight;
    private float height;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof ProfileData)) {
            return false;
        }
        ProfileData other = (ProfileData) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.sc.ProfileData[ id=" + id + " ]";
    }

    /**
     * @return the userID
     */
    public Long getUserID() {
        return userID;
    }

    /**
     * @param userID the userID to set
     */
    public void setUserID(Long userID) {
        this.userID = userID;
    }

    /**
     * @return the dateOfBirth updated
     */
    public String getDateOfBirth() {
        return dateOfBirth;
    }

    /**
     * @param dateOfBirth the dateOfBirth to set
     */
    public void setDateOfBirth(String dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    /**
     * @return the genderId
     */
    public int getGenderId() {
        return genderId;
    }

    /**
     * @param genderId the genderId to set
     */
    public void setGenderId(int genderId) {
        this.genderId = genderId;
    }

    /**
     * @return the genderDescription
     */
    public String getGenderDescription() {
        return genderDescription;
    }

    /**
     * @param genderDescription the genderDescription to set
     */
    public void setGenderDescription(String genderDescription) {
        this.genderDescription = genderDescription;
    }

    /**
     * @return the activityLevelId
     */
    public int getActivityLevelId() {
        return activityLevelId;
    }

    /**
     * @param activityLevelId the activityLevelId to set
     */
    public void setActivityLevelId(int activityLevelId) {
        this.activityLevelId = activityLevelId;
    }

    /**
     * @return the activityLevelDescription
     */
    public String getActivityLevelDescription() {
        return activityLevelDescription;
    }

    /**
     * @param activityLevelDescription the activityLevelDescription to set
     */
    public void setActivityLevelDescription(String activityLevelDescription) {
        this.activityLevelDescription = activityLevelDescription;
    }

    /**
     * @return the weight
     */
    public float getWeight() {
        return weight;
    }

    /**
     * @param weight the weight to set
     */
    public void setWeight(float weight) {
        this.weight = weight;
    }

    /**
     * @return the height
     */
    public float getHeight() {
        return height;
    }

    /**
     * @param height the height to set
     */
    public void setHeight(float height) {
        this.height = height;
    }
    
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/hlca/TestHLCA_CSVMapper.java<|end_filename|>
/*
 * 
Copyright [2016] [name of copyright owner <-Put your name]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
package mm.hlca;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.ModelFactory;

import mm.icl.hlc.ContextOntologyManager.ContextOntologyManager;
import mm.icl.hlc.HLC.TimeUtil;
import mm.icl.hlc.HLCBuilder.ContextMapper;
import mm.icl.hlc.HLCNotifier.HLCNotifier;
//import mm.hlca.ContextCSVReader;
import mm.hlca.ContextCSV;




import org.apache.log4j.Logger;

public class TestHLCA_CSVMapper {
	
    private static final String COMMA_DELIMITER = ",";
	final static Logger logger = Logger.getLogger(TestHLCA_CSVMapper.class);

	static final String directory ="E:\\ICL_LOG\\TDB"; 		                  	             
	static final String ontologyFile = "file:////E:/ICL_LOG/TDB/context-v2-5.owl";             
//	static final String llcLabel = "RidingEscalator";     
//	static final String userId = "9735";

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);
		ontModel.read(ontologyFile);
		ContextOntologyManager mng = new ContextOntologyManager(directory, ontModel);
		TimeUtil util = new TimeUtil();
		try{
		if (mng.correctInitialization()) {
			ContextMapper mapper = new ContextMapper(mng.getContextOntology());
//			  Calendar cal = util.parseString("2016 04 18 10:11:25");           
/////////// CONTEXTcsvREADER.JAVA STARTS HERE ///////////
  				BufferedReader br = null;
		        try
		        {
		            //Reading the csv file
		            br = new BufferedReader(new FileReader("E:/ICL_LOG/TDB/Location.csv")); //ContextCSV Activitytest Activity
		            
		            //Create List for holding Employee objects
		            List<ContextCSV> contextList = new ArrayList<ContextCSV>();
		            
		            String line = "";
		            //Read to skip the header
		            br.readLine();
		            //Reading from the second line
		            while ((line = br.readLine()) != null) 
		            {
		                String[] ContextCSVDetails = line.split(COMMA_DELIMITER);
		                
		                if(ContextCSVDetails.length > 0 )
		                {
		                	ContextCSV context_llc = new ContextCSV(ContextCSVDetails[0], ContextCSVDetails[1],ContextCSVDetails[2]);
		                	contextList.add(context_llc);
		                }
		            }
		            
		            //Lets print the Employee List
		            for(ContextCSV c : contextList)
		            { 
		            	
		                System.out.println(c.getllcLabel()+" "+ c.getuserId()+" "+ util.parseString(c.getcal()));
//		  			  mapper.mapLLC(llcLabel, userId, cal);
			  			  mapper.mapLLC(c.getllcLabel(), c.getuserId(), util.parseString(c.getcal()));
		                
		                //		                System.out.println(util.parseString(c.getcal())); //                System.out.println(c.getcal()); //                System.out.println(c.getuserId()); //                System.out.println(c.getllcLabel());
		            }
		        }
		        catch(Exception ee)
		        {
		            ee.printStackTrace();
		        }
		        finally
		        {
		            try
		            {
		                br.close();
		            }
		            catch(IOException ie)
		            {
		                System.out.println("Error occured while closing the BufferedReader");
		                ie.printStackTrace();
		            }
		        }
		        
		        
		///////// CONTEXTcsvREADER.JAVA ENDS HERE ///////////	        
		
		
		
		}
		
		} catch (Exception e) {
			logger.error("Error while Notifying HLC.  Message: " + e.getMessage());
			
			e.printStackTrace();
		}
	}
}




















/*
 * package mm.hlca;
import java.util.Calendar;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import mm.icl.hlc.ContextOntologyManager.ContextOntologyManager;
import mm.icl.hlc.HLC.TimeUtil;
import mm.icl.hlc.HLCBuilder.ContextMapper;
public class TestHLCAMapper {
	static final String directory ="E:\\ICL_LOG\\TDB"; 		                  	             
	static final String ontologyFile = "file:////E:/ICL_LOG/TDB/context-v2-5.owl";             
	static final String llcLabel = "Salmon";                               //"Sitting";"Office" Boredom Office Happiness Mall
	static final String userId = "9735";
	//static final String startTime = "2015-08-10T11:25:50+09:00";
	public static void main(String[] args) {
		// READ THE CONTEXT ONTOLOGY FROM FILE
		OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);
		ontModel.read(ontologyFile);
		// CREATE THE CONTEXT ONTOLOGY MANAGER
		ContextOntologyManager mng = new ContextOntologyManager(directory, ontModel);
		TimeUtil util = new TimeUtil();
		if (mng.correctInitialization()) {
			// CREATE THE MAPPER
			ContextMapper mapper = new ContextMapper(mng.getContextOntology());
			// MAP LLC
			  Calendar cal = util.parseString("2016 04 18 10:11:25");                       //10:06:50  Calendar.getInstance();  //Asif (from DongUK)
			  mapper.mapLLC(llcLabel, userId, cal);                                         //Asif (from DongUK)
			//mapper.mapLLC(llcLabel, userId, startTime.);
		}
/*            ORignal
 * 
 *       	// CREATE THE MAPPER
			ContextMapper mapper = new ContextMapper(mng.getContextOntology());
			// MAP LLC
			//mapper.mapLLC(llcLabel, userId, startTime);
 * */
	

<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/framework/RecInterpreter/FoodItemRecommender/SNSTrendIdentifier.java<|end_filename|>
/* Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.scl.framework.RecInterpreter.FoodItemRecommender;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.uclab.scl.communication.CommunicationManager;
import org.uclab.scl.interpreterdatamodel.SNSTrends;

public class SNSTrendIdentifier{
  private static Logger LOG = LogManager.getRootLogger();
  
  static HashMap<String, String> mapNutrientToCategory = new HashMap<>();
  static HashMap<String, String> mapCatToFooditems = new HashMap<>();
  static HashMap<String, String> mapFooditemsToNutrient = new HashMap<>();
  static HashMap<String, String> mapUserChoices = new HashMap<>();
  
  /**
   * The main purpose of this class is to process food related recommendations. This function receives the recommended nutrient label and userid
   * Current trends against the food category are received from [SO] which in turn calls SNS services provided by [SL]
   * Received food items are filtered based on the major nutrients and user's dislike list
   * Final list of food items is provided to getFoodRecommendation() function
   * 
   * @param nutrientLabel
   * @param userid
   * @return
   * @throws Exception
   */

  @SuppressWarnings("unchecked")
  public String processFoodRec(String nutrientLabel, String userid) throws Exception {  
	  
    NutrientToCategoryMapper nutritionToCat = new NutrientToCategoryMapper();
    CategoryToFooditemsMapper catToFood = new CategoryToFooditemsMapper();
    mapNutrientToCategory = nutritionToCat.NutrientToCategoryMapper();
    mapCatToFooditems = catToFood.CatToFooditemsMapper();
    String foodCategory = mapNutrientToCategory.containsKey(nutrientLabel) ? mapNutrientToCategory.get(nutrientLabel) : mapNutrientToCategory.get(null);
    if (foodCategory == null){
      LOG.debug("FoodCategory not found in the low repository");
      foodCategory = "Protein";
    }
    LOG.debug("Nutrient to Category: " + nutrientLabel + ": " + foodCategory);
    CommunicationManager commManager = CommunicationManager.getCommunicationManager();
    
    SNSTrends snsTrends = commManager.getSNSTrendsFromSLforFoods(foodCategory);
    
    String rawFoodItems = "";
    for (String fooditem : snsTrends.getName()) {
      rawFoodItems = rawFoodItems + fooditem + ",";
    }
    rawFoodItems = rawFoodItems.substring(0, rawFoodItems.length() - 1);
    LOG.debug("RawFooditems for Category: " + rawFoodItems);
    FooditemsToNutrientMapper foodItemsToNut = new FooditemsToNutrientMapper();
    mapFooditemsToNutrient = foodItemsToNut.FooditemtoNutrientMapper();
    String processedList = "";
    String rawFoodArr[] = rawFoodItems.split(",");
    String item = "";
    for (String fooditem : rawFoodArr) {
      item = mapFooditemsToNutrient.containsKey(fooditem) ? mapFooditemsToNutrient.get(fooditem) : mapFooditemsToNutrient.get(null);
      if (item != null)
        if (item.equals(nutrientLabel))
          processedList = processedList + fooditem + ",";
      }
    processedList = processedList.substring(0, processedList.length() - 1);
    LOG.debug("Processedlist for " + nutrientLabel + ": " + processedList);
    // Fifth filter out those fooditems which are on the user's dislike list
    String finalList = "";
    String processedfood_Arr[] = processedList.split(",");
    UserChoiceMapper userCh = new UserChoiceMapper();
    mapUserChoices = userCh.UserChoicesMapper();    
    String userDislikes = mapUserChoices.containsKey(userid) ? mapUserChoices.get(userid) : mapUserChoices.get("default");
    if (userDislikes.equals("default")) {
      LOG.debug("Preference NOT FOUND in the repository");
      userDislikes = mapUserChoices.get("default");    //?
    }
    String foodDislike[] = userDislikes.split(",");
    LOG.debug("User dislike list : " + userDislikes);
    for (String fooditem : processedfood_Arr) {
      if (!userDislikes.contains(fooditem))
        finalList = finalList + fooditem + ",";
    }
    finalList = finalList.substring(0, finalList.length() - 1);
    String processedFoodItems[] = finalList.split(",");
    finalList = "";
    int index = 0;
    String trendValues = "";
    for (String fooditem : processedFoodItems) {
      if (snsTrends.getName().contains(fooditem)) {
        index = snsTrends.getName().indexOf(fooditem);
        trendValues = snsTrends.getTotal().get((index));
        LOG.debug("Fooditem =" + fooditem + " TrendValue ="+ trendValues);
        finalList = finalList + fooditem + ","+ trendValues + ",";
      }
    }
    finalList = finalList.substring(0, finalList.length() - 1);
    LOG.debug("final list" + finalList);
    return (finalList);
  }
}


<|start_filename|>knowledge-curation-layer/i-kat/src/main/webapp/WEB-INF/views/RulesDashboard.jsp<|end_filename|>
<!--
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

-->	
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ page session="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<link href="${pageContext.request.contextPath}/resources/css/bootstrap.min.css" rel="stylesheet">
	<link href="${pageContext.request.contextPath}/resources/css/bootstrap-responsive.min.css" rel="stylesheet">
	<link href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600" rel="stylesheet">
	<link href="${pageContext.request.contextPath}/resources/css/font-awesome.css" rel="stylesheet">
	<link href="${pageContext.request.contextPath}/resources/css/style.css" rel="stylesheet">
	<link href="${pageContext.request.contextPath}/resources/css/pages/dashboard.css" rel="stylesheet">
    <title>Rules Dashboard</title>
    <style type="text/css">
        .tg  {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
        .tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#fff;}
        .tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#f0f0f0;}
        .tg .tg-4eph{background-color:#f9f9f9}
    </style>
</head>
<body>
<!--  Start of header -->
<div class="navbar navbar-fixed-top">
  <div class="navbar-inner">
    <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"><span
                    class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span> </a><a class="brand" href="index.aspx"> <img src="<c:url value="resources/images/MMlogo.png" />" style="height:55px; float:left; margin-right:10px;" /> &nbsp;Expert-Driven Intelligent Knowledge Authoring Tool</a>
      <div class="nav-collapse">
        <ul class="nav pull-right"> 
          <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown"><i
                            class="icon-cog"></i> Account <b class="caret"></b></a>
            <ul class="dropdown-menu">
              <li><a href="#">Settings</a></li>
              <li><a href="#">Help</a></li>
            </ul>
          </li>
          <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown"><i
                            class="icon-user"></i> Dr. John <b class="caret"></b></a>
            <ul class="dropdown-menu">
              <li><a href="#">Profile</a></li>
              <li><a href="login.aspx">Logout</a></li>
            </ul>
          </li>
        </ul>
      </div>
      <!--/.nav-collapse --> 
    </div>
    <!-- /container --> 
  </div>
  <!-- /navbar-inner --> 
</div>
<!-- /navbar -->
<div class="subnavbar">
  <div class="subnavbar-inner">
    <div class="container">
      <ul class="mainnav">


        <li class="active"><a href="rules"><i class="icon-dashboard"></i><span>Dashboard</span> </a> </li>
        <li><a href="addNewRule"><i class="icon-list-alt"></i><span>Rule Editor</span> </a> </li>
        <li><a href="#"><i class="icon-eye-open "></i><span>Show Created Rule</span> </a></li>
      </ul>
    </div>
    <!-- /container --> 
  </div>
  <!-- /subnavbar-inner --> 
</div>
<!-- /subnavbar -->
<div class="main">
  <div class="main-inner">
    <div class="container">
      <div class="row">
<!--  End of header -->
<br>
<h3>Rules List</h3>
<a href="<c:url value='/addNewRule' />" class="btn btn-primary mBottom pull-right"  ><i class="icon-plus"></i> Add new rule</a>
<c:if test="${!empty listRules}">
    <table class="table table-striped table-hover table-bordered">
    <tr>
        <th width="80">Rule Title</th>
        <th width="120">Specialist Name</th>
        <th width="120">Institution</th>
        <th width="120">Created Date</th>
        <th width="60">Edit</th>
        <th width="60">Delete</th>
    </tr>
    <c:forEach items="${listRules}" var="Rules">
        <tr>
            <td>${Rules.getRuleTitle()}</td>
            <td>${Rules.getSpecialistName()}</td>
            <td>${Rules.getInstitution()}</td>
            <td>${Rules.getRuleCreatedDate()}</td>
            <td><a href="<c:url value='/edit/${Rules.getRuleID()}' />"  class="btn btn-default"  ><i class="icon-pencil"></i> Edit</a></td>
            <td><a href="<c:url value='/remove/${Rules.getRuleID()}' />" class="btn btn-default"  > <i class="icon-trash"></i> Delete</a></td>
        </tr>
    </c:forEach>
    </table>
</c:if>

<!-- Start of Footer -->

 </div>
      <!-- /row --> 
    </div>
    <!-- /container --> 
  </div>
  <!-- /main-inner --> 
</div>
<!-- /main --> 

<div class="extra">

	<div class="extra-inner">

		<div class="container">

			<div class="row">
                    <div class="span3">
                        
                      <img src="<c:url value="resources/images/uclab_logo.png" />"  />
                   
                      
                    </div>
                   
      <div class="span9">
                       
                          <p>The UCLab. at the <a href="http://www.kyunghee.edu" target="_blank">Kyung Hee University</a> is consisted of more than 30 Post-doc, Ph.D and Master students,   working on research projects under the supervision of Prof. <NAME>, who studied in the field of ubiquitous systems.</p>
                    </div>
         
          </div> <!-- /row -->

		</div> <!-- /container -->

	</div> <!-- /extra-inner -->

</div>
<!-- extra -->
<div class="footer">
  <div class="footer-inner">
    <div class="container">
      <div class="row">
        <div class="span12"> &copy; 2015. Intelligent Knowledge Authoring Tool.</div>
        <!-- /span12 --> 
      </div>
      <!-- /row --> 
    </div>
    <!-- /container --> 
  </div>
  <!-- /footer-inner --> 
</div>
<!-- /footer --> 
<!-- Le javascript
================================================== --> 
<!-- Placed at the end of the document so the pages load faster --> 

<!-- end of footer --> 
</body>
</html>

<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/OntologyTools/ClinicalContext.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.OntologyTools;
import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.ontology.OntResource;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
import com.hp.hpl.jena.vocabulary.OWL2;
/**
 * clinical Context is the class encapsulating the OntModel associated to a
 * clinical Context Instance. This is an instance of the clinical Context
 * class in the Context Ontology which represents the Mining Minds Context
 * Model. This class provides supporting methods to facilitate the access to
 * clinical Context.
 * 
 * @author <NAME> and <NAME>
 * @version 2.5
 * @since 2015-10-28
 */
public class ClinicalContext extends Context{   
	/**
	 * Constructor of a new clinical Context instance.
	 * 
	 * @param hlcModel
	 *            OntModel associated to the clinical Context instance.
	 */
	public ClinicalContext(OntModel hlcModel) {
		super(hlcModel);
	}
	/**
	 * Constructor of a new clinical Context instance.
	 * 
	 * @param hlcModel
	 *            OntModel associated to the clinical Context instance.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 */
	public ClinicalContext(OntModel hlcModel, ContextOntology ont) {
		super(hlcModel);
		OntModel hlcInst = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, hlcModel);
		hlcInst.addSubModel(ont.getCtxModel());
		ExtendedIterator<? extends OntResource> it = hlcInst.getOntClass(HLCA.clinicalClassName).listInstances(false); 
		if (it.hasNext()) {
			Individual inst = (Individual) it.next();
			if (!it.hasNext()) {
				super.ctxInstanceName = inst.getURI();
				ExtendedIterator<Resource> iter = inst.listRDFTypes(true);
				boolean classified = false;
				while (iter.hasNext()) {
					String uri = iter.next().getURI();
					if (uri != null && !uri.equals(OWL2.NamedIndividual.getURI())) {
						if (!uri.equals(HLCA.clinicalClassName)) {   
							super.ctxTypeName = uri;
							classified = true;
						}
					}
				}
				if (!classified)
					setUnidentifiedHlc();
			}
		}
	}
	/**
	 * Method to retrieve whether a clinical Context instance is valid or not.
	 * 
	 * @return true if the clinical Context Instance is valid, and false
	 *         otherwise.
	 */
	public boolean isValidInstanceOfHlc() {
		return (super.ctxInstanceName != null);
	}
	/**
	 * Method to retrieve whether a clinical Context instance has been
	 * classified or not.
	 * 
	 * @return true if the clinical Context Instance is classified, and false
	 *         otherwise.
	 */
	public boolean isClassified() {
		return (super.ctxTypeName != null && !super.ctxTypeName.equals(HLCA.unidentifiedHlc));
	}
	/**
	 * Method to set the clinical Context Instance.
	 * 
	 * @param inst
	 *            OntResource representing the clinical Context Instance.
	 */
	public void setHlcInstance(OntResource inst) {
		setCtxInstanceName(inst.getURI());
	}
	/**
	 * Method to set the class to which a the clinical Context Instance
	 * belongs to.
	 * 
	 * @param c
	 *            OntClass to which the clinical Context Instance belongs and
	 *            which has to be added.
	 */
	public void setHlcClass(OntClass c) {
		getCtxIndiv().addOntClass(c);
		setCtxTypeName(c.getURI());
	}
	/**
	 * Method to set that the clinical Context Instance does not belongs to
	 * any of the defined classes in the Context Ontology. This process does not
	 * involve any changes in the OntModel associated to the clinical Context
	 * Instance, but only setting the type of the Context Instance. This is done
	 * this way in order to avoid conflicts in the future and to ensure the
	 * Context Ontology extensibility.
	 * 
	 */
	public void setUnidentifiedHlc() {
		setCtxTypeName(HLCA.unidentifiedHlc);
	}
}

<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/communication/ServiceCommunicator.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */
package org.uclab.mm.dcl.llm.communication;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;

import org.uclab.mm.dcl.llm.dataaccess.SituationEventDAOImp;
import org.uclab.mm.dcl.llm.monitoring.*;
import org.uclab.mm.dcl.llm.objectmodel.FoodLog;
import org.uclab.mm.dcl.llm.objectmodel.SituationConditions;
import org.uclab.mm.dcl.llm.objectmodel.SituationEvents;
import org.uclab.mm.dcl.llm.objectmodel.Violations;
import org.uclab.mm.dcl.llm.objectmodel.VoilationNotification;

/**
 * REST Web Service
 *
 * @author Rizvi
 */
// @Path("testweb")
@Path("servicecommunicator")
public class ServiceCommunicator {

	@Context
	private UriInfo context;

	/**
	 * Creates a new instance of testweb
	 */
	public ServiceCommunicator() {
	}

	/**
	 * Retrieves representation of an instance of ServiceCommunicator
	 *
	 * @return an instance of java.lang.String
	 */
	@GET
	@Produces("application/json")
	@Path("/")
	public String getJson() {
		// TODO return proper representation object
		throw new UnsupportedOperationException();
	}

	/**
	 * PUT method for updating or creating an instance of ServiceCommunicator
	 *
	 * @param content
	 *            representation for the resource
	 * @return an HTTP response with content of the updated or created resource.
	 */
	@PUT
	@Consumes("application/json")
	@Path("/")
	public void putJson(String content) {
	}

	@POST
	@Produces("application/json")
	@Consumes("application/json")
	@Path("/AddFoodLog/")
	public String AddFoodLog(FoodLog objOuterFoodLog) {

		// List<String> response = new ArrayList<String>();
		String strResponse = "Done";
		try {
			NutritionMonitor ObjNutritionMonitoring = new NutritionMonitor();
			// strResponse = ObjNutritionMonitoring.doMonitor(objOuterFoodLog);
			ObjNutritionMonitoring.doMonitor(objOuterFoodLog);

			// Gson objJson = new Gson();
			// strResponse = objJson.toJson(response);
		} catch (Exception ex) {
		}

		return strResponse;
	}

	/**
	 * Retrieves violation from the log .
	 *
	 * @return List<Violations>
	 *
	 */
	@GET
	@Path("/Violations/")
	@Produces(MediaType.APPLICATION_JSON)
	public List<Violations> getViolationConditions() {
		VoilationNotification objViolationNotification = new VoilationNotification();
		return objViolationNotification.getViolations();

	}

	/**
	 * Retrieves total count of the violation from the log.
	 *
	 * @return List<Violations>
	 */
	@GET
	@Path("/TotalViolations/")
	@Produces(MediaType.APPLICATION_JSON)
	public List<Violations> getTotalViolationConditions() {
		VoilationNotification objViolationNotification = new VoilationNotification();
		return objViolationNotification.getTotalViolations();

	}

	/**
	 * Retrieves total count of the violation from the log.
	 *
	 * @return List<Violations>
	 */
	@GET
	@Path("/PhysicalMonitoring/")
	@Produces(MediaType.APPLICATION_JSON)
	public String getStartedPhysicalMonitoring() throws SQLException,
			IOException, IllegalThreadStateException {
		Thread t = new Thread(new LifeLogMonitoring());
		t.start();
		System.out.println("Deamon is running Alone......");
		return "MonitoringStarted ";
	}

	/**
	 * Retrieves total violation from the log against a user information in term
	 * of ID.
	 *
	 * @param uid
	 * @return List<Violations>
	 */
	@GET
	@Path("/UserViolations/{uid}")
	@Produces(MediaType.APPLICATION_JSON)
	public List<Violations> getUserViolationConditions(
			@PathParam("uid") String uid) {
		VoilationNotification objViolationNotification = new VoilationNotification();
		return objViolationNotification.getUserViolations(uid);

	}

	/**
	 * Retrieves violation details from the log against a log information in
	 * term of ID.
	 *
	 * @param lgid
	 * @return List<Violations>
	 */
	@GET
	@Path("/LogViolations/{lgid}")
	@Produces(MediaType.APPLICATION_JSON)
	public List<Violations> getLogViolationConditions(
			@PathParam("lgid") String lgid) {
		VoilationNotification objViolationNotification = new VoilationNotification();
		return objViolationNotification.getLogDeatails(lgid);

	}

	/**
	 * Retrieves violation with sequence grater then the provided id from the
	 * log.
	 *
	 * @param lgid
	 * @return List<Violations>
	 */
	@GET
	@Path("/SLViolations/{maxlgid}")
	@Produces(MediaType.APPLICATION_JSON)
	public List<Violations> getMaxLogViolationConditions(
			@PathParam("maxlgid") String maxlgid) {
		VoilationNotification objViolationNotification = new VoilationNotification();
		return objViolationNotification.getMaxViolations(maxlgid);

	}

	/**
	 * Accept the json of the constraints and monitoring conditions required for
	 * monitoring and assessing the conditions.
	 *
	 * @param siuationEvents
	 * @return
	 */
	@POST
	@Path("SituationAdd")
	@Produces("application/json")
	@Consumes("application/json")
	public String addSituationEvents(SituationEvents siuationEvents) {
		String sitID = "SuccessfullyProcessed ";
		SituationEventDAOImp imp = new SituationEventDAOImp();
		imp.persistentSituation(siuationEvents);
		return sitID;
	}

}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/MachineLearningTools/StatisticalFeatureExtraction.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Bang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.MachineLearningTools;

import java.util.Arrays;

import mm.icl.llc.MachineLearningTools.FeatureExtraction;

/**
 * This Class extract statistical feature such as mean, stddev, etc.
 * @author <NAME>
 *
 */

public class StatisticalFeatureExtraction extends FeatureExtraction {
	
	/**
	 * No Define
	 */
	@Override
	public Object extractFeature(Object input) {
		// TODO Auto-generated method stub
		return null;
	}
	
	/***
	 * Extract Average
	 * @param doubles
	 * @return double
	 */
	
	public double getMean(double[] doubles) {
		double result = 0;
		for (int i = 0; i < doubles.length; i++) {
			result = result + doubles[i];
		}
		result = result / doubles.length;
		return result;
	}
	/**
	 * Normalize Data
	 * @param doubles
	 * @return double[]
	 */

	public double[] normalization(double[] doubles) {
		double[] result = new double[doubles.length];
		double mean = getMean(doubles);
		double diff = 0;
		double sum = 0;
		double Var = 0;
		for (int i = 0; i < doubles.length; i++) {
			diff = doubles[i] - mean;
			sum += (diff * diff);
		}
		Var = sum / doubles.length;

		for (int i = 0; i < doubles.length; i++) {
			result[i] = (doubles[i] - mean) / Var;
		}
		return result;
	}
	/**
	 * Extract Standard Deviation
	 * @param doubles
	 * @return double
	 */

	public double getStdDev(double[] doubles) {
		double result = 0;
		double mean = getMean(doubles);
		double diff = 0;
		double sum = 0;
		for (int i = 0; i < doubles.length; i++) {
			diff = doubles[i] - mean;
			sum += (diff * diff);
		}
		result = Math.sqrt(sum / doubles.length - 0);
		return result;
	}
	
	/**
	 * Extract Minimum
	 * @param doubles
	 * @return double
	 */

	public double getMin(double[] doubles) {
		Arrays.sort(doubles);
		return doubles[0];
	}
	/**
	 * Extract Maximum
	 * @param doubles
	 * @return double
	 */

	public double getMax(double[] doubles) {
		Arrays.sort(doubles);
		return doubles[doubles.length - 1];
	}
	
	/**
	 * Extract Energy
	 * @param doubles
	 * @return double[]
	 */

	private double[] getEnergy(double[] doubles) {
		double[] result = new double[doubles.length];
		for (int i = 0; i < doubles.length; i++) {
			result[i] = (doubles[i] * doubles[i]);
		}
		return result;
	}
	/**
	 * Extract Energy Average
	 * @param doubles
	 * @return double
	 */

	public double getEnergyMean(double[] doubles) {
		double[] energy = getEnergy(doubles);
		return getMean(energy);
	}
	/**
	 * Extract Energy Standard Deviation
	 * @param doubles
	 * @return double
	 */

	public double getEnergyStdDev(double[] doubles) {
		double[] energy = getEnergy(doubles);
		return getStdDev(energy);
	}
	/**
	 * Extract Energy Maximum
	 * @param doubles
	 * @return double
	 */

	public double getEnergyMax(double[] doubles) {
		double[] energy = getEnergy(doubles);
		Arrays.sort(energy);
		return energy[energy.length - 1];
	}

	/**
	 * Extract Energy Median
	 * @param doubles
	 * @return double
	 */
	public double getEnergyMedian(double[] doubles) {
		double[] energy = getEnergy(doubles);
		return getMedian(energy);

	}
	/**
	 * Extract Median
	 * @param doubles
	 * @return double
	 */

	public double getMedian(double[] doubles) {
		if (doubles.length == 0)
			return Double.NaN;
		int center = doubles.length / 2;

		if (doubles.length % 2 == 1) {
			return doubles[center];
		} else {
			return (doubles[center - 1] + doubles[center]) / 2.0;
		}
	}

	

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/dataadapter/UserGoalAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.sc.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.sc.UserGoal;

/**
 * This is UserGoalAdapter class which implements the Data Access Interface for CRUD operations
 * @author Taqdir
 */
public class UserGoalAdapter implements DataAccessInterface{

    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(UserGoalAdapter.class);
    public UserGoalAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving UserGoal. 
     * @param objUserGoal
     * @return List of String
     */
    @Override
    public List<String> Save(Object objUserGoal) {
        UserGoal objInnerUserGoal = new UserGoal();
        objInnerUserGoal =  (UserGoal) objUserGoal;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_UserGoal(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserID", objInnerUserGoal.getUserId());
            objCallableStatement.setInt("WeightStatusID", objInnerUserGoal.getWeightStatusId());
            objCallableStatement.setLong("DailyCaloriesIntake", objInnerUserGoal.getDailyCaloriesInTake());
            objCallableStatement.setFloat("IdealWeight", objInnerUserGoal.getIdealWeight());
            objCallableStatement.setString("GoalDescription", objInnerUserGoal.getGoalDescription());
            objCallableStatement.setLong("TotalCaloriesToBurn", objInnerUserGoal.getTotalCaloriesToBurn());
            objCallableStatement.setInt("BurnedCalories", objInnerUserGoal.getBurnedCalories());
            
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
            Date dtDate = sdf.parse(objInnerUserGoal.getDate());
            
            Timestamp tsDate = new Timestamp(dtDate.getYear(),dtDate.getMonth(), dtDate.getDate(), dtDate.getHours(), dtDate.getMinutes(), dtDate.getSeconds(), 00);
            objCallableStatement.setTimestamp("Date", tsDate);
            
            objCallableStatement.setInt("DailyBurnedCal", objInnerUserGoal.getDailyBurnedCal());
            objCallableStatement.setInt("WeeklyBurnedCal", objInnerUserGoal.getWeklyBurnedCal());
            objCallableStatement.setInt("MonthlyBurnedCal", objInnerUserGoal.getMonthlyBurnedCal());
            objCallableStatement.setInt("QuarterlyBurnedCal", objInnerUserGoal.getQuarterlyBurnedCal());
            objCallableStatement.setFloat("BMI", objInnerUserGoal.getbMI());
            
            objCallableStatement.registerOutParameter("UserGoalID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intUserGoalID = objCallableStatement.getLong("UserGoalID");
            objDbResponse.add(String.valueOf(intUserGoalID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("User Goal saved successfully, User Goal Details="+objUserGoal);
        }
        catch (Exception e)
        {
        	logger.info("Error in Adding User Goal");
        	objDbResponse.add("Error in Adding User Goal");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for Update UserGoal. 
     * Not implemented
     */
    @Override
    public <T> List<String> Update(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for retrieving UserGoal.
     * @param objUserGoal
     * @return List of UserGoal 
     */
    @Override
    public List<UserGoal> RetriveData(Object objUserGoal) {
        UserGoal objOuterUserGoal = new UserGoal();
        List<UserGoal> objListInnerUserGoal = new ArrayList<UserGoal>();
        objOuterUserGoal =  (UserGoal) objUserGoal;
        
        try
        {
            CallableStatement objCallableStatement = null;
            if(objOuterUserGoal.getRequestType() == "ByUserOnly")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_SituationByUserID(?)}");
                objCallableStatement.setLong("UserID", objOuterUserGoal.getUserId());
            }
            else if(objOuterUserGoal.getRequestType() == "ByUserandDate")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_BurnedCaloriesByUserIDDate(?, ?, ?)}");
                
               SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
               Date dtStartDate = sdf.parse(objOuterUserGoal.getStartDate());
               Timestamp tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);

               Date dtEndDate =sdf.parse( objOuterUserGoal.getEndDate()); //.getTime();
               Timestamp tsEndDate = new Timestamp(dtEndDate.getYear(),dtEndDate.getMonth(), dtEndDate.getDate(), dtEndDate.getHours(), dtEndDate.getMinutes(),dtEndDate.getSeconds(),0);
            
                objCallableStatement.setLong("UserID", objOuterUserGoal.getUserId());
                objCallableStatement.setTimestamp("StartTime", tsStartDate);
                objCallableStatement.setTimestamp("EndTime", tsEndDate);
            }
            
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                UserGoal objInnerUserGoal = new UserGoal();
                objInnerUserGoal.setUserGoalId(objResultSet.getLong("UserGoalID"));
                objInnerUserGoal.setUserId(objResultSet.getLong("UserID"));
                objInnerUserGoal.setWeightStatusId(objResultSet.getInt("WeightStatusID"));
                objInnerUserGoal.setDailyCaloriesInTake(objResultSet.getLong("DailyCaloriesIntake"));
                objInnerUserGoal.setIdealWeight(objResultSet.getFloat("IdealWeight"));
                objInnerUserGoal.setGoalDescription(objResultSet.getString("GoalDescription"));
                objInnerUserGoal.setTotalCaloriesToBurn(objResultSet.getLong("TotalCaloriesToBurn"));
                objInnerUserGoal.setBurnedCalories(objResultSet.getInt("BurnedCalories"));
                objInnerUserGoal.setDate(objResultSet.getString("Date"));
               try
               {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
                    Date tsDate = sdf.parse(objResultSet.getTimestamp("Date").toString());
                    objInnerUserGoal.setDate( tsDate.toString());
               }
               catch(Exception ex)
               {}
                

                objInnerUserGoal.setDailyBurnedCal(objResultSet.getInt("DailyBurnedCal"));
                objInnerUserGoal.setWeklyBurnedCal(objResultSet.getInt("WeeklyBurnedCal"));
                objInnerUserGoal.setMonthlyBurnedCal(objResultSet.getInt("MonthlyBurnedCal"));
                objInnerUserGoal.setQuarterlyBurnedCal(objResultSet.getInt("QuarterlyBurnedCal"));
                objInnerUserGoal.setbMI(objResultSet.getFloat("BMI"));
                
                objListInnerUserGoal.add(objInnerUserGoal);
            }
            objConn.close();
            logger.info(" User Goal loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading  User Goal");
        }   
        return objListInnerUserGoal;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/dataadapter/UserPreferredActivitiesAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.sc.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.sc.UserPreferredActivities;

/**
 * This is UserPreferredActivitiesAdapter class which implements the Data Access Interface for CRUD operations
 * @author Taqdir
 */
public class UserPreferredActivitiesAdapter implements DataAccessInterface {

    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(UserPreferredActivitiesAdapter.class);
    public UserPreferredActivitiesAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving UserPreferredActivities.
     * @param objUserPreferredActivities
     * @return List of String
     */
    @Override
    public List<String> Save(Object objUserPreferredActivities) {
        UserPreferredActivities objInnerUserPreferredActivities = new UserPreferredActivities();
        objInnerUserPreferredActivities =  (UserPreferredActivities) objUserPreferredActivities;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_UserPreferredActivities(?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserID", objInnerUserPreferredActivities.getUserId());
            objCallableStatement.setInt("ActivityID", objInnerUserPreferredActivities.getActivityId());
            objCallableStatement.setInt("PreferenceLevelID", objInnerUserPreferredActivities.getPreferenceLevelId());
            
            objCallableStatement.registerOutParameter("UserPreferredActivityID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intUserPreferredActivityID = objCallableStatement.getLong("UserPreferredActivityID");
            objDbResponse.add(String.valueOf(intUserPreferredActivityID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("User Preferred Activities saved successfully, User Preferred Activities Details="+objUserPreferredActivities);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding User Preferred Activities");
        	objDbResponse.add("Error in adding User Preferred Activities");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for updating UserPreferredActivities. 
     * @param objUserPreferredActivities
     * @return List of String
     */
    @Override
    public List<String> Update(Object objUserPreferredActivities) {
        UserPreferredActivities objInnerUserPreferredActivities = new UserPreferredActivities();
        objInnerUserPreferredActivities =  (UserPreferredActivities) objUserPreferredActivities;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_UserPreferredActivities(?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserPreferredActivityID", objInnerUserPreferredActivities.getUserPreferredActivityId());
            objCallableStatement.setLong("UserID", objInnerUserPreferredActivities.getUserId());
            objCallableStatement.setInt("ActivityID", objInnerUserPreferredActivities.getActivityId());
            objCallableStatement.setInt("PreferenceLevelID", objInnerUserPreferredActivities.getPreferenceLevelId());
            
            objCallableStatement.execute();
            
            objDbResponse.add(String.valueOf(objInnerUserPreferredActivities.getUserPreferredActivityId()));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("User Preferred Activities updated successfully, User Preferred Activities Details="+objUserPreferredActivities);
        }
        catch (Exception e)
        {
        	logger.info("Error in updating User Preferred Activities");
        	objDbResponse.add("Error in updating User Preferred Activities");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for retrieving UserPreferredActivities. 
     * @param objUserPreferredActivities
     * @return List of UserPreferredActivities
     */
    @Override
    public List<UserPreferredActivities> RetriveData(Object objUserPreferredActivities) {
        UserPreferredActivities objOuterUserPreferredActivities = new UserPreferredActivities();
        List<UserPreferredActivities> objListInnerUserPreferredActivities = new ArrayList<UserPreferredActivities>();
        objOuterUserPreferredActivities =  (UserPreferredActivities) objUserPreferredActivities;
        
        try
        {
            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UserPreferredActivitiesByUserID(?)}");
            objCallableStatement.setLong("UserID", objOuterUserPreferredActivities.getUserId());
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                UserPreferredActivities objInnerUserPreferredActivities = new UserPreferredActivities();
                objInnerUserPreferredActivities.setUserPreferredActivityId(objResultSet.getLong("UserPreferredActivityID"));
                objInnerUserPreferredActivities.setUserId(objResultSet.getLong("UserID"));
                objInnerUserPreferredActivities.setActivityId(objResultSet.getInt("ActivityID"));
                objInnerUserPreferredActivities.setPreferenceLevelId(objResultSet.getInt("PreferenceLevelID"));
                
                objListInnerUserPreferredActivities.add(objInnerUserPreferredActivities);
            }
            objConn.close();
            logger.info("User Preferred Activities Data loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading User Preferred Activities");
        }   
        return objListInnerUserPreferredActivities;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sl/FactsFeedback.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sl;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author <NAME>
 */
@Entity
public class FactsFeedback implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private Long factsFeedbackID;
    private Long factID;
    private Long userID;
    private int rate;
    private String reason;
    private String feedbackDate;
    
    private String requestType;
    private int situationCategoryID;
    private String situationCategoryDescription;
    
    

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof FactsFeedback)) {
            return false;
        }
        FactsFeedback other = (FactsFeedback) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.sl.FactsFeedback[ id=" + id + " ]";
    }

    /**
     * @return the factsFeedbackID
     */
    public Long getFactsFeedbackID() {
        return factsFeedbackID;
    }

    /**
     * @param factsFeedbackID the factsFeedbackID to set
     */
    public void setFactsFeedbackID(Long factsFeedbackID) {
        this.factsFeedbackID = factsFeedbackID;
    }

    /**
     * @return the factID
     */
    public Long getFactID() {
        return factID;
    }

    /**
     * @param factID the factID to set
     */
    public void setFactID(Long factID) {
        this.factID = factID;
    }

    /**
     * @return the userID
     */
    public Long getUserID() {
        return userID;
    }

    /**
     * @param userID the userID to set
     */
    public void setUserID(Long userID) {
        this.userID = userID;
    }

    /**
     * @return the rate
     */
    public int getRate() {
        return rate;
    }

    /**
     * @param rate the rate to set
     */
    public void setRate(int rate) {
        this.rate = rate;
    }

    /**
     * @return the reason
     */
    public String getReason() {
        return reason;
    }

    /**
     * @param reason the reason to set
     */
    public void setReason(String reason) {
        this.reason = reason;
    }

    /**
     * @return the feedbackDate
     */
    public String getFeedbackDate() {
        return feedbackDate;
    }

    /**
     * @param feedbackDate the feedbackDate to set
     */
    public void setFeedbackDate(String feedbackDate) {
        this.feedbackDate = feedbackDate;
    }

    /**
     * @return the requestType
     */
    public String getRequestType() {
        return requestType;
    }

    /**
     * @param requestType the requestType to set
     */
    public void setRequestType(String requestType) {
        this.requestType = requestType;
    }

    /**
     * @return the situationCategoryID
     */
    public int getSituationCategoryID() {
        return situationCategoryID;
    }

    /**
     * @param situationCategoryID the situationCategoryID to set
     */
    public void setSituationCategoryID(int situationCategoryID) {
        this.situationCategoryID = situationCategoryID;
    }

    /**
     * @return the situationCategoryDescription
     */
    public String getSituationCategoryDescription() {
        return situationCategoryDescription;
    }

    /**
     * @param situationCategoryDescription the situationCategoryDescription to set
     */
    public void setSituationCategoryDescription(String situationCategoryDescription) {
        this.situationCategoryDescription = situationCategoryDescription;
    }
    
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/HLCReasoner/ReasonerFactory.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.HLCReasoner;

public class ReasonerFactory {
	enum Reasoning{HLC, LLC};
	
	private AbstractReasoner reasoner;
	
	public AbstractReasoner getReasoner(Reasoning type){
		switch(type){
		case HLC:
			reasoner = new HLCReasoner(null);
			break;
		case LLC:
			break;
		default:
			break;
		}
		
		return null;
	}
	
}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/framework/RecInterpreter/PARecommender/MultiRecContentTesting.java<|end_filename|>
/* Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.scl.framework.RecInterpreter.PARecommender;

import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;

import org.uclab.scl.datamodel.contextMapper.*;

public class MultiRecContentTesting {

  static HashMap<String, String> mapWeatherRec = new HashMap<>();
  static HashMap<String, String> mapLocationRec = new HashMap<>();
  static HashMap<String, String> mapHLCRec = new HashMap<>();
  static HashMap<String, String> mapEmotionRec = new HashMap<>();
  static HashMap<String, String> mapDisableRec = new HashMap<>();
  static HashMap<String, String> mapPreferRec = new HashMap<>();

  @SuppressWarnings("unchecked")
  public static int[] multiRecContextTest(String receivedContext) {
    int[] result = null; 
    try {
      WeatherMapper weatherMapper = new WeatherMapper();
      DisableMapper disableMapper = new DisableMapper();
      EmotionMapper emotionMapper = new EmotionMapper();
      HLCMapper hlcMapper = new HLCMapper();
      LocationMapper locationMapper = new LocationMapper();
      PreferenceMapper preferenceMapper = new PreferenceMapper();

      mapWeatherRec = weatherMapper.weatherMapper();
      mapLocationRec = locationMapper.locationMapper();
      mapHLCRec = hlcMapper.hlcMapper();
      mapEmotionRec = emotionMapper.emotionMapper();
      mapDisableRec = disableMapper.disableMapper();
      mapPreferRec = preferenceMapper.preferMapper();

      String context[] = receivedContext.split(",");
      char[] loc = mapLocationRec.get(context[0]).replaceAll(",", "").toCharArray();
      char[] hlc = mapHLCRec.get(context[1]).replaceAll(",", "").toCharArray();
      char[] weather = mapWeatherRec.get(context[2]).replaceAll(",", "").toCharArray();
      char[] emotion = mapEmotionRec.get(context[3]).replaceAll(",", "").toCharArray();
      char[] disable = mapDisableRec.get(context[4]).replaceAll(",", "").toCharArray();

      result = new int[loc.length];
      // CONTEXTUAL MATRIX
      for (int i = 0; i < loc.length; i++)
        if ((loc[i] == '1') && (hlc[i] == '1') && (weather[i] == '1') && (emotion[i] == '1') && (disable[i] == '1')) { 
          result[i] = 1;
        } else {
          result[i] = 0;
        }      
    }
    catch (FileNotFoundException e) {
      e.printStackTrace();      
    }    
    return (result);
  }
}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/datamodel/PhysiologicalFactors.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.datamodel;

import java.io.Serializable;

import org.codehaus.jackson.annotate.JsonIgnoreProperties;

/**
 * @version MM v2.5
 * @author Afzal
 *
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class PhysiologicalFactors implements Serializable{

  private long id;
  private String requestType;
  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public String getRequestType() {
    return requestType;
  }

  public void setRequestType(String requestType) {
    this.requestType = requestType;
  }

  private float weight;

  private float idealWeight;

  private float height;

  private long userId;

  private float targetWeight;

  private int physiologicalFactorId;

  private String date;

  private String weightStatus;

  private float bmi = 0;

  public PhysiologicalFactors() {
    this.weightStatus = "None";
    weightStatus = CalculateWeightStatus();
  }

  private String CalculateWeightStatus() {
    String weightStatus1 = "";
    // this.setBmi(this.getWeight()/(float)Math.pow((this.getHeight() * 0.01),
    // 2));
    this.bmi = this.getWeight()
        / (float) Math.pow((this.getHeight() * 0.01), 2);
    // setBmi((float) Math.round(getBmi() * 100) / 100);
    this.setBmi((float) Math.round(this.bmi));

    if (getBmi() < 18.5) {
      weightStatus1 = "Overweight";
    } else if (getBmi() >= 18.5 && getBmi() <= 24.9) {
      weightStatus1 = "Normal";
    } else if (getBmi() >= 25.0 && getBmi() <= 29.9) {
      weightStatus1 = "Overweight";
    } else {
      weightStatus1 = "Obese";
    }

    return weightStatus1;
  }

  public String getWeightStatus() {
    return this.weightStatus;
  }

  public float getIdealWeight() {
    return idealWeight;
  }

  public void setIdealWeight(float idealWeight) {
    this.idealWeight = idealWeight;
  }

  public long getUserId() {
    return userId;
  }

  public void setUserId(long userId) {
    this.userId = userId;
  }

  public float getTargetWeight() {
    return targetWeight;
  }

  public void setTargetWeight(float targetWeight) {
    this.targetWeight = targetWeight;
  }

  public int getPhysiologicalFactorId() {
    return physiologicalFactorId;
  }

  public void setPhysiologicalFactorId(int physiologicalFactorId) {
    this.physiologicalFactorId = physiologicalFactorId;
  }

  public String getDate() {
    return date;
  }

  public void setDate(String date) {
    this.date = date;
  }

  @Override
  public String toString() {
    return "ClassPojo [weight = " + getWeight() + ", idealWeight = "
        + idealWeight + ", height = " + getHeight() + ", userId = " + userId
        + ", targetWeight = " + targetWeight + ", physiologicalFactorId = "
        + physiologicalFactorId + ", date = " + date + "]";
  }

  /**
   * @param weightStatus
   *          the weightStatus to set
   */
  public void setWeightStatus(String weightStatus) {
    this.weightStatus = weightStatus;
  }

  /**
   * @return the bmi
   */
  public float getBmi() {
    return bmi;
  }

  /**
   * @param bmi
   *          the bmi to set
   */
  public void setBmi(float bmi) {
    this.bmi = bmi;
  }

  /**
   * @return the weight
   */
  public float getWeight() {
    return weight;
  }

  /**
   * @param weight
   *          the weight to set
   */
  public void setWeight(float weight) {
    this.weight = weight;
  }

  /**
   * @return the height
   */
  public float getHeight() {
    return height;
  }

  /**
   * @param height
   *          the height to set
   */
  public void setHeight(float height) {
    this.height = height;
  }

}

<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/AR/iar/AR_FeatureExtractor.java<|end_filename|>
/**
Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */

package org.uclab.mm.icl.llc.AR.iar;

import org.apache.commons.math3.stat.descriptive.moment.Kurtosis;

/**
 * This class is for extracting features.
 * It contains feature calculation functions and function to return feature list.
 * 
 * @author <NAME>
 *
 */
public class AR_FeatureExtractor {

	/**
	 * get Zero Crossing
	 * @param signal double array(eg:accelerometer data)
	 * @return number of zero crossing
	 */
	static double getCrossing(double[] signal) {
		double crossing = 0;
		double mean = 0;
		mean = getAverage(signal);
		for (int i = 0; i < signal.length - 1; i++) {
			if ((signal[i] - mean) * (signal[i + 1] - mean) < 0)
				crossing += 1;
		}
		crossing /= signal.length;

		return crossing;
	}

	/**
	 * get Standard deviation
	 * @param signal double array(eg:accelerometer data)
	 * @return Standard deviation
	 */
	static double getStandardDeviation(double[] signal) {
		double variance = getVariance(signal);
		return Math.sqrt(variance);
	}

	/**
	 * get Max value
	 * @param signal double array(eg:accelerometer data)
	 * @return max value
	 */
	static double getMax(double[] signal) {
		double max = -9999;
		for (int j = 0; j < signal.length; j++) {
			if (signal[j] > max) {
				max = signal[j];
			}
		}
		return max;
	}

	/**
	 * get minimum value
	 * @param signal double array(eg:accelerometer data)
	 * @return minimum value
	 */
	static double getMin(double[] signal) {
		double min = 9999;
		for (int j = 0; j < signal.length; j++) {
			if (signal[j] < min) {
				min = signal[j];
			}
		}
		return min;
	}

	/**
	 * get sum of array data
	 * @param values double array(eg:accelerometer data)
	 * @return sum of array data
	 */
	public static double getSum(double[] values) {
		double sumData = 0;

		for (int i = 0; i < values.length; i++) {
			sumData += values[i];
		}
		return sumData;
	}

	/**
	 * get average of array
	 * @param values double array(eg:accelerometer data)
	 * @return average
	 */
	public static double getAverage(double[] values) {
		double avgData = 0;

		avgData = getSum(values) / values.length;

		return avgData;
	}

	/**
	 * get variance of array
	 * @param values double array(eg:accelerometer data)
	 * @return variance
	 */
	public static double getVariance(double[] values) {
		double varData = 0;
		double sum_varData = 0;
		double avg = getAverage(values);

		for (int i = 0; i < values.length; i++) {
			sum_varData += Math.pow((values[i] - avg), 2);
		}
		varData = sum_varData / values.length;

		return varData;
	}

	/**
	 * get covariance of two arrays
	 * @param values_A double array(eg:accelerometer data)
	 * @param values_B double array(eg:accelerometer data)
	 * @return covariance of two arrays
	 */
	public static double getCovariance(double[] values_A, double[] values_B) {
		double a_avg = getAverage(values_A);
		double b_avg = getAverage(values_B);
		double covarData = 0;

		double[] ab_avg = new double[values_A.length];

		for (int i = 0; i < values_A.length; i++) {
			ab_avg[i] = (values_A[i] - a_avg) * (values_B[i] - b_avg);
		}

		covarData = getAverage(ab_avg);

		return covarData;
	}

	/**
	 * get quartile value
	 * @param values double array(eg:accelerometer data)
	 * @return quartile
	 */
	public static double getQuartile(double[] values) {
		double[] result = sort(values);
		int quart = values.length / 4;
		return Math.abs((result[quart] + result[quart + 1]) / 2
				- (result[values.length - quart] + result[values.length - quart + 1]) / 2);
	}

	/**
	 * get mean value of abs
	 * @param double array(eg:accelerometer data)
	 * @return meanabs
	 */
	public static double getMeanAbs(double[] values) {
		double average = getAverage(values);
		double[] list = new double[values.length];
		for (int j = 0; j < values.length; j++) {
			list[j] = Math.abs(values[j] - average);
		}

		return getAverage(list);
	}

	/**
	 * get median value of abs
	 * @param double array(eg:accelerometer data)
	 * @return median value of abs
	 */
	public static double getMedianAbs(double[] values) {
		double median = getMedian(values);
		double list[] = new double[values.length];
		for (int j = 0; j < values.length; j++) {
			list[j] = Math.abs(values[j] - median);
		}
		return getMedian(list);
	}

	
	/**
	 * get median value
	 * @param values double array(eg:accelerometer data)
	 * @return median value
	 */
	public static double getMedian(double[] values) {
		double[] result = sort(values);
		if (result.length % 2 == 1) {
			return result[(result.length / 2) + 1];
		} else {
			double a, b;
			a = result[(result.length / 2) + 1];
			b = result[(result.length / 2)];
			return (a + b) / 2.;
		}
	}

	/**
	 * get range of array
	 * @param value double array(eg:accelerometer data)
	 * @return maximum data - minimum data
	 */
	public static double getRange(double[] value) {
		return getMax(value) - getMin(value);
	}

	/**
	 * get geomean of array
	 * @param value double array(eg:accelerometer data)
	 * @return geomean of array
	 */
	public static double getGeomean(double[] value) {
		double result = 1;
		for (int j = 0; j < value.length; j++) {
			result *= value[j];
		}
		return Math.pow(result, (1 / value.length));
	}

	/**
	 * sort array
	 * @param value double array(eg:accelerometer data)
	 * @return sorted array
	 */
	public static double[] sort(double[] value) {
		double[] result = new double[value.length];
		for (int j = 0; j < value.length; j++) {
			result[j] = value[j];
		}

		for (int j = 0; j < result.length; j++) {
			for (int k = 0; k < result.length - 1; k++) {
				if (result[k] > result[k + 1]) {
					double temp = result[k];
					result[k] = result[k + 1];
					result[k + 1] = result[k];
				}
			}
		}

		return result;
	}

	/**
	 * get harmonic value of array
	 * @param double array(eg:accelerometer data)
	 * @return harmonic value of array
	 */
	public static double getHarmonic(double[] values) {
		double sum = 0.0;

		for (int j = 0; j < values.length; j++) {
			sum += 1.0 / values[j];
		}

		return sum;
	}

	/**
	 * 
	 * @param values double array to get kurtosis
	 * @return kurtosis of the input array
	 */
	public static double getKurtosis(double[] values) {
		Kurtosis ks = new Kurtosis();
		return ks.evaluate(values);
	}

	public static double getTrimMean(double[] values) {
		double sum = 0.0;
		for (int j = 1; j < values.length - 1; j++) {
			sum += values[j];
		}
		return sum / (values.length - 2);
	}

	/**
	 * 
	 * @param 
	 * @param 
	 * @param 
	 * @param 
	 * @param 
	 * @param 
	 * @param 
	 * @param 
	 * @param 
	 * @param 
	 * @param 
	 * @param 
	 * @return 
	 */
	
	/**
	 * get integrated model's featured data(with 50 features)
	 * @param SaccX Smartphone's accelerometer dataX
	 * @param SaccY Smartphone's accelerometer dataY
	 * @param SaccZ Smartphone's accelerometer dataZ
	 * @param WaccX Smart watch's accelerometer dataX
	 * @param WaccY Smart watch's accelerometer dataY
	 * @param WaccZ Smart watch's accelerometer dataZ
	 * @param SgyroX Smartphone's gyroscope dataX
	 * @param SgyroY Smartphone's gyroscope dataY
	 * @param SgyroZ Smartphone's gyroscope dataZ
	 * @param WgyroX Smart watch's gyroscope dataX
	 * @param WgyroY Smart watch's gyroscope dataY
	 * @param WgyroZ Smart watch's gyroscope dataZ
	 * @return feature list.
	 */
	public static double[] MiningMindsV2_151005_integrated50(double[] SaccX, double[] SaccY, double[] SaccZ,
			double[] WaccX, double[] WaccY, double[] WaccZ, double[] SgyroX, double[] SgyroY, double[] SgyroZ,
			double[] WgyroX, double[] WgyroY, double[] WgyroZ) {

		double[] feature = new double[49];

		feature[0] = getRange(WgyroZ);
		feature[1] = getMax(SaccY);
		feature[2] = getRange(SaccZ);
		feature[3] = getStandardDeviation(SaccY);
		feature[4] = getStandardDeviation(SaccZ);
		feature[5] = getQuartile(SaccY);
		feature[6] = getQuartile(SaccZ);
		feature[7] = getMeanAbs(SaccY);
		feature[8] = getMeanAbs(SaccZ);
		feature[9] = getMedianAbs(SaccY);
		feature[10] = getMedianAbs(SaccZ);
		feature[11] = getStandardDeviation(SgyroX);
		feature[12] = getMeanAbs(SgyroX);
		feature[13] = getMax(WaccX);
		feature[14] = getStandardDeviation(WgyroZ);
		feature[15] = getMeanAbs(WgyroZ);
		feature[16] = getAverage(SaccZ);
		feature[17] = getMedian(SaccZ);
		feature[18] = getRange(SaccY);
		feature[19] = getTrimMean(SaccZ);
		feature[20] = getStandardDeviation(SaccX);
		feature[21] = getMeanAbs(SaccX);
		feature[22] = getMedianAbs(SaccX);
		feature[23] = getMin(SgyroX);
		feature[24] = getMin(SgyroY);
		feature[25] = getRange(SgyroX);
		feature[26] = getRange(SgyroY);
		feature[27] = getGeomean(SgyroX);
		feature[28] = getQuartile(SgyroX);
		feature[29] = getMedianAbs(SgyroX);
		feature[30] = getMedianAbs(SgyroZ);
		feature[31] = getStandardDeviation(WaccX);
		feature[32] = getQuartile(WaccX);
		feature[33] = getMeanAbs(WaccX);
		feature[34] = getMedianAbs(WaccX);
		feature[35] = getMin(WgyroZ);
		feature[36] = getStandardDeviation(WgyroY);
		feature[37] = getGeomean(WgyroY);
		feature[38] = getGeomean(WgyroZ);
		feature[39] = getQuartile(WgyroY);
		feature[40] = getQuartile(WgyroZ);
		feature[41] = getMeanAbs(WgyroY);
		feature[42] = getMedianAbs(WgyroY);
		feature[43] = getMedianAbs(WgyroZ);
		feature[44] = getMin(SaccZ);
		feature[45] = getRange(SaccX);
		feature[46] = getVariance(SaccY);
		feature[47] = getGeomean(SaccY);
		feature[48] = getGeomean(SaccZ);

		return feature;

	}
		
	/**
	 * get each device's featured data(basic feature lists)
	 * @param accX Device's accelerometer dataX
	 * @param accY Device's accelerometer dataY
	 * @param accZ Device's accelerometer dataZ
	 * @param gyroX Device's gyroscope dataX
	 * @param gyroY Device's gyroscope dataY
	 * @param gyroZ Device's gyroscope dataZ
	 * @return
	 */
	public static double[] MiningMindsV2_150923_basic42(double[] accX, double[] accY, double[] accZ, double[] gyroX,
			double[] gyroY, double[] gyroZ) {
		double[] feature = new double[42];

		feature[0] = getAverage(accX);
		feature[1] = getAverage(accY);
		feature[2] = getAverage(accZ);
		feature[3] = getMax(accX);
		feature[4] = getMax(accY);
		feature[5] = getMax(accZ);
		feature[6] = getMin(accX);
		feature[7] = getMin(accY);
		feature[8] = getMin(accZ);
		feature[9] = getStandardDeviation(accX);
		feature[10] = getStandardDeviation(accY);
		feature[11] = getStandardDeviation(accZ);
		feature[12] = getCrossing(accX);
		feature[13] = getCrossing(accY);
		feature[14] = getCrossing(accZ);
		feature[15] = getQuartile(accX);
		feature[16] = getQuartile(accY);
		feature[17] = getQuartile(accZ);
		feature[18] = getMeanAbs(accX);
		feature[19] = getMeanAbs(accY);
		feature[20] = getMeanAbs(accZ);

		feature[21] = getAverage(gyroX);
		feature[22] = getAverage(gyroY);
		feature[23] = getAverage(gyroZ);
		feature[24] = getMax(gyroX);
		feature[25] = getMax(gyroY);
		feature[26] = getMax(gyroZ);
		feature[27] = getMin(gyroX);
		feature[28] = getMin(gyroY);
		feature[29] = getMin(gyroZ);
		feature[30] = getStandardDeviation(gyroX);
		feature[31] = getStandardDeviation(gyroY);
		feature[32] = getStandardDeviation(gyroZ);
		feature[33] = getCrossing(gyroX);
		feature[34] = getCrossing(gyroY);
		feature[35] = getCrossing(gyroZ);
		feature[36] = getQuartile(gyroX);
		feature[37] = getQuartile(gyroY);
		feature[38] = getQuartile(gyroZ);
		feature[39] = getMeanAbs(gyroX);
		feature[40] = getMeanAbs(gyroY);
		feature[41] = getMeanAbs(gyroZ);

		return feature;

	}
	
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/MMDataCurationRestfulService/src/main/java/org/uclab/mm/rs/datacuration/DataCurationResource.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.rs.datacuration;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.AbstractDataBridge;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.DatabaseStorage;
import org.uclab.mm.datamodel.dc.PhysiologicalFactors;
import org.uclab.mm.datamodel.dc.UserDisabilities;
import org.uclab.mm.datamodel.dc.UserFacilities;
import org.uclab.mm.datamodel.dc.UserRiskFactors;
import org.uclab.mm.datamodel.dc.UserSchedule;
import org.uclab.mm.datamodel.dc.Users;
import org.uclab.mm.datamodel.dc.dataadapter.PhysiologicalFactorsAdapter;
import org.uclab.mm.datamodel.dc.dataadapter.UserDataAdapter;
import org.uclab.mm.datamodel.dc.dataadapter.UserDisabilitiesAdapter;
import org.uclab.mm.datamodel.dc.dataadapter.UserFacilitiesAdapter;
import org.uclab.mm.datamodel.dc.dataadapter.UserRiskFactorsAdapter;
import org.uclab.mm.datamodel.dc.dataadapter.UserScheduleAdapter;
import org.uclab.mm.datamodel.sl.ActiveSession;
import org.uclab.mm.datamodel.sl.HashClass;
import org.uclab.mm.datamodel.sl.dataadapter.ActiveSessionAdapter;

import com.google.gson.Gson;



/**
 * Facade for the Restful Web service to handle the data curation functions 
 *
 * @author <NAME>
 */
@Path("DataCuration")
public class DataCurationResource {

    @Context
    private UriInfo context;

    /**
     * Creates a new instance of DataCurationResource
     */
    public DataCurationResource() {
    }
    
    private static final Logger logger = LoggerFactory.getLogger(DataCurationResource.class);
    
    /**
     * This function is using to Register user 
     * @param objOuterUser
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("RegisterUser")
    public List<String> RegisterUser(Users objOuterUser) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            objOuterUser.setRequestType("UserValidate");
            DataAccessInterface objDAInterface = new UserDataAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveUser(objOuterUser);
            logger.info("User saved successfully, User Details="+objOuterUser);
        }
        catch(Exception ex)
        {
        	logger.info("Error in saving user, User Details=");
        	response.add("Error in saving user");
        }
        return response;
    }
    
    /**
     * This function is using to update user 
     * @param objOuterUser
     * @return a list of object string with "Error", "No Error" and updated ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UpdateUser")
    public List<String> UpdateUser(Users objOuterUser) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserDataAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.UpdateUser(objOuterUser);
            logger.info("User udpated successfully, User Details="+objOuterUser);
        }
        catch(Exception ex)
        { 
        	logger.info("Error in updating user, User Details=");
        	response.add("Error in saving user");
        }
        return response;
    }
    

    /**
     * This function is using to get user by ID 
     * @param UserID
     * @return a list of object Users with "Error", "No Error" and new added ID
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("User/{UserID}")
    public List<Users> GetUser(@PathParam ("UserID") String UserID) {
        Users objOuterUser = new Users();
        List<Users> objListUsers = new  ArrayList<Users>();
        try
        {
            objOuterUser.setUserID(Long.parseLong(UserID));
            objOuterUser.setRequestType("UserData");

            DataAccessInterface objDAInterface = new UserDataAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUsers = objADBridge.RetriveUser(objOuterUser);
            logger.info("Get user successfully, User Details="+objOuterUser);
        }
        catch(Exception ex)
        {
        	logger.info("Error in getting user");
        }
        return objListUsers;
    }
    
    /**
     * This function is  using to retrieves Users List by ExpertID 
     * @param UserID
     * @return an instance of list of Users
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UserListByExpertID/{UserID}")
    public List<Users> GetUserListByExpertID(@PathParam ("UserID") String UserID) {
        Users objOuterUser = new Users();
        List<Users> objListUsers = new  ArrayList<Users>();
        try
        {
            objOuterUser.setUserID(Long.parseLong(UserID));
            objOuterUser.setRequestType("UsersListByExpert");

            DataAccessInterface objDAInterface = new UserDataAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUsers = objADBridge.RetriveUser(objOuterUser);
            logger.info("Get user successfully by expert id, User Details="+objOuterUser);
        }
        catch(Exception ex)
        {
        	logger.info("Error in getting user");
        }
        return objListUsers;
    }
    
    /**
     * Authenticate user by user login and password
     * @param objOuterUser
     * @return an instance of list of Users
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("ValidateUser")
    public List<Users> ValidateUser(Users objOuterUser) {
        
        List<Users> objListUsers = new  ArrayList<Users>();
        try
        {
            objOuterUser.setRequestType("UserValidate");
            DataAccessInterface objDAInterface = new UserDataAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUsers = objADBridge.RetriveUser(objOuterUser);
            logger.info("User authenticated successfully, User Details="+objOuterUser);
        }
        catch(Exception ex)
        {
        	logger.info("Error in getting user");
        }
        return objListUsers;
    }
    
    /**
     * Check the user is already exist by email address
     * @param objOuterUser
     * @return an instance of list of Users
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("IsUserExist")
    public List<Users> IsUserExist(Users objOuterUser) {
        
        List<Users> objListUsers = new  ArrayList<Users>();
        try
        {
            objOuterUser.setRequestType("IsUserExist");
            DataAccessInterface objDAInterface = new UserDataAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUsers = objADBridge.RetriveUser(objOuterUser);
            logger.info("User checked successfully, User Details=");
        }
        catch(Exception ex)
        {
        	logger.info("Error in getting user");
        }
        return objListUsers;
    }
    
    /**
     * This function is adding user risk factors
     * @param objOuterUserRiskFactors
     * @return an instance of list of string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddUserRiskFactors")
    
    public List<String> AddUserRiskFactors(UserRiskFactors objOuterUserRiskFactors) {
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserRiskFactorsAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveUserRiskFactors(objOuterUserRiskFactors);
            logger.info("Risk factor saved successfully, User Details=" + objOuterUserRiskFactors);
        }
        catch(Exception ex)
        {
        	logger.info("Error in saving risk factor");
        	response.add("Error in saving risk factor");
        }
        return response;
    }
    
    /**
     * This function is retrieving the Risk factors by UserID 
     * @param UserID
     * @return an instance of list of UserRiskFactors
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("RiskFactors/{UserID}")
    public List<UserRiskFactors> GetRiskFactors(@PathParam ("UserID") String UserID) {
        UserRiskFactors objOuterUserRiskFactors = new UserRiskFactors();
        List<UserRiskFactors> objListUserRiskFactors = new  ArrayList<UserRiskFactors>();
        try
        {
            objOuterUserRiskFactors.setUserId(Long.parseLong(UserID));

            DataAccessInterface objDAInterface = new UserRiskFactorsAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserRiskFactors = objADBridge.RetriveUserRiskFactors(objOuterUserRiskFactors);
            logger.info("Risk factor loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in getting risk factor");
        }
        return objListUserRiskFactors;
    }
    
    /**
     * This function is using to Update user risk factors
     * @param objOuterUserRiskFactors
     * @return an instance of list of string with "Error", "No Error" and updated ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UpdateUserRiskFactors")
    public List<String> UpdateUserRiskFactors(UserRiskFactors objOuterUserRiskFactors) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserRiskFactorsAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.UpdateUserRiskFactors(objOuterUserRiskFactors);
            logger.info("Risk factor saved successfully, User Details="+objOuterUserRiskFactors);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating risk factor");
        	response.add("Error in updating risk factor");
        }
        return response;
    }
    
    /**
     * This function is used to Add user Physiological factors
     * @param objOuterPhysiologicalFactors
     * @return an instance of list of string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddPhysiologicalFactors")
    public List<String> AddPhysiologicalFactors(PhysiologicalFactors objOuterPhysiologicalFactors) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new PhysiologicalFactorsAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SavePhysiologicalFactors(objOuterPhysiologicalFactors);
            logger.info("Physiological factor saved successfully, User Details="+objOuterPhysiologicalFactors);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Physiological factors");
        	response.add("Error in adding Physiological factors");
        }
        return response;
    }
    
    /**
     * This function is implemented to Retrieve Physiological Factors by UserID 
     * @param UserID
     * @return an instance of list of PhysiologicalFactors
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("PhysiologicalFactors/{UserID}")
    public List<PhysiologicalFactors> GetPhysiologicalFactors(@PathParam ("UserID") String UserID) {
        PhysiologicalFactors objOuterPhysiologicalFactors = new PhysiologicalFactors();
        List<PhysiologicalFactors> objListPhysiologicalFactors = new  ArrayList<PhysiologicalFactors>();
        try
        {
            objOuterPhysiologicalFactors.setUserId(Long.parseLong(UserID));

            DataAccessInterface objDAInterface = new PhysiologicalFactorsAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListPhysiologicalFactors = objADBridge.RetrivePhysiologicalFactors(objOuterPhysiologicalFactors);
            logger.info("Physiological is loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in Loading Physiological factors");
        }
        return objListPhysiologicalFactors;
    }
    
    /**
     * This function is using to Update user Physiological factors
     * @param objOuterPhysiologicalFactors
     * @return list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UpdatePhysiologicalFactors")
    public List<String> UpdatePhysiologicalFactors(PhysiologicalFactors objOuterPhysiologicalFactors) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new PhysiologicalFactorsAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.UpdatePhysiologicalFactors(objOuterPhysiologicalFactors);
            logger.info("Physiological factor updated successfully, User Details="+objOuterPhysiologicalFactors);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updated Physiological factors");
        	response.add("Error in updated Physiological factors");
        }
        return response;
    }
    
    /**
     *  This function is using to Add user Facilities
     * @param objOuterUserFacilities
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddUserFacilities")
    public List<String> AddUserFacilities(UserFacilities objOuterUserFacilities) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserFacilitiesAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveUserFacilities(objOuterUserFacilities);
            logger.info("user Facilities saved successfully, User Details="+objOuterUserFacilities);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding user Facilities");
        	response.add("Error in adding user Facilities");
        }
        return response;
    }
    
    /**
     * This function is using to Retrieves users Facilities by UserID 
     * @param UserID
     * @return an instance of list of UserFacilities
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UserFacilities/{UserID}")
    public List<UserFacilities> GetUserFacilities(@PathParam ("UserID") String UserID) {
        UserFacilities objOuterUserFacilities = new UserFacilities();
        List<UserFacilities> objListUserFacilities = new  ArrayList<UserFacilities>();
        try
        {
            objOuterUserFacilities.setUserId(Long.parseLong(UserID));

            DataAccessInterface objDAInterface = new UserFacilitiesAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserFacilities = objADBridge.RetriveUserFacilities(objOuterUserFacilities);
            logger.info("user Facilities loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading user Facilities");
        }
        return objListUserFacilities;
    }
    
    /**
     * This function is using to Update user Facilities
     * @param objOuterUserFacilities
     * @return a list of object string with "Error", "No Error" and updated ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UpdateUserFacilities")
    public List<String> UpdateUserFacilities(UserFacilities objOuterUserFacilities) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserFacilitiesAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.UpdateUserFacilities(objOuterUserFacilities);
            logger.info("user Facilities saved successfully, User Details="+objOuterUserFacilities);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updated user Facilities");
        	response.add("Error in updated user Facilities");
        }
        return response;
    }
    
    /**
     * This function is using to Authenticate user by user login and password
     * @param objUsers
     * @return an instance of list of Users
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AuthenticateUser")
    public List<String> AuthenticateUser(Users objUsers) {
        List<String> objResponse = new ArrayList<String>();
        List<Users> objListUsers = new  ArrayList<Users>();
        try
        {
           objUsers.setRequestType("UserValidate");
            DataAccessInterface objDAInterface = new UserDataAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUsers = objADBridge.RetriveUser(objUsers);
            if(objListUsers.size() >= 1)
            {
                ActiveSession objActiveSession = new ActiveSession();
                HashClass objHashClass = new HashClass(objListUsers.get(0).getUserID().toString());
                String strMD5Result = objHashClass.getHashMD5();
                objActiveSession.setUserID(objListUsers.get(0).getUserID());
                objActiveSession.setHashCode(strMD5Result);
                objActiveSession.setStatus(1);

                DataAccessInterface objDAInterfaceSession = new ActiveSessionAdapter();
                objADBridge.setDataAdapter(objDAInterfaceSession);
                objResponse = objADBridge.SaveActiveSession(objActiveSession);
                objResponse.add(objListUsers.get(0).getUserID().toString());
                objResponse.add("ValidUser");
                objResponse.add(strMD5Result);

            }
            else
            {
                objResponse.add("InvalidUser");
            }
            logger.info("User authenticated successfully, User Details="+objUsers);
        }
        catch(Exception ex)
        {
        	logger.info("Error in authenticating user");
        	objResponse.add("Error in authenticating user");
        }
        return objResponse;
    }
    
    /**
     * This function is using to Add User Disabilities
     * @param objOuterUserDisabilities
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddUserDisabilities")
    public List<String> AddUserDisabilities(UserDisabilities objOuterUserDisabilities) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserDisabilitiesAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveUserDisabilities(objOuterUserDisabilities);
            logger.info("User Disabilities saved successfully, User Details="+objOuterUserDisabilities);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding User Disabilities");
        	response.add("Error in adding User Disabilities");
        }
        return response;
    }
    
    /**
     * This function is using to Update User Disabilities
     * @param objOuterUserDisabilities
     * @return a list of object string with "Error", "No Error" and updated ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UpdateUserDisabilities")
    public List<String> UpdateUserDisabilities(UserDisabilities objOuterUserDisabilities) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserDisabilitiesAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.UpdateUserDisabilities(objOuterUserDisabilities);
            logger.info("User Disabilities updated successfully, User Details="+objOuterUserDisabilities);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updated User Disabilities");
        	response.add("Error in updated User Disabilities");
        }
        return response;
    }
    
    /**
     * This function is using to Retrieves User Disabilities by UserID 
     * @param UserID
     * @return an instance of list of UserDisabilities
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UserDisabilities/{UserID}")
    public List<UserDisabilities> GetUserDisabilities(@PathParam ("UserID") String UserID) {
        UserDisabilities objOuterUserDisabilities = new UserDisabilities();
        List<UserDisabilities> objListUserDisabilities = new  ArrayList<UserDisabilities>();
        try
        {
            objOuterUserDisabilities.setUserID(Long.parseLong(UserID));

            DataAccessInterface objDAInterface = new UserDisabilitiesAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserDisabilities = objADBridge.RetriveUserDisabilities(objOuterUserDisabilities);
            logger.info("User Disabilities loaded successfully, User Details=");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading User Disabilities");
        }
        return objListUserDisabilities;
    }
    
    /**
     * This function is using to Add User Schedule
     * @param objOuterUserSchedule
     * @return  a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddUserSchedule")
    public List<String> AddUserSchedule(UserSchedule objOuterUserSchedule) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserScheduleAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveUserSchedule(objOuterUserSchedule);
            logger.info(" User Schedule saved successfully, User Details="+objOuterUserSchedule);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding User Schedule");
        	response.add("Error in adding User Schedule");
        }
       return response;
    }

    /**
     * This function is using to Update User Schedule
     * @param objOuterUserSchedule
     * @return a list of object string with "Error", "No Error" and updated ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UpdateUserSchedule")
    public List<String> UpdateUserSchedule(UserSchedule objOuterUserSchedule) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserScheduleAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.UpdateUserSchedule(objOuterUserSchedule);
            logger.info("User Schedule saved successfully, User Details="+objOuterUserSchedule);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updated User Schedule");
        	response.add("Error in updated User Schedule");
        }
        return response;
    }
    
    /**
     * This function is using to  Retrieves User Schedule by user id, start time and end time
     * @param objOuterUserSchedule
     * @return an instance of list of UserSchedule
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("GetUserScheduleByIDandTime")
    public List<UserSchedule> GetUserScheduleByIDandTime(UserSchedule objOuterUserSchedule) {
        
        List<UserSchedule> objListUserSchedule = new ArrayList<UserSchedule>();
        try
        {
            DataAccessInterface objDAInterface = new UserScheduleAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserSchedule = objADBridge.RetriveUserSchedule(objOuterUserSchedule);
            logger.info("User Schedule loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading User Schedule");
        }
        return objListUserSchedule;
    }
    
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/dc/UserDisabilities.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.dc;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author <NAME>
 */
@Entity
public class UserDisabilities implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    
    private  Long userDisabilityID;
    private  Long userID;
    private  int disabilityID;
    private  int  statusID;
    
    private String disabilityDescription;
    private String statusDescription;
    
    
    

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof UserDisabilities)) {
            return false;
        }
        UserDisabilities other = (UserDisabilities) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.dc.UserDisabilities[ id=" + id + " ]";
    }

    /**
     * @return the userDisabilityID
     */
    public Long getUserDisabilityID() {
        return userDisabilityID;
    }

    /**
     * @param userDisabilityID the userDisabilityID to set
     */
    public void setUserDisabilityID(Long userDisabilityID) {
        this.userDisabilityID = userDisabilityID;
    }

    /**
     * @return the userID
     */
    public Long getUserID() {
        return userID;
    }

    /**
     * @param userID the userID to set
     */
    public void setUserID(Long userID) {
        this.userID = userID;
    }

    /**
     * @return the disabilityID
     */
    public int getDisabilityID() {
        return disabilityID;
    }

    /**
     * @param disabilityID the disabilityID to set
     */
    public void setDisabilityID(int disabilityID) {
        this.disabilityID = disabilityID;
    }

    /**
     * @return the statusID
     */
    public int getStatusID() {
        return statusID;
    }

    /**
     * @param statusID the statusID to set
     */
    public void setStatusID(int statusID) {
        this.statusID = statusID;
    }

    /**
     * @return the disabilityDescription
     */
    public String getDisabilityDescription() {
        return disabilityDescription;
    }

    /**
     * @param disabilityDescription the disabilityDescription to set
     */
    public void setDisabilityDescription(String disabilityDescription) {
        this.disabilityDescription = disabilityDescription;
    }

    /**
     * @return the statusDescription
     */
    public String getStatusDescription() {
        return statusDescription;
    }

    /**
     * @param statusDescription the statusDescription to set
     */
    public void setStatusDescription(String statusDescription) {
        this.statusDescription = statusDescription;
    }
    
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/MachineLearningTools/TimeDomainFeatureExtraction.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Bang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.MachineLearningTools;

import java.util.Vector;

import javax.sound.sampled.UnsupportedAudioFileException;

import mm.icl.llc.MachineLearningTools.FeatureExtraction;


/**
 * This Class extract time-domain features based on seconds
 * 
 * @author <NAME>
 *
 */
public class TimeDomainFeatureExtraction extends FeatureExtraction {
	
	/**
	 * Extract Time Domain Feature based on MFCC Filterbank (unit of second)
	 * 
	 * @param mfcc_matrix
	 * @param sec
	 * @return double[][]
	 * @throws UnsupportedAudioFileException
	 */

	public double[][] getTimeDomainMFCC(double[][] mfcc_matrix, int sec)
			throws UnsupportedAudioFileException {

		double[][] bind_mfcc_matrix = new double[sec][(mfcc_matrix[0].length - 1) * 2];
		int size = mfcc_matrix.length / sec;
		double[] sum = new double[mfcc_matrix[0].length];

		double diff = 0;
		double temp_sum = 0;
		double mean = 0;
		int cnt = 0;
		double result = 0;
		for (int i = 0; i < mfcc_matrix.length; i++) {
			for (int j = 0; j < mfcc_matrix[0].length - 1; j++) {
				sum[j] = sum[j] + mfcc_matrix[i][j + 1];

				if ((i + 1) % size == 0) {
					mean = sum[j] / (double) size;
					for (int k = 0; k < i; k++) {
						diff = mfcc_matrix[k][j + 1] - mean;
						temp_sum += diff * diff;
					}
					result = Math.sqrt(temp_sum / (double) size);
					bind_mfcc_matrix[cnt][j] = mean;
					bind_mfcc_matrix[cnt][j + mfcc_matrix[i].length - 1] = result;
					sum[j] = 0;
					temp_sum = 0;
				}

			}

			if ((i + 1) % size == 0) {

				cnt++;
			}

		}

		return bind_mfcc_matrix;
	}
	public double[] getTimeDomainFeatures(double[][] data){
		double[][] reverseData = reverse2ArraysData(data);
		StatisticalFeatureExtraction sfe = new StatisticalFeatureExtraction();
		double[] mfccMeans = new double[data[0].length-1];
		double[] mfccStdDev = new double[data[0].length-1];
		double[] mfccMax = new double[data[0].length-1];
		double[] mfccMin = new double[data[0].length-1];
		//double[] mfccMedian = new double[data[0].length-1];
		double[] featurevt = new double[mfccMeans.length*4];
	
		for(int i =0; i< reverseData.length-1; i++){
			mfccMeans[i] = sfe.getMean(reverseData[i+1]);
			mfccStdDev[i] = sfe.getStdDev(reverseData[i+1]);
			mfccMax[i] = sfe.getMax(reverseData[i+1]);
			mfccMin[i] = sfe.getMin(reverseData[i+1]);
			//mfccMedian[i] = sfe.getMedian(reverseData[i+1]);
			featurevt[i] = mfccMeans[i];
			featurevt[mfccMeans.length + i] = mfccStdDev[i];
			featurevt[mfccMeans.length*2 + i] = mfccMax[i];
			featurevt[mfccMeans.length*3 + i] = mfccMin[i];	
			//featurevt[mfccMeans.length*4 + i] = mfccMedian[i];		
		}
		
		
		return featurevt;
	}
	public double[][] reverse2ArraysData(double[][] data){
		double[][] result = new double[data[0].length][data.length];
		for(int i =0; i<data.length; i++){
			for(int j=0; j<data[i].length; j++){
				result[j][i] = data[i][j];
			}
		}
		return result;
	}

	/**
	 * Convert Single Array
	 * 
	 * @param data
	 * @return double[][]
	 */

	public double[] getSigleArray(double[][] data) {
		double[] result = new double[data.length * data[0].length];
		int cnt = 0;
		for (int i = 0; i < data.length; i++) {
			for (int j = 0; j < data[i].length; j++) {
				result[cnt] = data[i][j];
				cnt++;
			}
		}
		return result;
	}

	/**
	 * No Define
	 */
	@Override
	public Object extractFeature(Object input) {
		// TODO Auto-generated method stub
		return null;
	}
	public double[] convertVector(Vector<double[]> input){
		int size =0;
		for(int i=0; i<input.size(); i++){
			for(int j=0;j<input.get(i).length; j++){
				size++;
			}
		}
		
		double[] result = new double[size];
		int cnt =0;
		for(int i =0; i<input.size(); i++){
			for(int j=0; j<input.get(i).length;j++){
				result[cnt] = input.get(i)[j];
				cnt++;
			}
		}
		return result;
	}
	
	

}


<|start_filename|>knowledge-curation-layer/DDKAT/src/main/java/org/uclab/mm/kcl/ddkat/modellearner/ModelLearner.java<|end_filename|>
/**
 * Copyright [2017] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.mm.kcl.ddkat.modellearner;

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Random;

import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.classifiers.evaluation.NominalPrediction;
import weka.classifiers.trees.BFTree;
import weka.classifiers.trees.FT;
import weka.classifiers.trees.J48;
import weka.classifiers.trees.J48graft;
import weka.classifiers.trees.REPTree;
import weka.classifiers.trees.RandomTree;
import weka.classifiers.trees.SimpleCart;
import weka.core.FastVector;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;

//TODO: Auto-generated Javadoc
/**
* This class learns the data based on algorithm and computes the classification accuracies of original as well as processed data.
*/
public class ModelLearner {
	
	/** The accuracies list. */
	private ArrayList<String> modelAccuracies;
	
	/** The decision attribute. */
	private String decisionAttribute;
	
	/** The decision tree. */
	private String modelString;
	
	/** base directory to store resource data files */
	private static final String BASE_DIR = System.getProperty("user.home") + "/DDKAT/resources/";
	
	/**
	 * Constructor to instantiate a new ModelLearner object.
	 * @param algo the algorithm name
	 * @throws Exception the exception
	 */
 	public ModelLearner(String algo) throws Exception {
    	
    	this.modelAccuracies = new ArrayList<String>();
    	this.decisionAttribute = new String();
    	this.modelString = new String();
    	   	 		
		String[][] accuracyArr = new String[2][4];
			
		String originaldataFile = BASE_DIR + "OriginalDataSet.csv";
		DataSource originaldata_source = new DataSource(originaldataFile);
        Instances original_data = originaldata_source.getDataSet();
        
        String processeddataFile = BASE_DIR + "ProcessedDataSet.arff";
        DataSource processeddata_source = new DataSource(processeddataFile);
        Instances processed_data = processeddata_source.getDataSet();
		
    		       		
		accuracyArr[0] = modelAccuracy(algo, original_data,"Original Data");     
        accuracyArr[1] = modelAccuracy(algo, processed_data,"Processed Data");
        
        this.modelAccuracies.add(accuracyArr[0][3]);
        this.modelAccuracies.add(accuracyArr[1][3]);
		this.decisionAttribute = accuracyArr[0][1];
		this.modelString = accuracyArr[0][2];
		
		System.out.println("\n\n Generation of Classification Model : \n\n"+accuracyArr[0][2]);
	
 	}
 	
 	
 	/**
	 * Method to compute the classification accuracy.
	 *
	 * @param algo the algorithm name
	 * @param data the data instances
	 * @param datanature the dataset nature (i.e. original or processed data)
	 * @throws Exception the exception
	 */   
	protected String[] modelAccuracy(String algo, Instances data, String datanature) throws Exception {
	
		String modelResultSet[] = new String[4];
		String modelStr ="";
		Classifier classifier = null;
		
	    // setting class attribute if the data format does not provide this information  			
	    if (data.classIndex() == -1)
	         data.setClassIndex(data.numAttributes() - 1);
	    
	    String decisionAttribute = data.attribute(data.numAttributes() - 1).toString();
	    String res[] = decisionAttribute.split("\\s+");
	    decisionAttribute = res[1];
	   
	    
	    if(algo.equals("BFTree")){
	    	
	    	// Use BFTree classifiers
            BFTree BFTreeclassifier = new BFTree(); 
            BFTreeclassifier.buildClassifier(data);
            modelStr = BFTreeclassifier.toString();
            classifier = BFTreeclassifier;
            
	    } else if(algo.equals("FT")){
	    	  
		    // Use FT classifiers
            FT FTclassifier = new FT();
            FTclassifier.buildClassifier(data);
            modelStr = FTclassifier.toString();
            classifier = FTclassifier;
	    	
	    } else if(algo.equals("J48")){
	    	  
		    // Use J48 classifiers
            J48 J48classifier = new J48();
            J48classifier.buildClassifier(data);
            modelStr = J48classifier.toString();
            classifier = J48classifier;
            System.out.println("Model String: "+modelStr);

	    } else if(algo.equals("J48graft")){
	    	
	    	// Use J48graft classifiers
            J48graft J48graftclassifier = new J48graft();
            J48graftclassifier.buildClassifier(data);
            modelStr = J48graftclassifier.toString();
            classifier = J48graftclassifier;
	    	
	    } else if(algo.equals("RandomTree")){
	    	
	    	// Use RandomTree classifiers
            RandomTree RandomTreeclassifier = new RandomTree(); 
            RandomTreeclassifier.buildClassifier(data);
            modelStr = RandomTreeclassifier.toString();
            classifier = RandomTreeclassifier;
	    	
	    } else if(algo.equals("REPTree")){
	    	
	    	// Use REPTree classifiers
            REPTree REPTreeclassifier = new REPTree(); 
            REPTreeclassifier.buildClassifier(data);
            modelStr = REPTreeclassifier.toString();
            classifier = REPTreeclassifier;

	    } else if(algo.equals("SimpleCart")){
	    	
	    	// Use SimpleCart classifiers
            SimpleCart SimpleCartclassifier = new SimpleCart(); 
            SimpleCartclassifier.buildClassifier(data);
            modelStr = SimpleCartclassifier.toString();
            classifier = SimpleCartclassifier;
	    	
	    }
	    
	    modelResultSet[0] = algo;
	    modelResultSet[1] = decisionAttribute;
	    modelResultSet[2] = modelStr;
	    
	    // Collect every group of predictions for J48 model in a FastVector
	    FastVector predictions = new FastVector();
    
	    Evaluation evaluation=new Evaluation(data);
	    int folds = 10;  // cross fold validation = 10
	    evaluation.crossValidateModel(classifier,data,folds,new Random(1));  
	    // System.out.println("Evaluatuion"+evaluation.toSummaryString());
	    System.out.println("\n\n"+datanature + " Evaluatuion "+evaluation.toMatrixString());
	
	    // ArrayList<Prediction> predictions = evaluation.predictions();
	    predictions.appendElements(evaluation.predictions());

	    System.out.println("\n\n 11111");
	    // Calculate overall accuracy of current classifier on all splits
        double correct = 0;
	
	    for (int i = 0; i < predictions.size(); i++) {
	  	NominalPrediction np = (NominalPrediction) predictions.elementAt(i);
	        if (np.predicted() == np.actual()) {
	                correct++;
	                        }
	                }
	
	    System.out.println("\n\n 22222");
	    double accuracy = 100 * correct / predictions.size();
	    String accString = String.format("%.2f%%", accuracy);
	    modelResultSet[3] = accString;
	    System.out.println(datanature + " Accuracy "+ accString);
	    
	    String modelFileName = algo+"-DDKA.model";
	    
	    System.out.println("\n\n 33333");
 
	    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\DDKAResources\\"+modelFileName)); 
		oos.writeObject(classifier);
		oos.flush();
		oos.close();

		return modelResultSet;

 		}


public ArrayList<String> getModelAccuracies() {
	return modelAccuracies;
}

public void setModelAccuracies(ArrayList<String> modelAccuracies) {
	this.modelAccuracies = modelAccuracies;
}

public String getDecisionAttribute() {
	return decisionAttribute;
}

public void setDecisionAttribute(String decisionAttribute) {
	this.decisionAttribute = decisionAttribute;
}

public String getModelString() {
	return modelString;
}

public void setModelString(String modelString) {
	this.modelString = modelString;
}



}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/dataadapter/AchievementsAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.sc.Achievements;

/**
 * This is AchievementsAdapter class which implements the Data Access Interface for CRUD operations
 * @author <NAME>
 */
public class AchievementsAdapter implements DataAccessInterface {
    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(AchievementsAdapter.class);
    public AchievementsAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving Achievements. 
     * @param objAchievements
     * @return List of String
     */
    @Override
    public List<String> Save(Object objAchievements) {
        Achievements objInnerAchievements = new Achievements();
        objInnerAchievements =  (Achievements) objAchievements;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_Achievements(?, ?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserID", objInnerAchievements.getUserID());
            objCallableStatement.setString("AchievementValue", objInnerAchievements.getAchievementValue());
            objCallableStatement.setString("AchievementDescription", objInnerAchievements.getAchievementDescription());
            
            if(objInnerAchievements.getAchievementDate()!= null)
            {
               SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
               Date dtDate = sdf.parse(objInnerAchievements.getAchievementDate());

               Timestamp tsDate = new Timestamp(dtDate.getYear(),dtDate.getMonth(), dtDate.getDate(), dtDate.getHours(), dtDate.getMinutes(), dtDate.getSeconds(), 00);
               objCallableStatement.setTimestamp("AchievementDate", tsDate);
            }
            objCallableStatement.setString("SupportingLink", objInnerAchievements.getSupportingLink());
            objCallableStatement.setInt("AchievementStatusID", objInnerAchievements.getAchievementStatusID());
            
            objCallableStatement.registerOutParameter("AchievementID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intAchievementID = objCallableStatement.getLong("AchievementID");
            objDbResponse.add(String.valueOf(intAchievementID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Achievements saved successfully, Achievements Details="+objAchievements);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding Achievements");
        	objDbResponse.add("Error in adding Achievements");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for updating Achievements. 
     * @param objAchievements
     * @return List of String
     */
    @Override
    public List<String> Update(Object objAchievements) {
        
        Achievements objInnerAchievements = new Achievements();
        objInnerAchievements =  (Achievements) objAchievements;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_Achievements(?, ?, ?, ?, ?, ?, ?)}");
            objCallableStatement.setLong("AchievementID", objInnerAchievements.getAchievementID());
            objCallableStatement.setLong("UserID", objInnerAchievements.getUserID());
            objCallableStatement.setString("AchievementValue", objInnerAchievements.getAchievementValue());
            objCallableStatement.setString("AchievementDescription", objInnerAchievements.getAchievementDescription());
            
            if(objInnerAchievements.getAchievementDate()!= null)
            {
               SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
               Date dtDate = sdf.parse(objInnerAchievements.getAchievementDate());

               Timestamp tsDate = new Timestamp(dtDate.getYear(),dtDate.getMonth(), dtDate.getDate(), dtDate.getHours(), dtDate.getMinutes(), dtDate.getSeconds(), 00);
               objCallableStatement.setTimestamp("AchievementDate", tsDate);
            }
            objCallableStatement.setString("SupportingLink", objInnerAchievements.getSupportingLink());
            objCallableStatement.setInt("AchievementStatusID", objInnerAchievements.getAchievementStatusID());
            
            objCallableStatement.execute();
            
            Long intAchievementID = objInnerAchievements.getAchievementID();
            objDbResponse.add(String.valueOf(intAchievementID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Achievements updated successfully, Achievements Details="+objAchievements); 
        }
        catch (Exception e)
        {
        	logger.info("Error in updating Achievements");
        	objDbResponse.add("Error in updating Achievements");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for retrieving Achievements. 
     * @param objAchievements
     * @return List of Achievements
     */
    @Override
    public List<Achievements> RetriveData(Object objAchievements) {
        
        Achievements objOuterAchievements = new Achievements();
        List<Achievements> objListInnerAchievements = new ArrayList<Achievements>();
        objOuterAchievements =  (Achievements) objAchievements;
        
        try
        {
            CallableStatement objCallableStatement = null;
            if(objOuterAchievements.getRequestType() == "ByUserOnly")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_AchievementsByUser(?)}");
                objCallableStatement.setLong("UserID", objOuterAchievements.getUserID());
            }
            else if(objOuterAchievements.getRequestType() == "ByUserandDate")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_AchievementsByUserIDDate(?, ?, ?)}");
                
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
               Date dtStartDate = sdf.parse(objOuterAchievements.getStartDate());
               Timestamp tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);

               Date dtEndDate =sdf.parse( objOuterAchievements.getEndDate()); //.getTime();
               Timestamp tsEndDate = new Timestamp(dtEndDate.getYear(),dtEndDate.getMonth(), dtEndDate.getDate(), dtEndDate.getHours(), dtEndDate.getMinutes(),dtEndDate.getSeconds(),0);
            
                objCallableStatement.setLong("UserID", objOuterAchievements.getUserID());
                objCallableStatement.setTimestamp("StartTime", tsStartDate);
                objCallableStatement.setTimestamp("EndTime", tsEndDate);
            }
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                Achievements objInnerAchievements = new Achievements();
                objInnerAchievements.setAchievementID(objResultSet.getLong("AchievementID"));
                objInnerAchievements.setUserID(objResultSet.getLong("UserID"));
                objInnerAchievements.setAchievementValue(objResultSet.getString("AchievementValue"));
                objInnerAchievements.setAchievementDescription(objResultSet.getString("AchievementDescription"));
                
                if(objResultSet.getTimestamp("AchievementDate") != null)
                {
                    Timestamp tsAchievementDate = objResultSet.getTimestamp("AchievementDate");
                    objInnerAchievements.setAchievementDate(tsAchievementDate.toString());
                }
                objInnerAchievements.setSupportingLink(objResultSet.getString("SupportingLink"));
                   
               objInnerAchievements.setAchievementStatusID(objResultSet.getInt("AchievementStatusID"));
               objInnerAchievements.setAchievementStatusDescription(objResultSet.getString("RecommendationStatusDescription"));
               
               objListInnerAchievements.add(objInnerAchievements);
            }
            objConn.close();
            logger.info("Achievements loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading Achievements");
        }   
        return objListInnerAchievements;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/AER/jh/TransMFCC.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Bang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.AER.jh;
import comirva.audio.util.AudioPreProcessor;
import comirva.audio.util.MFCC;
import comirva.audio.util.PointList;
import comirva.audio.util.gmm.GaussianComponent;
import comirva.audio.util.gmm.GaussianMixture;
import comirva.audio.util.kmeans.KMeansClustering;
import comirva.audio.util.math.Matrix;
import java.io.File;
import java.io.IOException;
import java.util.Vector;

import javax.imageio.IIOException;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;

public class TransMFCC {
	int fileNo=0;
	double[] win_size = new double[157];
	int count = 0;
	private PointList list;
	
	/**
	 * Extract MFCC feature to Vector<double[]>
	 * @param file
	 * @return double[][]
	 */
	

	public Vector<double[]> getMFCC(File file){
		
		Vector<double[]> featurevt = new Vector<double[]>();
		MFCC mf;
		AudioInputStream audioIn;
		AudioPreProcessor audioPre;
		try {
			audioIn = AudioSystem.getAudioInputStream(file);
			audioPre = new AudioPreProcessor(audioIn,audioIn.getFormat().getSampleRate());
			mf = new MFCC(audioPre.getSampleRate(),1024,13,true);
			featurevt = mf.process(audioPre);
			audioIn.close();
			return featurevt;
		} catch (UnsupportedAudioFileException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return featurevt;
	}
	
	public Vector<double[]> getMFCC(AudioInputStream ais, int windowSize, int cepstral,boolean useFirstCoefficient ) throws IOException{
		Vector<double[]>featurevt = new Vector<double[]>();
		ais.reset();
		AudioPreProcessor audioPre;
		try{
			audioPre = new AudioPreProcessor(ais, ais.getFormat().getSampleRate());
			MFCC mf = new MFCC(audioPre.getSampleRate(),windowSize,cepstral,useFirstCoefficient);
			featurevt = mf.process(audioPre);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return featurevt;
		
	}
	/**
	 * Transform MFCC to dobule[][] 
	 * @param doubles
	 * @return double[][]
	 */
	public double[][] getSingleFileFeatures(Vector<double[]> doubles) {
		double[][] result = new double[doubles.size()][doubles.get(0).length];
		for (int i = 0; i < doubles.size(); i++) {
			for (int j = 0; j < doubles.get(0).length; j++) {
					result[i][j] = doubles.get(i)[j];
				}
		}
		
	
		return result;
	}
	
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/test/java/org/uclab/mm/datamodel/sc/dataadapter/testcases/SituationAdapterTest.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc.dataadapter.testcases;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.uclab.mm.datamodel.AbstractDataBridge;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.DatabaseStorage;
import org.uclab.mm.datamodel.sc.Situation;
import org.uclab.mm.datamodel.sc.dataadapter.SituationAdapter;


/**
 * This is a class for testing the insertion, fetching, and update of Situation
 * @author <NAME>
 *
 */
public class SituationAdapterTest {

	/**
	 * This is function for testing the insertion, fetching, and update of Situation 
	 */
	@Test
	public void test() {
		/* Preparing input object for insertion*/
		Situation objOuterSituation = new Situation();
		Situation objInnerSituation = new Situation();
		List<Situation> objListSituation = new  ArrayList<Situation>();
		
		objOuterSituation.setUserID(2L);
		objOuterSituation.setSituationCategoryID(2);
		objOuterSituation.setSituationDescription("5hoursSitting");
		objOuterSituation.setSituationDate("2016 12 12 01:30:01");
	
		/* Testing of insertion function*/
		 DataAccessInterface objDAInterface = new SituationAdapter();
         AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
         List<String> lstResponse = objADBridge.SaveSituation(objOuterSituation);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerSituation.setUserID(2L);
        	 objInnerSituation.setRequestType("ByUserOnly");
        	 DataAccessInterface objDAInterfaceRetrieval = new SituationAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListSituation = objADBridgeRetrieval.RetriveSituation(objInnerSituation);
        	 objInnerSituation = objListSituation.get(0);
         }
         
         assertEquals(objOuterSituation.getSituationDescription(), objInnerSituation.getSituationDescription());
         
         /* Testing of Update function*/
         objInnerSituation.setSituationDescription("5hoursSittingUpdated");
         DataAccessInterface objDAInterfaceUpdate = new SituationAdapter();
         AbstractDataBridge objADBridgeUpdate = new DatabaseStorage(objDAInterfaceUpdate);
         lstResponse = objADBridgeUpdate.UpdateSituation(objInnerSituation);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerSituation.setUserID(2L);
        	 DataAccessInterface objDAInterfaceRetrieval = new SituationAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListSituation = objADBridgeRetrieval.RetriveSituation(objInnerSituation);
        	 objInnerSituation = objListSituation.get(0);
         }
         
         assertEquals(objInnerSituation.getSituationDescription(), "5hoursSittingUpdated");
	}

}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/FoodCategorizer.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Park]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl;

import java.util.Vector;

public class FoodCategorizer {
	String[] foodCate = { "Grain", "Meat", "SeaFood", "Eggs", "MilkyAndDairyProducts", "Legumes", "Nuts", "Fruits",
			"Vegetable", "Snacks" };
	String Grain[] = { "Rice", "Noodle", "Oats", "Barley", "Quinoa", "Brown", "Rye", "Bread" };
	String Meat[] = { "Beef", "Pork", "Chicken" };
	String SeaFood[] = { "Flounder", "PacificSaury", "Daegu", "Shrimp", "Salmon", "Early", "Tuna", "Mackerel", "Head",
			"FishEggs", "SeaWeed" };
	String Eggs[] = { "Egg", "QuailEggs" };
	String MilkyAndDairyProducts[] = { "Milk", "Yogurt", "LowFatCheese", "LowFatMilk" };
	String Legumes[] = { "Beans", "Tofu", "SoyMilk" };
	String Nuts[] = { "Peanut" };
	String Fruits[] = { "Apple", "Kiwi", "Peach", "Apricot", "Melon", "GrapeFruit", "Lemon", "Avocado", "Orange",
			"Banana", "WaterMelon", "Grape" };
	String Vegeable[] = { "Spinach", "Carrot", "Pumpkin", "Cucumber" };
	String Snack[] = { "FriedFood", "Ham", "Snack", "Pizza", "Ramen", "CarbonatedDrink", "Hamburger", "ChickenSnack" };
	Vector<String[]> foodList = new Vector<String[]>();

	public FoodCategorizer() {
		foodList.add(Grain);
		foodList.add(Meat);
		foodList.add(SeaFood);
		foodList.add(Eggs);
		foodList.add(MilkyAndDairyProducts);
		foodList.add(Legumes);
		foodList.add(Nuts);
		foodList.add(Fruits);
		foodList.add(Vegeable);
		foodList.add(Snack);
	}

	public String recognizeFoodItem(String food) {
		String result = "";
		int saveIndex = 0;
		for (int i = 0; i < foodList.size(); i++) {
			for (int k = 0; k < foodList.get(i).length; k++) {
				if (foodList.get(i)[k].equals(food)) {
					saveIndex = i;
				}
			}
		}

		return foodMapping(saveIndex);
	}

	private String foodMapping(int index) {
		return foodCate[index];
	}

}


<|start_filename|>knowledge-curation-layer/DDKAT/src/main/java/org/uclab/mm/kcl/ddkat/services/ModeltoRuleTranslator.java<|end_filename|>
/**
 * Copyright [2017] [<NAME>, <NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.mm.kcl.ddkat.services;

import java.util.ArrayList;
import java.util.List;

import org.uclab.mm.kcl.ddkat.modeltranslator.DTtoRuleTranslator;
import org.uclab.mm.kcl.ddkat.productionmodel.Rule;

//TODO: Auto-generated Javadoc
/**
* This class defines the service functionalities of model translation.
*/
public class ModeltoRuleTranslator implements IClassificationModelTranslator {
	
	private DTtoRuleTranslator ruleTranslator = new DTtoRuleTranslator();
	
	public void setRuleTranslator(DTtoRuleTranslator ruleTranslator) {
		this.ruleTranslator = ruleTranslator;
	}
	
	/**
	 * Method to translate the classification model.
	 *
	 * @return listRule the list of rules
	 */
	public List<Rule> translateModel() {
		
		List<Rule> listRule = new ArrayList<Rule>();
		try{
			listRule = ruleTranslator.translateModel();
		}
		catch(Exception exp)
		{
			exp.printStackTrace();
		}
		
		return listRule;
	}
	

}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/datamodel/SituationConditions.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.datamodel;

import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @version MM v2.5
 * @author Afzal
 *
 */
@XmlRootElement()
public class SituationConditions implements Serializable {

  private String conditionKey;
  private String conditionValueOperator;
  private String conditionValue;
  private String conditionType;

  public SituationConditions() {

  }

  /**
   * SituationCondions
   * 
   * @param conditionKey
   * @param conditionValue
   * @param conditionType
   * @param conditionValueOperator
   */
  public SituationConditions(String conditionKey, String conditionValue,
      String conditionType, String conditionValueOperator) {
    this.conditionKey = conditionKey;
    this.conditionValue = conditionValue;
    this.conditionType = conditionType;
    this.conditionValueOperator = conditionValueOperator;
  }

  /**
   * @return the conditionKey
   */
  public String getConditionKey() {
    return conditionKey;
  }

  /**
   * @param conditionKey
   *          the conditionKey to set
   */
  public void setConditionKey(String conditionKey) {
    this.conditionKey = conditionKey;
  }

  /**
   * @return the conditionValueOperator
   */
  public String getConditionValueOperator() {
    return conditionValueOperator;
  }

  /**
   * @param ConditionValueOperator
   *          the conditionValueOperator to set
   */
  public void setConditionValueOperator(String ConditionValueOperator) {
    this.conditionValueOperator = ConditionValueOperator;
  }

  /**
   * @return the conditionValue
   */
  public String getConditionValue() {
    return conditionValue;
  }

  /**
   * @param ConditionValue
   *          the conditionValue to set
   */
  public void setConditionValue(String ConditionValue) {
    this.conditionValue = ConditionValue;
  }

  /**
   * @return the conditionType
   */
  public String getConditionType() {
    return conditionType;
  }

  /**
   * @param ConditionType
   *          the conditionType to set
   */
  public void setConditionType(String ConditionType) {
    this.conditionType = ConditionType;
  }

  @Override
  public String toString() {
    String keyValue = "\"" + conditionKey + "\":\"" + conditionValue + "\"";

    return keyValue;
  }

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/dataadapter/ActivityPlanAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.sc.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.sc.ActivityPlan;

/**
 * This is ActivityPlanAdapter class which implements the Data Access Interface for CRUD operations
 * @author Taqdir
 */
public class ActivityPlanAdapter implements DataAccessInterface{

     private Connection objConn;
     private static final Logger logger = LoggerFactory.getLogger(ActivityPlanAdapter.class);
    public ActivityPlanAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving ActivityPlan. 
     * @param objActivityPlan
     * @return List of String
     */
    @Override
    public List<String> Save(Object objActivityPlan) {
        ActivityPlan objInnerActivityPlan = new ActivityPlan();
        objInnerActivityPlan =  (ActivityPlan) objActivityPlan;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_ActivityPlan(?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserGoalID", objInnerActivityPlan.getUserGoalId());
            objCallableStatement.setString("PlanDescription", objInnerActivityPlan.getPlanDescription());
            objCallableStatement.setString("Explanation", objInnerActivityPlan.getExplanation());
                                   
            objCallableStatement.registerOutParameter("ActivityPlanID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intActivityPlanID = objCallableStatement.getLong("ActivityPlanID");
            objDbResponse.add(String.valueOf(intActivityPlanID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Activity Plan saved successfully, Activity Plan Details="+objActivityPlan);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding Activity Plan");
        	objDbResponse.add("Error in adding Activity Plan");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for Update ActivityPlan. 
     * Not implemented
     */
    @Override
    public <T> List<String> Update(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for retrieving ActivityPlan. 
     * @param objActivityPlan
     * @return List of ActivityPlan
     * 
     */
    @Override
    public List<ActivityPlan> RetriveData(Object objActivityPlan) {
        ActivityPlan objOuterActivityPlan = new ActivityPlan();
        List<ActivityPlan> objListInnerActivityPlan = new ArrayList<ActivityPlan>();
        objOuterActivityPlan =  (ActivityPlan) objActivityPlan;
        
        try
        {
            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_ActivityPlanByUserGoalID(?)}");
            objCallableStatement.setLong("UserGoalID", objOuterActivityPlan.getUserGoalId());
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                ActivityPlan objInnerActivityPlan = new ActivityPlan();
                objInnerActivityPlan.setActivityPlanId(objResultSet.getLong("ActivityPlanID"));
                objInnerActivityPlan.setUserGoalId(objResultSet.getLong("UserGoalID"));
                objInnerActivityPlan.setPlanDescription(objResultSet.getString("PlanDescription"));
                objInnerActivityPlan.setExplanation(objResultSet.getString("Explanation"));
                
                
                objListInnerActivityPlan.add(objInnerActivityPlan);
            }
            objConn.close();
            logger.info("User Goal loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading User Goal");
        }   
        return objListInnerActivityPlan;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet."); 
    }

    /**
     * This is implementation function for connection database.
     * @param objConf 
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/OntologyTools/ContextOntology.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.OntologyTools;
import java.util.Iterator;
import com.hp.hpl.jena.ontology.DatatypeProperty;
import com.hp.hpl.jena.ontology.ObjectProperty;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.sparql.syntax.ElementUnion;
/**
 * ContextOntology is the class encapsulating the OntModel associated to the
 * Context Ontology which represents the Mining Minds Context Model. This class
 * provides supporting methods to facilitate the access to the Context Ontology.
 * 
 * @author <NAME> and <NAME>
 * @version 2.5
 * @since 2015-10-28
 */
public class ContextOntology extends AbstractOntology{
	/**
	 * OntModel associated to the Context Ontology which represents the Mining
	 * Minds Context Model.
	 */
	protected OntModel ctxModel;
	/**
	 * Constructor of a new Context Ontology
	 * 
	 * @param ctxModel
	 *            OntModel associated to the Context Ontology.
	 */
	public ContextOntology(OntModel ctxModel) {
		this.ctxModel = ctxModel;
	}
	/**
	 * Method to get the OntModel associated to the Context Ontology which
	 * represents the Mining Minds Context Model.
	 * 
	 * @return OntModel representation of the Context Ontology.
	 */
	public OntModel getCtxModel() {
		return ctxModel;
	}
	/**
	 * Method to set the OntModel associated to the Context Ontology which
	 * represents the Mining Minds Context Model.
	 * 
	 * @param ctxModel
	 *            OntModel representation of the Context Ontology.
	 */
	public void setCtxModel(OntModel ctxModel) {
		this.ctxModel = ctxModel;
	}
	/**
	 * Method to get the User class in the Context Ontology.
	 * 
	 * @return OntClass representing the User in the Context Ontology.
	 */
	public OntClass getUserClass() {
		return ctxModel.getOntClass(HLCA.userClassName);
	}
	/**
	 * Method to get the property in the Context Ontology which links a Context
	 * to the User it belongs to.
	 * 
	 * @return ObjectProperty linking a Context to the User it belongs to.
	 */
	public ObjectProperty getContextOfProp() {
		return ctxModel.getObjectProperty(HLCA.isCtxOfPropName);
	}
	/**
	 * Method to get the property in the Context Ontology which links a Context
	 * to its start time.
	 * 
	 * @return DatatypeProperty linking a Context to its start time.
	 */
	public DatatypeProperty getStartTimeProp() {
		return ctxModel.getDatatypeProperty(HLCA.hasStartTimePropName);
	}
	/**
	 * Method to get the property in the Context Ontology which links a Context
	 * to its end time.
	 * 
	 * @return DatatypeProperty linking a Context to its end time.
	 */
	public DatatypeProperty getEndTimeProp() {
		return ctxModel.getDatatypeProperty(HLCA.hasEndTimePropName);
	}
	/**
	 * Method to get the PhysicalActivity Context class in the Context Ontology.
	 * 
	 * @return OntClass representing PhysicalActivity Context in the Context Ontology.
	 */
	public OntClass getHlcClass() {

		return ctxModel.getOntClass(HLCA.pacClassName);
	}
	/** Asif
	 * Method to get the Nutrition Context class in the Context Ontology.
	 * 
	 * @return OntClass representing Nutrition Context in the Context Ontology.
	 */
	public OntClass getNutHlcClass() {
		return ctxModel.getOntClass(HLCA.nutrClassName); 
	}
	/** Asif
	 * Method to get the Nutrition Context class in the Context Ontology.
	 * 
	 * @return OntClass representing Nutrition Context in the Context Ontology.
	 */
	public OntClass getClinicalHlcClass() {
		return ctxModel.getOntClass(HLCA.clinicalClassName); 
	}
	/**
	 * Method to get the Low Level Context class in the Context Ontology.
	 * 
	 * @return OntClass representing Low Level Context in the Context Ontology.
	 */
	public OntClass getLlcClass() {
		return ctxModel.getOntClass(HLCA.llcClassName);    
	}
	/**
	 * Method to get the property in the Context Ontology which links a 
	 * PhysicalActivity and Nutrition Context to the Activity which is part of it.
	 * 
	 * @return ObjectProperty linking a PhysicalActivity Context to the Activity which
	 *         is part of it.
	 */
	public ObjectProperty getActivityProp() {
		return ctxModel.getObjectProperty(HLCA.hasActivityPropName);
	}
	/**
	 * Method to get the property in the Context Ontology which links a 
	 * PhysicalActivity and Nutrition Context to the Location which is part of it.
	 * 
	 * @return ObjectProperty linking a PhysicalActivity Context to the Location which
	 *         is part of it.
	 */
	public ObjectProperty getLocationProp() {
		return ctxModel.getObjectProperty(HLCA.hasLocationPropName);
	}
	/**
	 * Method to get the property in the Context Ontology which links a 
	 * PhysicalActivity and Nutrition to the Emotion which is part of it.
	 * 
	 * @return ObjectProperty linking a PhysicalActivity Context to the Emotion which
	 *         is part of it.
	 */
	public ObjectProperty getEmotionProp() {
		return ctxModel.getObjectProperty(HLCA.hasEmotionPropName);
	}
	/**   Asif
	 * Method to get the property in the Context Ontology which links a 
	 * PhysicalActivity and Nutrition Context to the Food which is part of it.
	 * 
	 * @return ObjectProperty linking a Nutrition Context to the Food which
	 *         is part of it.
	 */
	public ObjectProperty getFoodProp() {
		return ctxModel.getObjectProperty(HLCA.hasFoodPropName);
	}
	/**   Asif
	 * Method to get the property in the Context Ontology which links a 
	 * PhysicalActivity and Nutrition Context to the Food which is part of it.
	 * 
	 * @return ObjectProperty linking a Nutrition Context to the Food which
	 *         is part of it.
	 */
	public ObjectProperty getBloodGlucoseProp() {
		return ctxModel.getObjectProperty(HLCA.hasBloodGlucosePropName);
	}

	/**   Asif
	 * Method to get the property in the Context Ontology which links a 
	 * PhysicalActivity and Nutrition Context to the Food which is part of it.
	 * 
	 * @return ObjectProperty linking a Nutrition Context to the Food which
	 *         is part of it.
	 */
	public ObjectProperty getBloodPressureProp() {
		return ctxModel.getObjectProperty(HLCA.hasBloodPressurePropName);
	}
	/**   Asif
	 * Method to get the property in the Context Ontology which links a 
	 * PhysicalActivity and Nutrition Context to the Food which is part of it.
	 * 
	 * @return ObjectProperty linking a Nutrition Context to the Food which
	 *         is part of it.
	 */
	public ObjectProperty getWaterIntakeProp() {
		return ctxModel.getObjectProperty(HLCA.hasWaterIntakePropName);
	}
	/**
	 * Method to get the subclass of Low Level Context of a given type, e.g.
	 * Sitting or Standing for the category Activity.
	 * 
	 * @param llcTypeName
	 *            Name of the type of Low Level Context.
	 * @return OntClass representing the type llcTypeName in the Context
	 *         Ontology.
	 */
	public OntClass getLlcTypeClass(String llcTypeName) {
		return ctxModel.getOntClass(llcTypeName);
	}
	/**
	 * Method to get the subclass of Low Level Context of a given category, e.g.
	 * Activity, Emotion or Location.
	 * 
	 * @param llcCategoryName
	 *            Name of the category of Low Level Context.
	 * @return OntClass representing the category llcCategoryName in the Context
	 *         Ontology.
	 */
	public OntClass getLlcCategoryClass(String llcCategoryName) {
		return ctxModel.getOntClass(llcCategoryName);
	}
	/**
	 * Method to get the superclass of Low Level Context of a given category, e.g.
	 * Activity, Emotion, food or Location.
	 * 
	 * @param LlcSuperClassCategory
	 *            Name of the category of Low Level Context.
	 * @return OntClass representing the category LlcSuperClassCategory in the Context
	 *         Ontology.
	 */
	public OntClass getLlcSuperClassCategory (OntClass category) {
		OntClass LlcSuperClassCategory = null;
		for (Iterator i = category.listSuperClasses(true); i.hasNext();)  
		{
			LlcSuperClassCategory  = (OntClass) i.next();
				};	
		return LlcSuperClassCategory;
	}
}

<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/ActivityRecommendation.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.sc;

import java.io.Serializable;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author Taqdir
 */
@Entity
public class ActivityRecommendation implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    
    private Long activityRecommendationId;
    private Long activityPlanId;
    private String description;
    //private GregorianCalendar timestamp;
    private String timestamp;
    private String planDescription;
    private String requestType;
    private Long userID;
    
    private String startTimestamp;
    private String endTimestamp;
    

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof ActivityRecommendation)) {
            return false;
        }
        ActivityRecommendation other = (ActivityRecommendation) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.sc.ActivityRecommendation[ id=" + id + " ]";
    }

    /**
     * @return the activityRecommendationId
     */
    public Long getActivityRecommendationId() {
        return activityRecommendationId;
    }

    /**
     * @param activityRecommendationId the activityRecommendationId to set
     */
    public void setActivityRecommendationId(Long activityRecommendationId) {
        this.activityRecommendationId = activityRecommendationId;
    }

    /**
     * @return the activityPlanId
     */
    public Long getActivityPlanId() {
        return activityPlanId;
    }

    /**
     * @param activityPlanId the activityPlanId to set
     */
    public void setActivityPlanId(Long activityPlanId) {
        this.activityPlanId = activityPlanId;
    }

    /**
     * @return the description
     */
    public String getDescription() {
        return description;
    }

    /**
     * @param description the description to set
     */
    public void setDescription(String description) {
        this.description = description;
    }

    /**
     * @return the timestamp
     */
    public String getTimestamp() {
        return timestamp;
    }

    /**
     * @param timestamp the timestamp to set
     */
    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
    }

    /**
     * @return the planDescription
     */
    public String getPlanDescription() {
        return planDescription;
    }

    /**
     * @param planDescription the planDescription to set
     */
    public void setPlanDescription(String planDescription) {
        this.planDescription = planDescription;
    }

    /**
     * @return the requestType
     */
    public String getRequestType() {
        return requestType;
    }

    /**
     * @param requestType the requestType to set
     */
    public void setRequestType(String requestType) {
        this.requestType = requestType;
    }

    /**
     * @return the userID
     */
    public Long getUserID() {
        return userID;
    }

    /**
     * @param userID the userID to set
     */
    public void setUserID(Long userID) {
        this.userID = userID;
    }

    /**
     * @return the startTimestamp
     */
    public String getStartTimestamp() {
        return startTimestamp;
    }

    /**
     * @param startTimestamp the startTimestamp to set
     */
    public void setStartTimestamp(String startTimestamp) {
        this.startTimestamp = startTimestamp;
    }

    /**
     * @return the endTimestamp
     */
    public String getEndTimestamp() {
        return endTimestamp;
    }

    /**
     * @param endTimestamp the endTimestamp to set
     */
    public void setEndTimestamp(String endTimestamp) {
        this.endTimestamp = endTimestamp;
    }
    
}


<|start_filename|>data-curation-layer/data-acquisition-and-synchronization/api.js<|end_filename|>
/*Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/
var nodeProcess = require('process');
var jsonFile = require('jsonfile');
var util = require('util');
var request = require("request");
function isJson(item) {
    item = typeof item !== "string"
        ? JSON.stringify(item)
        : item;

    try {
        item = JSON.parse(item);
    } catch (e) {
        return false;
    }

    if (typeof item === "object" && item !== null) {
        return true;
    }

    return false;
}

function isURL(str) {
  var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
  '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|'+ // domain name
  '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
  '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
  '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
  '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
  return pattern.test(str);
}

function syncStart (mergeDataBody, jsonConfig)
{	
	var jsonUrl=jsonConfig.destUrl;		
	var requestData=JSON.stringify(mergeDataBody);
	console.log("send data-------------------: " + requestData)	
	for(var i=0;i<jsonUrl.length;i++)
	{
		requestUrl=jsonUrl[i]["url"]+'/saveData';
		console.log("Sending data to URL: " + requestUrl);
		request({
		url: requestUrl,
		method: "POST",
		json: true,
		headers: {
			"content-type": "application/json",
		},
		json: mergeDataBody //no need to stringify, we can send json directly!
		},function (error, response, body) {
			if (!error && response.statusCode === 200) {
				console.log(body)
			}
			else {

				console.log("error: " + error)
				//console.log("response.statusCode: " + response.statusCode)
				//console.log("response.statusText: " + response.statusText)
			}
		});
	}
}

var sensorQtyAdjust = function(sensorNumber, jsonConfig) {
	try {
		if(isNaN(sensorNumber)) throw "the input should be a number. Adjustment is cancelled.";
		if(jsonConfig.nDataSource!=sensorNumber)
		{
			jsonConfig.nDataSource=sensorNumber;		
			jsonFile.writeFileSync("./config.json",jsonConfig);
			console.log("Notice: adjustment completed.");
			nodeProcess.exit(1);			
		}else{
			console.log("Notice: The input value is the same as the last one. Adjustment rejected.");
		}
		
	}catch(err)
	{
		console.log("Error: "+err);
	}
};

var serverPortAdjust = function(port, jsonConfig) {
	try {
		if(isNaN(sensorNumber)) throw "the input should be a number. Adjustment is cancelled.";
		if(jsonConfig.serverPort!=port)
		{
			jsonConfig.serverPort=port;		
			jsonFile.writeFileSync("./config.json",jsonConfig);
			console.log("Notice: adjustment completed.");
			nodeProcess.exit(1);			
		}else{
			console.log("Notice: The input value is the same as the last one. Adjustment rejected.");
		}
		
	}catch(err)
	{
		console.log("Error: "+err);
	}
};


var deadlineAdjust = function(dueDate, jsonConfig) {
	try {
		if(isNaN(dueDate)) throw "the input should be milliseconds. Adjustment is cancelled.";
		if(jsonConfig.deadline!=dueDate)
		{
			jsonConfig.deadline=dueDate;	
			jsonFile.writeFileSync("./config.json",jsonConfig);
			console.log("Notice: adjustment completed.");
			nodeProcess.exit(1);
		}else{
			console.log("Notice: The input value is the same as the last one. Adjustment rejected.");
		}
	}catch(err)
	{
		console.log("Error: "+err);
	}
};
var destAdjust= function(jsonUrl, jsonConfig) {
	try {
		if(!isJson(jsonUrl)) throw "the input should be in JSON format. Adjustment is cancelled.";
		for(var i=0;i<jsonUrl.length;i++)
		{			
			if(!isURL(jsonUrl[i]["url"])) throw "the input should be URL. Adjustment is cancelled.";
		}		
		if(JSON.stringify(jsonConfig.destUrl)!=JSON.stringify(jsonUrl))
		{
			jsonConfig.destUrl=jsonUrl;	
			jsonFile.writeFileSync("./config.json",jsonConfig);
			console.log("Notice: adjustment completed.");
			nodeProcess.exit(1);
		}else{
			console.log("Notice: The input value is the same as the last one. Adjustment rejected.");
		}
	}catch(err)
	{
		console.log("Error: "+err);
	}
};

/*****************************************************
Function: coreSync
Content: every time a data comes, check for enough data or not, then do the good sync as we expected.
Input parameters: coreSync(objLoki,mUserId,history,badMerge,historyRecord)
1. objLoki: the reference to the buffer collection.
2. mUserId: the id of the user.
3. history: the reference to the history collection.
4. badMerge: optional, this flag indicates that the coreSync needs to check for syncronization for one last time, then do the forced sync.
5. historyRecord: the record that is used to cover the missing data.
Output:
1. return 1 if the sync is not performed.
2. return the synced json if enough data is collected by good or bad sync.
*****************************************************/
var coreSync= function(objLoki,mUserId,history,nDataSource,jsonConfig,badMerge,historyRecord,syncType) {
	
	var mergeDataBody=1;
	//var recordSyncYet = objLoki.find({'$and': [{syncYet:1},{userID: mUserId}]});
	//if(recordSyncYet.length){return mergeDataBody;}//has already synced!
	objLoki.find({userID: mUserId});
	var record = objLoki.find({userID: mUserId});
	//console.log("record.length"+record.length);
	if(record.length==nDataSource)//enough quantity. start merging the data and send.
	{
		mergeDataBody={};//all the records are merged into this variable.
		mergeDataBody["userID"]=mUserId;	
		for(var i = 0; i < record.length; i++){//merge data process
			/*if(record[i].syncYet == 0){
				record[i].syncYet=1;
				record[i].syncEndTime=Date.now();
				objLoki.update(record[i]);
				clearTimeout(record[i].syncClockRef);
				console.log("clear bad sync for "+record[0].userID+"---"+record[i].syncClockRef);
			}*/
			mergeDataBody["timeStamp_"+record[i].dataType]=record[i].timeStamp;
			mergeDataBody["contentBody_"+record[i].dataType]=record[i].contentBody;
			clearTimeout(record[i].syncClockRef);//clear the bad sync handle.
			objLoki.remove(record[i]);//remove the merged record.
		}
		var recordHistory = history.find({userID: mUserId});//find the latest historical data of this user
		if(recordHistory.length){history.remove(recordHistory);}//delete the latest one.
		history.insert(mergeDataBody);//insert with the new one
		//console.log(JSON.stringify(history));
	}else{// not enough data.
		if(typeof badMerge == 'undefined')//but the deadline is not exceed, no need for bad sync.
		{
			return mergeDataBody;//return 1 to indicate that the data is not synced yet.
		}else{//deadline is exceeded, let's do the bad thing.
			if(typeof historyRecord != 'undefined')//the historical data is ok to cover the missing data.
			{	
				mergeDataBody=historyRecord;//fill the data collection with the historical data.
				for(var i = 0; i < record.length; i++){//this moment, I add the new data to data collection.
					/*if(record[i].syncYet == 0){
							record[i].syncYet=1;
							record[i].syncEndTime=Date.now();
							objLoki.update(record[i]);
							console.log("do the bad sync for "+record[0].userID+"---"+record[i].syncClockRef);
						}*/
					mergeDataBody["timeStamp_"+record[i].dataType]=record[i].timeStamp;
					mergeDataBody["contentBody_"+record[i].dataType]=record[i].contentBody;
					objLoki.remove(record[i]);//remove the merged record.
				}
				console.log("?????????????????????Data synced by badSync????????????????");
			}else{//there is no historical data, reset the bad sync to wait for enough data. There is no other option.
				/*console.log("The history data is not available to cover the missing data.");
				var badSyncClockAgain=setTimeout(function(){ badSync(objLoki,mUserId,history)},deadline);//reset the bad sync.
				//update the first record to keep the bad sync handle. the syncYet key keeps the role of an anchor to define the first record.
				var reSync = objLoki.find({'$and': [{syncYet:0},{userID: mUserId}]});
				reSync[0].syncClockRef=badSyncClockAgain;
				objLoki.update(reSync[0]);
				*/
				console.log("?????????????????????Data synced by forcedSync????????????????");
				mergeDataBody={};//all the records are merged into this variable.
				mergeDataBody["userID"]=mUserId;	
				for(var i = 0; i < record.length; i++){//merge data process					
					mergeDataBody["timeStamp_"+record[i].dataType]=record[i].timeStamp;
					mergeDataBody["contentBody_"+record[i].dataType]=record[i].contentBody;
					clearTimeout(record[i].syncClockRef);//clear the bad sync handle.
					objLoki.remove(record[i]);//remove the merged record.
				}				
			}
		}
	}
	console.log("********");
	console.log("-------");
	console.log("Synced data:");
	console.log("-------");
	//console.log(JSON.stringify(mergeDataBody));
	console.log(util.inspect(mergeDataBody));
	console.log("++++++++");
	//var time2Sync=Date.now();
	//var timeObj=new Date(time2Sync);
	//summaryDuration=summaryDuration+time2Sync;	
	//nSync=nSync+1;
	//console.log("Time to end sync:"+ timeObj.toUTCString());
	//console.log("Average sync duration:"+ ((summaryDuration-tempDate.getTime())/nSync));
	console.log("********");
	
	syncStart(mergeDataBody,jsonConfig);
	return mergeDataBody;
};
exports.sensorQtyAdjust = sensorQtyAdjust;
exports.deadlineAdjust = deadlineAdjust;
exports.destAdjust = destAdjust;
exports.coreSync = coreSync;
exports.serverPortAdjust = serverPortAdjust;

<|start_filename|>supporting-layer/uiux-authoring-tool/JavaDoc/org/uclab/mm/sl/uiux/analytics/TrackHelper.html<|end_filename|>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_76-release) on Fri Dec 23 12:27:01 KST 2016 -->
<title>TrackHelper</title>
<meta name="date" content="2016-12-23">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
    try {
        if (location.href.indexOf('is-external=true') == -1) {
            parent.document.title="TrackHelper";
        }
    }
    catch(err) {
    }
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":9,"i6":9,"i7":10};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!--   -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!--   -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/TrackHelper.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/Tracker.html" title="class in org.uclab.mm.sl.uiux.analytics"><span class="typeNameLink">Prev&nbsp;Class</span></a></li>
<li><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.AppTracking.html" title="class in org.uclab.mm.sl.uiux.analytics"><span class="typeNameLink">Next&nbsp;Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/uclab/mm/sl/uiux/analytics/TrackHelper.html" target="_top">Frames</a></li>
<li><a href="TrackHelper.html" target="_top">No&nbsp;Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
  allClassesLink = document.getElementById("allclasses_navbar_top");
  if(window==top) {
    allClassesLink.style.display = "block";
  }
  else {
    allClassesLink.style.display = "none";
  }
  //-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary:&nbsp;</li>
<li><a href="#nested.class.summary">Nested</a>&nbsp;|&nbsp;</li>
<li>Field&nbsp;|&nbsp;</li>
<li>Constr&nbsp;|&nbsp;</li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail:&nbsp;</li>
<li>Field&nbsp;|&nbsp;</li>
<li>Constr&nbsp;|&nbsp;</li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!--   -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.uclab.mm.sl.uiux.analytics</div>
<h2 title="Class TrackHelper" class="title">Class TrackHelper</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.uclab.mm.sl.uiux.analytics.TrackHelper</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="typeNameLabel">TrackHelper</span>
extends java.lang.Object</pre>
<div class="block">The type Track helper.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== NESTED CLASS SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="nested.class.summary">
<!--   -->
</a>
<h3>Nested Class Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Nested Class Summary table, listing nested classes, and an explanation">
<caption><span>Nested Classes</span><span class="tabEnd">&nbsp;</span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static class&nbsp;</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.AppTracking.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper.AppTracking</a></span></code>
<div class="block">The type App tracking.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static class&nbsp;</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.EventBuilder.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper.EventBuilder</a></span></code>
<div class="block">The type Event builder.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static class&nbsp;</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.Exception.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper.Exception</a></span></code>
<div class="block">The type Exception.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static class&nbsp;</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.Screen.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper.Screen</a></span></code>
<div class="block">The type Screen.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static class&nbsp;</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.UncaughtExceptions.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper.UncaughtExceptions</a></span></code>
<div class="block">The type Uncaught exceptions.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!--   -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.EventBuilder.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper.EventBuilder</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.html#event-java.lang.String-java.lang.String-">event</a></span>(java.lang.String&nbsp;category,
     java.lang.String&nbsp;action)</code>
<div class="block">Events are a useful way to collect data about a user's interaction with interactive components of your app,
 like button presses or the use of a particular item in a game.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.Exception.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper.Exception</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.html#exception-java.lang.Throwable-">exception</a></span>(java.lang.Throwable&nbsp;throwable)</code>
<div class="block">Caught exceptions are errors in your app for which you've defined exception handling code,
 such as the occasional timeout of a network connection during a request for data.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.Screen.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper.Screen</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.html#screen-android.app.Activity-">screen</a></span>(android.app.Activity&nbsp;activity)</code>
<div class="block">Calls <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.html#screen-java.lang.String-"><code>screen(String)</code></a> for an activity.</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.Screen.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper.Screen</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.html#screen-java.lang.String-">screen</a></span>(java.lang.String&nbsp;path)</code>
<div class="block">To track a screenview.</div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.AppTracking.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper.AppTracking</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.html#screens-android.app.Application-">screens</a></span>(android.app.Application&nbsp;app)</code>
<div class="block">This method will bind a tracker to your application,
 causing it to automatically track Activities with <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.html#screen-android.app.Activity-"><code>screen(Activity)</code></a> within your app.</div>
</td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.html#track--">track</a></span>()</code>
<div class="block">Track track helper.</div>
</td>
</tr>
<tr id="i6" class="altColor">
<td class="colFirst"><code>static <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.html#track-org.uclab.mm.sl.uiux.analytics.TrackMe-">track</a></span>(<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackMe.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackMe</a>&nbsp;base)</code>
<div class="block">Track track helper.</div>
</td>
</tr>
<tr id="i7" class="rowColor">
<td class="colFirst"><code><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.UncaughtExceptions.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper.UncaughtExceptions</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.html#uncaughtExceptions--">uncaughtExceptions</a></span>()</code>
<div class="block">This will create an exception handler that wraps any existing exception handler.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!--   -->
</a>
<h3>Methods inherited from class&nbsp;java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!--   -->
</a>
<h3>Method Detail</h3>
<a name="track--">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>track</h4>
<pre>public static&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper</a>&nbsp;track()</pre>
<div class="block">Track track helper.</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the track helper</dd>
</dl>
</li>
</ul>
<a name="track-org.uclab.mm.sl.uiux.analytics.TrackMe-">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>track</h4>
<pre>public static&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper</a>&nbsp;track(@NonNull
                                <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackMe.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackMe</a>&nbsp;base)</pre>
<div class="block">Track track helper.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>base</code> - the base</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the track helper</dd>
</dl>
</li>
</ul>
<a name="screen-java.lang.String-">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>screen</h4>
<pre>public&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.Screen.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper.Screen</a>&nbsp;screen(java.lang.String&nbsp;path)</pre>
<div class="block">To track a screenview.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>path</code> - Example: "/user/settings/billing"</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>an object that allows addition of further details.</dd>
</dl>
</li>
</ul>
<a name="screen-android.app.Activity-">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>screen</h4>
<pre>public&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.Screen.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper.Screen</a>&nbsp;screen(android.app.Activity&nbsp;activity)</pre>
<div class="block">Calls <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.html#screen-java.lang.String-"><code>screen(String)</code></a> for an activity.
 Uses the activity-stack as path and activity title as names.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>activity</code> - the activity to track</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the screen</dd>
</dl>
</li>
</ul>
<a name="event-java.lang.String-java.lang.String-">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>event</h4>
<pre>public&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.EventBuilder.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper.EventBuilder</a>&nbsp;event(@NonNull
                                      java.lang.String&nbsp;category,
                                      @NonNull
                                      java.lang.String&nbsp;action)</pre>
<div class="block">Events are a useful way to collect data about a user's interaction with interactive components of your app,
 like button presses or the use of a particular item in a game.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>category</code> - (required) – this String defines the event category.                 You might define event categories based on the class of user actions,                 like clicks or gestures or voice commands, or you might define them based upon the                 features available in your application (play, pause, fast forward, etc.).</dd>
<dd><code>action</code> - (required) this String defines the specific event action within the category specified.                 In the example, we are basically saying that the category of the event is user clicks,                 and the action is a button click.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>an object that allows addition of further details.</dd>
</dl>
</li>
</ul>
<a name="exception-java.lang.Throwable-">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>exception</h4>
<pre>public&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.Exception.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper.Exception</a>&nbsp;exception(java.lang.Throwable&nbsp;throwable)</pre>
<div class="block">Caught exceptions are errors in your app for which you've defined exception handling code,
 such as the occasional timeout of a network connection during a request for data.
 <p/>
 This is just a different way to define an event.
 Keep in mind UIUXAnalytics is not a crash tracker, use this sparingly.
 <p/>
 For this to be useful you should ensure that proguard does not remove all classnames and line numbers.
 Also note that if this is used across different app versions and obfuscation is used, the same exception might be mapped to different obfuscated names by proguard.
 This would mean the same exception (event) is tracked as different events by UIUXAnalytics.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>throwable</code> - exception instance</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the exception</dd>
</dl>
</li>
</ul>
<a name="uncaughtExceptions--">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>uncaughtExceptions</h4>
<pre>public&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.UncaughtExceptions.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper.UncaughtExceptions</a>&nbsp;uncaughtExceptions()</pre>
<div class="block">This will create an exception handler that wraps any existing exception handler.
 Exceptions will be caught, tracked, dispatched and then rethrown to the previous exception handler.
 <p/>
 Be wary of relying on this for complete crash tracking..
 Think about how to deal with older app versions still throwing already fixed exceptions.
 <p/></div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the uncaught exceptions</dd>
</dl>
</li>
</ul>
<a name="screens-android.app.Application-">
<!--   -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>screens</h4>
<pre>public&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.AppTracking.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackHelper.AppTracking</a>&nbsp;screens(android.app.Application&nbsp;app)</pre>
<div class="block">This method will bind a tracker to your application,
 causing it to automatically track Activities with <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.html#screen-android.app.Activity-"><code>screen(Activity)</code></a> within your app.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>app</code> - your app</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the registered callback, you need this if you wanted to unregister the callback again</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!--   -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!--   -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/TrackHelper.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/Tracker.html" title="class in org.uclab.mm.sl.uiux.analytics"><span class="typeNameLink">Prev&nbsp;Class</span></a></li>
<li><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/TrackHelper.AppTracking.html" title="class in org.uclab.mm.sl.uiux.analytics"><span class="typeNameLink">Next&nbsp;Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/uclab/mm/sl/uiux/analytics/TrackHelper.html" target="_top">Frames</a></li>
<li><a href="TrackHelper.html" target="_top">No&nbsp;Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
  allClassesLink = document.getElementById("allclasses_navbar_bottom");
  if(window==top) {
    allClassesLink.style.display = "block";
  }
  else {
    allClassesLink.style.display = "none";
  }
  //-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary:&nbsp;</li>
<li><a href="#nested.class.summary">Nested</a>&nbsp;|&nbsp;</li>
<li>Field&nbsp;|&nbsp;</li>
<li>Constr&nbsp;|&nbsp;</li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail:&nbsp;</li>
<li>Field&nbsp;|&nbsp;</li>
<li>Constr&nbsp;|&nbsp;</li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!--   -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/config/ContextType.java<|end_filename|>
/*
Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.config;

import java.util.ArrayList;

import org.uclab.mm.icl.llc.LLCManager.ContextLabel;
import org.uclab.mm.icl.llc.restservices.RestClients;



/**
 * Enum to represent the different types of context which are generated by the different RecognizerType.
 * @author Nailbrainz
 *
 */
public enum ContextType {
	
	Activity(0), Emotion(1), Location(2), Food(3);
	
	
    private int value;
    private ContextType(int _value){
        value = _value;
    }
    
    private static final ArrayList<String[]> labels = new ArrayList<String[]>();
    
    
    static{
    	String[] actLabels = {"Eating","Running","Sitting"
    			,"Standing","Walking","Stretching","Sweeping","LyingDown","NoActivity"};
        String[] emoLabel = { "Angry", "Happiness", "Neutral", "Sadness", "NoEmotion" };
        //String[] places = {"Home", "Office", "NoLocation"};
        String[] places = {"Home", "Office", "Yard","Gym","Mall", "Restaurant", "NoLocation"};
        
        
        String[] directions = {"NoFood"};
        
        labels.add(actLabels);
        labels.add(emoLabel);
        labels.add(places);
        labels.add(directions);
    }
    
    //define the labels of each context type below. Note that, the last context should be No(contextName)
    
    
    
  
    
    /**
     * Returns the window size of the current context
     * @return window size of the current context
     */
    public int getDefaultWindowSize(){
    	ContextType ct = ContextType.values()[value];
    	switch(ct){
    	case Activity:
    		return 6;
    	case Emotion:
    		return 9;
    	case Location:
    		return 12;
    	case Food:
    		return 12;
    	}
    	return 0;
    }
    
    /**
	 * 
	 * @param llc low level context which will be transfered into DCL
	 * @return State string describing the operation
	 */
	public void notifyLLCToDCL(ContextLabel llc){
		String ret = "Err";
		ContextType ct = ContextType.values()[value];
		try {
			switch(ct){
			case Emotion:
				ret =  RestClients.addUserRecognizedEmotion(llc);
				break;
			case Activity:
				ret =  RestClients.addUserRecognizedAct(llc);
				break;
			case Location:
				ret =  RestClients.addUserDetectedLoc(llc);
				break;
			case Food:
				ret =  RestClients.AddFoodLog(llc);
				break;
			default:
				break;				
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		//return ret;
	}
    
    
    /**
     * Returns the list of labels for the current context
     * @return label of the current context
     */
    public String[] getLabels(){
    	return labels.get(value);
    }
    
    /**
     * Returns the value for the current context, which is configed inside the enum
     * @return value of the current context
     */
    public int getValue(){
        return value;
    }
    
    
    /**
     * Returns basic ContextLabel instance of label No(ContextName), for each contextType
     * @param userID user Id to set on ContextLabel instance 
     * @param timeStamp timestamp to set on ContextLabel instance
     * @return Basic ContextLabel instance
     */
    public ContextLabel getBasicLabel(long userID, String timeStamp){
    	return new ContextLabel(userID, labels.get(value)[labels.get(value).length-1], timeStamp, ContextType.values()[value]);
    }
    
    /**
     * Returns  ContextLabel instance for each contextType
     * @param userID user Id to set on ContextLabel instance 
     * @param Label label to set on ContextLabel instance 
     * @param timeStamp timestamp to set on ContextLabel instance 
     * @return ContextLabel instance, corresponding to the parameters
     */
    public ContextLabel getContext(long userID, String Label, String timeStamp){
    	return new ContextLabel(userID, Label, timeStamp, ContextType.values()[value]);
    }
    
    
    /**
     * Returns the window size of the current context
     * @return window size of the current context
     */
    public int getWindowSize(){
    	return ICLConfig.contextWindowSize.get(value);
    }
    
    
}


<|start_filename|>data-curation-layer/data-persistence/LocalFileManagement.js.html<|end_filename|>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JSDoc: Source: LocalFileManagement.js</title>

    <script src="scripts/prettify/prettify.js"> </script>
    <script src="scripts/prettify/lang-css.js"> </script>
    <!--[if lt IE 9]>
      <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>

<body>

<div id="main">

    <h1 class="page-title">Source: LocalFileManagement.js</h1>

    



    
    <section>
        <article>
            <pre class="prettyprint source linenums"><code>
/**
 * @author <NAME>
 * @since 2016.11.21
 * @version 0.1

 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at

 *   http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


/**
 * @description Storing data in local(temp.txt).
 * @description Storing metadata in local(metadata.txt).
 * @module lfm(LocalFileManagement)
 * @param {string} parsed sequential JSON data.
 * @return {number} cnt
 */

var config = require('./config.json');
var fs = require('fs');
var unitSize = config.fileSizeUnit;

exports.lfm = function(userID, timestamp, contentbody){	

	var cnt;
	var filedata; 

	filedata = fs.readFileSync('temp.txt', 'utf-8');
	fs.writeFileSync('temp.txt', filedata + '\r\n' + userID + '  ' + timestamp + '  ' + contentbody);

	var stats = fs.statSync("temp.txt");
	var fileSizeInBytes = stats["size"];
	console.log("temp.txt file size is : " + fileSizeInBytes);

	if(fileSizeInBytes &lt; unitSize)
	{
		console.log("File is not full");
		return -1;
	}
	else
	{
		cnt = fs.readFileSync('metadata.txt', 'utf-8');
		fs.writeFileSync('metadata.txt', parseInt(cnt)+1);
		console.log("File is Full : is seding to HDFS Server!");
		return cnt;
	}

	return -1;
};
</code></pre>
        </article>
    </section>




</div>

<nav>
    <h2><a href="index.html">Home</a></h2><h3>Modules</h3><ul><li><a href="lfm.html">lfm</a></li></ul>
</nav>

<br class="clear">

<footer>
    Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.4.3</a> on Sat Dec 24 2016 10:13:33 GMT+0900 (KST)
</footer>

<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/LLCRecognizer/AudioEmotionRecognizer.java<|end_filename|>
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.uclab.mm.icl.llc.LLCRecognizer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Vector;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioFormat.Encoding;
import org.apache.log4j.Logger;
import org.uclab.mm.icl.data.DeviceData;
import org.uclab.mm.icl.data.SmartphoneData;
import org.uclab.mm.icl.llc.AER.jh.AudioBufferManagement;
import org.uclab.mm.icl.llc.LLCManager.ContextLabel;
import org.uclab.mm.icl.llc.LLCManager.LLCUnifier;
import org.uclab.mm.icl.llc.LLCManager.MajorityVoting;
import org.uclab.mm.icl.llc.MachineLearningTools.ExtClassification;
import org.uclab.mm.icl.llc.MachineLearningTools.FilterBankPreprocessing;
import org.uclab.mm.icl.llc.MachineLearningTools.SilentRemoverPreprocessing;
import org.uclab.mm.icl.llc.MachineLearningTools.TimeDomainFeatureExtraction;
import org.uclab.mm.icl.llc.MachineLearningTools.WindowBasedSegmentation;
import org.uclab.mm.icl.llc.config.ContextType;
import org.uclab.mm.icl.llc.config.DeviceType;
import org.uclab.mm.icl.llc.config.RecognizerType;

/**
 * This class recognizes filters the audio data based on the frequency, and
 * recognizes user emotion from the filtered audio data.
 * 
 * @author <NAME>
 */


class EmotionDataJH{
	
	AudioInputStream ais;
	String timeStamp;
	
	@SuppressWarnings("unused")
	private EmotionDataJH(){}
	
	public EmotionDataJH(AudioInputStream ais, String timeStamp) {
		super();
		this.ais = ais;
		this.timeStamp = timeStamp;
	}
	public AudioInputStream getAIS() {
		return ais;
	}
	public void setAIS(AudioInputStream ss) {
		this.ais = ss;
	}
	public String getTimeStamp() {
		return timeStamp;
	}
	public void setTimeStamp(String timeStamp) {
		this.timeStamp = timeStamp;
	}
	
	
	
}

public class AudioEmotionRecognizer extends LLCRecognizer<EmotionDataJH> {
	private final static Logger logger = Logger.getLogger(AudioEmotionRecognizer.class);
	public static String[] emoLabel = { "Anger", "Happiness", "Sadness", "NoEmotion" };
	String timeStamp;

	Long userID;

	AudioInputStream buffer = null; // Audio Buffer
	AudioInputStream inputData = null; // Audio Buffer
	AudioBufferManagement abm = null; // Supporting Class for accumulating Audio
										// Buffer
	TimeDomainFeatureExtraction fe = new TimeDomainFeatureExtraction();
	SilentRemoverPreprocessing silentRemover = new SilentRemoverPreprocessing(Encoding.PCM_SIGNED, 44100, 16, 1, 2,
			44100, false, 5); // set Silent Remover Option
	FilterBankPreprocessing fbp = new FilterBankPreprocessing();
	WindowBasedSegmentation aers = new WindowBasedSegmentation(3, 44100);
	ExtClassification aerc = null;
	String path;

	public AudioEmotionRecognizer(ExtClassification classifier, String filepath, long userID) {
		super(userID);
		aerc = classifier;
		
		this.path = filepath;
	}

	// data from llcrawdatabuffer

	@Override
	public ContextLabel recognize(EmotionDataJH jh, String timeStamp) {
		ContextLabel emotion = ContextType.Emotion.getBasicLabel(userID, timeStamp);
		try {
			double[][] mfccPreprocessing = null;
			AudioInputStream[] devideSegmented = aers.divideInputStream(jh.getAIS(), 3);
			Vector<double[]> featureVector = new Vector<double[]>();

			for (int k = 0; k < devideSegmented.length; k++) {

				try {
					mfccPreprocessing = fbp.getMfcc(devideSegmented[k]);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					logger.error(e);
				}
				double[] featureVT = fe.getTimeDomainFeatures(mfccPreprocessing);
				featureVector.add(featureVT);
			}

			double[] timeDomainFeatureVt = fe.convertVector(featureVector);

			if(emoLabel[aerc.classify(timeDomainFeatureVt)] != null)emotion.setLabel(emoLabel[aerc.classify(timeDomainFeatureVt)]);

			if(verbose)logger.info("EMOJH individual output : " + userID + "\t" + emotion.getLabel() + "\t" + timeStamp);


			return emotion;
		} catch (Exception e) {
			logger.error(e);
		}
		return null;

	}

	public AudioEmotionRecognizer(long userID) {
		super(userID);
	}

	@Override
	public RecognizerType getType() {
		// TODO Auto-generated method stub
		return RecognizerType.SER;
	}

	@Override
	public void ConsumeData(DeviceType it, DeviceData obj) {
		// TODO Auto-generated method stub
		if (it.equals(DeviceType.SmartPhone)) {
			SmartphoneData data = (SmartphoneData) obj;
			timeStamp = data.getTimeStamp();
			userID = data.getUserID();
			// emoJHinput = silentRemover.preprocessing(data); //Audio Input
			// Stream for removing silent
			if (data.getAudioSensoryData() != null) {
				AudioInputStream preprocessed = silentRemover.preprocessing(data); // Audio Input Stream for removing silent

				if (preprocessed != null) {
					abm = new AudioBufferManagement(preprocessed.getFormat()); // AudioBufferManagement for accumulating Audio Buffer

					buffer = abm.accumulateData(buffer, preprocessed);
					if (buffer != null) {
						//inputData = aers.segmentation(buffer);
						if(aers.segmentation(buffer) != null)
							setData(new EmotionDataJH(aers.segmentation(buffer), timeStamp));
						buffer = aers.returnRemainedData(buffer);
					}
				}
			}

		}
	}

	
/*
	@Override
	public Runnable getRunnable(String timeStamp, LLCUnifier unifier) {
		// TODO Auto-generated method stub
		return new EmoJHRunnable(unifier, this);
	}

	class EmoJHRunnable implements Runnable {
		LLCUnifier unifier;
		AudioEmotionRecognizer cla;

		public EmoJHRunnable(LLCUnifier unifier, AudioEmotionRecognizer cla) {
			this.unifier = unifier;
			this.cla = cla;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			if (cla.isThreasholdReached())
				unifier.push(cla.recognize(inputData, timeStamp), RecognizerType.SER);
			else {
				if(verbose)logger.info(userID + "\t" + "NoEmotion" + "\t" + timeStamp);
				unifier.push(new ContextLabel(userID, "NoEmotion", timeStamp, ContextType.Emotion), RecognizerType.SER);
			}
		}

	}
*/
}


<|start_filename|>supporting-layer/descriptive-analytics/src/assets/js/feedback_activities.js<|end_filename|>
AmCharts.makeChart("feedback_activites_chartdiv",
				{
					"type": "serial",
					"pathToImages": "http://cdn.amcharts.com/lib/3/images/",
					"categoryField": "category",
					"rotate": true,
					"startDuration": 1,
					"categoryAxis": {
						"gridPosition": "start"
					},
					"trendLines": [],
					"graphs": [
						{
							"balloonText": "[[title]] of [[category]]:[[value]]",
							"fillAlphas": 1,						
							"title": "Negative",
							"type": "column",
							"valueField": "Negative"
						},
						{
							"balloonText": "[[title]] of [[category]]:[[value]]",
							"fillAlphas": 1,
							"title": "Positive",
							"type": "column",
							"valueField": "Positive"
						}
					],
					"guides": [],
					"valueAxes": [
						{
							"id": "activities_feedback",
							"stackType": "regular",
							"title": ""
						}
					],
					"allLabels": [],
					"balloon": {},
					"legend": {
						"periodValueText": "Total : [[value.sum]]",
						"useGraphSettings": true,
						"valueAlign": "left"
					},
					
					"dataProvider": [
						{
							"category": "Walking",
							"Negative": 8,
							"Positive": 5
						},
						{
							"category": "Running",
							"Negative": 6,
							"Positive": 7
						},
						{
							"category": "Biking",
							"Negative": 2,
							"Positive": 3
						}
					]
				}
			);

<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/restservices/RestServices.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Kang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.mm.icl.llc.restservices;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.servlet.ServletContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.uclab.mm.icl.MainServlet;
import org.uclab.mm.icl.llc.AR.var.KinectARClassification;
import org.uclab.mm.icl.llc.AR.var.KinectARFeatureExtraction4;
import org.uclab.mm.icl.llc.config.DeviceType;
import org.uclab.mm.icl.utils.TimeUtil;
import java.lang.reflect.Type;

/**
 * Rest services of LLCA and HLCA. Need to be seperated when modularized
 * @author Nailbrainz
 *
 */
@Path("/llc")
public class RestServices {
	private final static Logger logger = Logger.getLogger(RestClients.class);
	
	
	
	/**
	 * Rest endpoint for testing.
	 * 
	 * @return alive message
	 * @throws JSONException
	 */
	@Path("/start")
	@GET
	public Response convertFtoCfromInput() throws JSONException {
		logger.info("ICL Running!!");
		return null;
	}

	/**
	 * receives the data from Kinect
	 * @param incomingData kinect skeleton data (Json formated string)
	 * @return status of the update
	 */
	@POST
	@Path("/update")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response updateKinect(InputStream incomingData) {
		logger.info("update endpoint called");
		StringBuilder crunchifyBuilder = null;
		synchronized (this) {
			crunchifyBuilder = new StringBuilder();

			String line = null;
			try {
				BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
				while ((line = in.readLine()) != null) {
					crunchifyBuilder.append(line);
				}
			} catch (Exception e) {
				logger.error("Error at rcvd string stream from Kinect!");
				logger.error(e);
			}
		}
		if (MainServlet.server == null) {
			logger.error("Main server null");
		} else {
			try {
				//MainServlet.server.getUser(userID).fillBuffer(DataType.Kinect, crunchifyBuilder.toString());
				JSONObject obj = new JSONObject(crunchifyBuilder.toString());
				MainServlet.server.RouteData(DeviceType.Kinect, obj.getString("data"));
			} catch (Exception e) {
				logger.error(e);
			}
		}

		JSONObject ret = new JSONObject();
		ret.put("response", "success");
		return Response.status(200).entity(ret.toString()).type(MediaType.APPLICATION_JSON).build();
	}

	String timeStamp = "";

	

	static AtomicBoolean lock = new AtomicBoolean(true);

	
	/**
	 * This function update the low level context label into HLC tdb.
	 * @param incomingData JSON data, which contains low level labels
	 * @return status of the update
	 */
	@POST
	@Path("/updatellc")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response updateLLC(InputStream incomingData) {
		//
		//
		//
		while (!lock.get()) {
			lock.set(false);
		}
		StringBuilder crunchifyBuilder = new StringBuilder();
		String line = null;
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));

			while ((line = in.readLine()) != null) {
				crunchifyBuilder.append(line);
			}
		} catch (Exception e) {
			logger.error("Error at parsing llc from LLCA, in HLCA");
			logger.error(e);
		}
		lock.set(true);
		JSONObject input = new JSONObject(crunchifyBuilder.toString());
		String label = input.getString("label");
		String userID = input.getString("userID");
		String timeStamp = input.getString("timeStamp");

		logger.info("------------HLCA server received change in the llc----------");
		logger.info(label + "   " + userID + "    " + timeStamp);
		logger.info("---------------------------------------------------------------");
		
		
		
		
		TimeUtil util = new TimeUtil();
		//MainServlet.sserver.mapLLC(label, userID, util.parseString(timeStamp));
		JSONObject retJson = new JSONObject();
		retJson.put("response", "success");
		
		return Response.status(200).entity(retJson.toString()).type(MediaType.APPLICATION_JSON).build();
		// return Response.ok(retJson, MediaType.APPLICATION_JSON).build();
		// return
		// return Response.status(200).entity("Mapping LLC Successful").build();
	}

	
	/**
	 * This function update the HLC label into TDB
	 * @param incomingData JSON data, which contains the HLC labels
	 * @return status of the update
	 */
	@POST
	@Path("/updatehlc")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response updateHLC(InputStream incomingData) {
		
		
		StringBuilder crunchifyBuilder = new StringBuilder();
		String line = null;
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));

			while ((line = in.readLine()) != null) {
				crunchifyBuilder.append(line);
			}
		} catch (Exception e) {
			logger.error(e);
		}
		/*
		 * Scanner scan = null; scan = new
		 * Scanner(crunchifyBuilder.toString()).useDelimiter(",|\n"); String
		 * label = scan.next(); String userID = scan.next(); String timeStamp =
		 * scan.next();
		 */
		JSONObject input = new JSONObject(crunchifyBuilder.toString());
		String label = input.getString("label");
		String userID = input.getString("userID");
		String timeStamp = input.getString("timeStamp");

		logger.info("------------LLCA received change in the hlc----------");
		logger.info(label + "   " + userID + "    " + timeStamp);
		logger.info("---------------------------------------------------------------");
		/*
		 * FileUtil.WriteHLCLog(
		 * "------------Restful server received change in the llc----------");
		 * FileUtil.WriteHLCLog(label + "   " + userID + "    " + timeStamp);
		 * FileUtil.WriteHLCLog(
		 * "---------------------------------------------------------------");
		 */
		TimeUtil util = new TimeUtil();
		System.out.println("Null ? " + label + " and " + userID + " and " + timeStamp);
		//MainServlet.sserver.mapLLC(label, userID, util.parseString(timeStamp));
		JSONObject retJson = new JSONObject();
		retJson.put("response", "success");
		return Response.status(200).entity(retJson.toString()).type(MediaType.APPLICATION_JSON).build();
		// return Response.ok(retJson, MediaType.APPLICATION_JSON).build();
		// return
		// return Response.status(200).entity("Mapping LLC Successful").build();
	}

	
	static final public boolean isFromMao = false;
	
	@POST
	@Path("/updatesensordata")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response updateSensorData(InputStream incomingData) {
		
		StringBuilder data = new StringBuilder();
		String line = null;
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));

			while ((line = in.readLine()) != null) {
				data.append(line);
			}
		} catch (Exception e) {
			System.out.println("Error Parsing: - ");
		}
		
		if(isFromMao){
			
			
			JSONObject wrapper = new JSONObject(data);
			for(DeviceType datatype : DeviceType.values()){ //for each datatype
				String contentsLabel = "contentBody_"+datatype.getValue(); //the value should match with the number defined in DCL
				if(wrapper.getString(contentsLabel) != null){ //check whether the data exists for each datatype
					MainServlet.server.RouteData(datatype, wrapper.getString(contentsLabel)); //byte encoded string
				}
				
			}
			
			
			JSONObject retJson = new JSONObject();
			retJson.put("response", "success");
			return Response.status(200).entity(retJson.toString()).type(MediaType.APPLICATION_JSON).build();
		}else{
			
			MainServlet.server.RouteData(DeviceType.SmartPhone, data.toString());
			JSONObject retJson = new JSONObject();
			retJson.put("response", "success");
			return Response.status(200).entity(retJson.toString()).type(MediaType.APPLICATION_JSON).build();
		}
		//
		//
		//
		
		// return Response.ok(retJson, MediaType.APPLICATION_JSON).build();
		// return
		// return Response.status(200).entity("Mapping LLC Successful").build();
	}
/*
	@GET
	@Path("/VARService/version")
	@Produces(MediaType.APPLICATION_JSON)
	public Response version() {
		JSONObject ret = new JSONObject();
		ret.put("result", "VARAPI version 1.0!");
		return Response.status(200).entity(ret.toString()).type(MediaType.APPLICATION_JSON).build();
	}

	@POST
	@Path("/VARService/classifyWithDefaultModel")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public String classifyWithDefaultModel(@Context ServletContext context, @FormParam("input") String sInput)
			throws IOException {
		String modelFile = context.getRealPath("/J48VAR.model");

		KinectARFeatureExtraction4 featureExtractor = new KinectARFeatureExtraction4();
		KinectARClassification classifier = new KinectARClassification(modelFile);

		Gson gson = new Gson();
		Type listType = new TypeToken<ArrayList<ArrayList<Float>>>() {
		}.getType();
		ArrayList<ArrayList<Float>> listInput = gson.fromJson(sInput, listType);

		if (listInput == null)
			return "{\"result\":\"ERROR\", \"message\":\"Input data is null\"}";

		if (listInput.size() != 30)
			return "{\"result\":\"ERROR\", \"message\":\"Wrong data size\"}";

		if (listInput.get(0).size() != 75)
			return "{\"result\":\"ERROR\", \"message\":\"Wrong data size\"}";

		double inputD[][] = new double[30][75];

		for (int i = 0; i < 30; i++)
			for (int j = 0; j < 75; j++)
				inputD[i][j] = listInput.get(i).get(j);

		featureExtractor.setInputData(inputD);
		double[] inputFeatures = featureExtractor.extractFeatures();
		String label = classifier.Classify(inputFeatures);

		return "{\"result\":\"OK\", \"label\":\"" + label + "\"}";
	}

	@POST
	@Path("/VARService/classifyWithCustomIndex")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public String classifyWithCustomIndex(@Context ServletContext context, @FormParam("input") String sInput,
			@FormParam("index") String sIndex) throws IOException {

		String modelFile = context.getRealPath("/J48VAR.model");

		KinectARFeatureExtraction4 featureExtractor = new KinectARFeatureExtraction4();
		KinectARClassification classifier = new KinectARClassification(modelFile);

		Gson gson = new Gson();
		Type listTypeDouble = new TypeToken<ArrayList<ArrayList<Double>>>() {
		}.getType();
		ArrayList<ArrayList<Double>> listInput = gson.fromJson(sInput, listTypeDouble);

		Type listTypeInteger = new TypeToken<ArrayList<ArrayList<Integer>>>() {
		}.getType();
		ArrayList<ArrayList<Integer>> listIndex = gson.fromJson(sIndex, listTypeInteger);

		if (listInput == null)
			return "{\"result\":\"ERROR\", \"message\":\"Input data is null\"}";

		if (listInput.size() != 30)
			return "{\"result\":\"ERROR\", \"message\":\"Wrong data size\"}";

		if (listInput.get(0).size() != 75)
			return "{\"result\":\"ERROR\", \"message\":\"Wrong data size\"}";

		if (listIndex == null)
			return "{\"result\":\"ERROR\", \"message\":\"Index is null\"}";

		if (listIndex.size() != 4)
			return "{\"result\":\"ERROR\", \"message\":\"Wrong index size\"}";

		if (listIndex.get(0).size() != 70)
			return "{\"result\":\"ERROR\", \"message\":\"Wrong index size\"}";

		double inputD[][] = new double[30][75];

		for (int i = 0; i < 30; i++)
			for (int j = 0; j < 75; j++)
				inputD[i][j] = listInput.get(i).get(j);

		featureExtractor.setIndex(listIndex);
		featureExtractor.setInputData(inputD);
		double[] inputFeatures = featureExtractor.extractFeatures();
		String label = classifier.Classify(inputFeatures);

		return "{\"result\":\"OK\", \"label\":\"" + label + "\"}";
	}

		/*
		@POST
		@Path("/VARService/uploadCustomModel")
		@Produces(MediaType.APPLICATION_JSON)
		@Consumes(MediaType.MULTIPART_FORM_DATA)
		public String uploadCustomModel(@Context ServletContext context, 
				@FormDataParam("model") InputStream uploadedInputStream,
				@FormDataParam("model") FormDataContentDisposition fileDetail) throws IOException {
			try {  
				FileOutputStream out = new FileOutputStream(new File("customModel.model"));  
				int read = 0;  
				byte[] bytes = new byte[1024];  
				out = new FileOutputStream(new File("customModel.model"));  
				while ((read = uploadedInputStream.read(bytes)) != -1) {  
					out.write(bytes, 0, read);  
				}  
				out.flush();  
				out.close();  
				return "{\"result\":\"OK\"}";
			} catch (IOException e) {
				e.printStackTrace();
			}  
			return "{\"result\":\"Failed\"}";
		}
		
		@POST
		@Path("/VARService/classifyWithCustomModel")
		@Produces(MediaType.APPLICATION_JSON)
		@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
		public String classifyWithCustomModel(@Context ServletContext context, 
				@FormParam("input") String sInput,
				@FormParam("index") String sIndex) throws IOException {
			
			String modelFile = context.getRealPath("customModel.model");
			
			KinectARFeatureExtraction4 featureExtractor = new KinectARFeatureExtraction4();
			KinectARClassification classifier = new KinectARClassification(modelFile);
			
			Gson gson = new Gson();
		    Type listTypeDouble = new TypeToken<ArrayList<ArrayList<Double>>>(){}.getType();
		    ArrayList<ArrayList<Double>> listInput = gson.fromJson(sInput, listTypeDouble);
		    
		    Type listTypeInteger = new TypeToken<ArrayList<ArrayList<Integer>>>(){}.getType();
		    ArrayList<ArrayList<Integer>> listIndex = gson.fromJson(sIndex, listTypeInteger);
		    
		    if (listInput == null)
		    	return "{\"result\":\"ERROR\", \"message\":\"Input data is null\"}";
		    
		    if (listInput.size() != 30)
		    	return "{\"result\":\"ERROR\", \"message\":\"Wrong data size\"}";
		    
		    if (listInput.get(0).size() != 75)
		    	return "{\"result\":\"ERROR\", \"message\":\"Wrong data size\"}";
		    
		    if (listIndex == null)
		    	return "{\"result\":\"ERROR\", \"message\":\"Index is null\"}";
		    
		    if (listIndex.size() != 4)
		    	return "{\"result\":\"ERROR\", \"message\":\"Wrong index size\"}";
		    
		    if (listIndex.get(0).size() != 70)
		    	return "{\"result\":\"ERROR\", \"message\":\"Wrong index size\"}";
		    
			double inputD[][] = new double[30][75];
			
			for (int i = 0; i < 30; i++)
				for (int j = 0; j < 75; j++)
					inputD[i][j] = listInput.get(i).get(j);
			
			featureExtractor.setIndex(listIndex);
			featureExtractor.setInputData(inputD);
			double[] inputFeatures = featureExtractor.extractFeatures();
			String label = classifier.Classify(inputFeatures);
			
			return "{\"result\":\"OK\", \"label\":\"" + label + "\"}";
		}*/
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/utils/ObjectSizer.java<|end_filename|>
package org.uclab.mm.icl.utils;

public final class ObjectSizer {

	/**
	 * Return the approximate size in bytes, and return zero if the class
	 * has no default constructor.
	 *
	 * @param aClass
	 *            refers to a class which has a no-argument constructor.
	 */
	public long getObjectSize(Class aClass) {
		long result = 0;

		// if the class does not have a no-argument constructor, then
		// inform the user and return 0.
		try {
			aClass.getConstructor(new Class[] {});
		} catch (NoSuchMethodException ex) {
			log(aClass + " does not have a no-argument constructor.");
			return result;
		}

		// this array will simply hold a bunch of references, such that
		// the objects cannot be garbage-collected
		Object[] objects = new Object[fSAMPLE_SIZE];

		// build a bunch of identical objects
		try {
			Object throwAway = aClass.newInstance();

			long startMemoryUse = getMemoryUse();
			for (int idx = 0; idx < objects.length; ++idx) {
				objects[idx] = aClass.newInstance();
			}
			long endMemoryUse = getMemoryUse();

			float approximateSize = (endMemoryUse - startMemoryUse) / 100f;
			result = Math.round(approximateSize);
		} catch (Exception ex) {
			log("Cannot create object using " + aClass);
		}
		return result;
	}

	// PRIVATE
	private int fSAMPLE_SIZE = 100;
	private long fSLEEP_INTERVAL = 100;

	private void log(String aMessage) {
		System.out.println(aMessage);
	}

	private long getMemoryUse() {
		putOutTheGarbage();
		long totalMemory = Runtime.getRuntime().totalMemory();
		putOutTheGarbage();
		long freeMemory = Runtime.getRuntime().freeMemory();
		return (totalMemory - freeMemory);
	}

	private void putOutTheGarbage() {
		collectGarbage();
		collectGarbage();
	}

	private void collectGarbage() {
		try {
			System.gc();
			Thread.currentThread().sleep(fSLEEP_INTERVAL);
			System.runFinalization();
			Thread.currentThread().sleep(fSLEEP_INTERVAL);
		} catch (InterruptedException ex) {
			ex.printStackTrace();
		}
	}
}

<|start_filename|>knowledge-curation-layer/i-kat/src/main/java/org/uclab/mm/kcl/edkat/datamodel/dclcommunication/SituationEvent.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.kcl.edkat.datamodel.dclcommunication;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class SituationEvent implements Serializable {

	private String SituationID;
	private List<SituationConditions> ListSConditions = new ArrayList<SituationConditions>();
	public String getSituationID() {
		return SituationID;
	}
	public void setSituationID(String situationID) {
		SituationID = situationID;
	}
	public List<SituationConditions> getListSConditions() {
		return ListSConditions;
	}
	public void setListSConditions(List<SituationConditions> listSConditions) {
		ListSConditions = listSConditions;
	}
	
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/dc/PhysiologicalFactors.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.dc;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Date;
import java.util.GregorianCalendar;
/**
 *
 * @author Taqdir
 */
@Entity
public class PhysiologicalFactors implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    
    private Long physiologicalFactorId;
    private Long userId;
    private float weight;
    private float height;
    //private GregorianCalendar date; //updated
    private String date;
    private float idealWeight;
    private float targetWeight;
    
    
    
    

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof PhysiologicalFactors)) {
            return false;
        }
        PhysiologicalFactors other = (PhysiologicalFactors) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.dc.PhysiologicalFactors[ id=" + id + " ]";
    }

    /**
     * @return the physiologicalFactorId
     */
    public Long getPhysiologicalFactorId() {
        return physiologicalFactorId;
    }

    /**
     * @param physiologicalFactorId the physiologicalFactorId to set
     */
    public void setPhysiologicalFactorId(Long physiologicalFactorId) {
        this.physiologicalFactorId = physiologicalFactorId;
    }

    /**
     * @return the userId
     */
    public Long getUserId() {
        return userId;
    }

    /**
     * @param userId the userId to set
     */
    public void setUserId(Long userId) {
        this.userId = userId;
    }

    /**
     * @return the weight
     */
    public float getWeight() {
        return weight;
    }

    /**
     * @param weight the weight to set
     */
    public void setWeight(float weight) {
        this.weight = weight;
    }

   

    /**
     * @return the phyFactorDate updated
     */
    public String getDate() {
        return date;
    }

    /**
     * @param date the phyFactorDate to set
     */
    public void setDate(String date) {
        this.date = date;
    }

    /**
     * @return the height
     */
    public float getHeight() {
        return height;
    }

    /**
     * @param height the height to set
     */
    public void setHeight(float height) {
        this.height = height;
    }

    /**
     * @return the idealWeight
     */
    public float getIdealWeight() {
        return idealWeight;
    }

    /**
     * @param idealWeight the idealWeight to set
     */
    public void setIdealWeight(float idealWeight) {
        this.idealWeight = idealWeight;
    }

    /**
     * @return the targetWeight
     */
    public float getTargetWeight() {
        return targetWeight;
    }

    /**
     * @param targetWeight the targetWeight to set
     */
    public void setTargetWeight(float targetWeight) {
        this.targetWeight = targetWeight;
    }
    
}


<|start_filename|>supporting-layer/descriptive-analytics/src/assets/css/main.css<|end_filename|>
/*
*   Yukon Admin
*   author: tzd-themes
*
*   Content:
*       1. variables/mixins
*       2. bootstrap framework custom styles
*       3. main styles
*       4. main menu
*       5. header
*       6. breadcrumbs
*       7. plugins
*       8. pages
*       9. css3 animations
*      10. ---
*      11. style switcher
*      12. themes
*      13. media queries
*      14. demo classes
*
*/
/* -- 1. Variables/Mixins -- */
/* used when generating css stylesheet */
/* -- 2. Bootstrap Framework Custom Styles -- */
/* remove border radius */
.form-control,
.label,
.panel-group,
.panel-group .panel,
.list-group-item:first-child,
.list-group-item:last-child,
.tooltip-inner,
.nav-tabs > li > a {
  -webkit-border-radius: 0 !important;
  -moz-border-radius: 0 !important;
  border-radius: 0 !important;
}

/* alerts */
.alert {
  border: none;
  color: #ffffff;
  text-shadow: none;
  padding: 10px 15px;
  background: #f5f5f5;
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  border-radius: 0;
}
.alert .alert-link {
  font-weight: normal;
  color: #ffffff;
  text-decoration: underline;
}
.alert .alert-link:hover {
  text-decoration: none;
}
.alert.alert-info {
  background: #35b494;
}
.alert.alert-danger {
  background: #d83b4b;
}
.alert.alert-success {
  background: #87be4a;
}
.alert.alert-warning {
  background: #f6b738;
}
.alert.alert-dismissable .close {
  opacity: 0.4;
  filter: alpha(opacity= 40 );
}
/* buttons */
.btn {
  -webkit-transition: all 275ms ease-in;
  transition: all 275ms ease-in;
}
.btn.active,
.btn:active {
  -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.125);
  -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.125);
  box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.125);
}
.btn-default {
  color: #333333;
  background-color: #ffffff;
  border-color: #cccccc;
}
.btn-default:hover,
.btn-default:focus,
.btn-default.focus,
.btn-default:active,
.btn-default.active,
.open > .dropdown-toggle.btn-default {
  color: #333333;
  background-color: #ffffff;
  border-color: #e0e0e0;
}
.btn-default:active,
.btn-default.active,
.open > .dropdown-toggle.btn-default {
  background-image: none;
}
.btn-default.disabled,
.btn-default[disabled],
fieldset[disabled] .btn-default,
.btn-default.disabled:hover,
.btn-default[disabled]:hover,
fieldset[disabled] .btn-default:hover,
.btn-default.disabled:focus,
.btn-default[disabled]:focus,
fieldset[disabled] .btn-default:focus,
.btn-default.disabled.focus,
.btn-default[disabled].focus,
fieldset[disabled] .btn-default.focus,
.btn-default.disabled:active,
.btn-default[disabled]:active,
fieldset[disabled] .btn-default:active,
.btn-default.disabled.active,
.btn-default[disabled].active,
fieldset[disabled] .btn-default.active {
  background-color: #ffffff;
  border-color: #cccccc;
}
.btn-default .badge {
  color: #ffffff;
  background-color: #333333;
}
.btn-default.btn-outline {
  color: #ffffff;
  background: #ffffff;
  border-width: 2px;
}
.btn-default.btn-outline:hover,
.btn-default.btn-outline:focus,
.btn-default.btn-outline.focus,
.btn-default.btn-outline:active,
.btn-default.btn-outline.active {
  border-color: #adadad;
}
.btn-default.btn-outline {
  color: #333;
}
.btn-primary {
  color: #ffffff;
  background-color: #3bafda;
  border-color: #3bafda;
}
.btn-primary:hover,
.btn-primary:focus,
.btn-primary.focus,
.btn-primary:active,
.btn-primary.active,
.open > .dropdown-toggle.btn-primary {
  color: #ffffff;
  background-color: #5dbde0;
  border-color: #5dbde0;
}
.btn-primary:active,
.btn-primary.active,
.open > .dropdown-toggle.btn-primary {
  background-image: none;
}
.btn-primary.disabled,
.btn-primary[disabled],
fieldset[disabled] .btn-primary,
.btn-primary.disabled:hover,
.btn-primary[disabled]:hover,
fieldset[disabled] .btn-primary:hover,
.btn-primary.disabled:focus,
.btn-primary[disabled]:focus,
fieldset[disabled] .btn-primary:focus,
.btn-primary.disabled.focus,
.btn-primary[disabled].focus,
fieldset[disabled] .btn-primary.focus,
.btn-primary.disabled:active,
.btn-primary[disabled]:active,
fieldset[disabled] .btn-primary:active,
.btn-primary.disabled.active,
.btn-primary[disabled].active,
fieldset[disabled] .btn-primary.active {
  background-color: #3bafda;
  border-color: #3bafda;
}
.btn-primary .badge {
  color: #3bafda;
  background-color: #ffffff;
}
.btn-primary.btn-outline {
  color: #3bafda;
  background: #ffffff;
  border-width: 2px;
}
.btn-primary.btn-outline:hover,
.btn-primary.btn-outline:focus,
.btn-primary.btn-outline.focus,
.btn-primary.btn-outline:active,
.btn-primary.btn-outline.active {
  border-color: #228eb6;
}
.btn-success {
  color: #ffffff;
  background-color: #8cc152;
  border-color: #8cc152;
}
.btn-success:hover,
.btn-success:focus,
.btn-success.focus,
.btn-success:active,
.btn-success.active,
.open > .dropdown-toggle.btn-success {
  color: #ffffff;
  background-color: #a0cc70;
  border-color: #a0cc70;
}
.btn-success:active,
.btn-success.active,
.open > .dropdown-toggle.btn-success {
  background-image: none;
}
.btn-success.disabled,
.btn-success[disabled],
fieldset[disabled] .btn-success,
.btn-success.disabled:hover,
.btn-success[disabled]:hover,
fieldset[disabled] .btn-success:hover,
.btn-success.disabled:focus,
.btn-success[disabled]:focus,
fieldset[disabled] .btn-success:focus,
.btn-success.disabled.focus,
.btn-success[disabled].focus,
fieldset[disabled] .btn-success.focus,
.btn-success.disabled:active,
.btn-success[disabled]:active,
fieldset[disabled] .btn-success:active,
.btn-success.disabled.active,
.btn-success[disabled].active,
fieldset[disabled] .btn-success.active {
  background-color: #8cc152;
  border-color: #8cc152;
}
.btn-success .badge {
  color: #8cc152;
  background-color: #ffffff;
}
.btn-success.btn-outline {
  color: #8cc152;
  background: #ffffff;
  border-width: 2px;
}
.btn-success.btn-outline:hover,
.btn-success.btn-outline:focus,
.btn-success.btn-outline.focus,
.btn-success.btn-outline:active,
.btn-success.btn-outline.active {
  border-color: #6d9d38;
}
.btn-info {
  color: #ffffff;
  background-color: #37bc9b;
  border-color: #37bc9b;
}
.btn-info:hover,
.btn-info:focus,
.btn-info.focus,
.btn-info:active,
.btn-info.active,
.open > .dropdown-toggle.btn-info {
  color: #ffffff;
  background-color: #50ccad;
  border-color: #50ccad;
}
.btn-info:active,
.btn-info.active,
.open > .dropdown-toggle.btn-info {
  background-image: none;
}
.btn-info.disabled,
.btn-info[disabled],
fieldset[disabled] .btn-info,
.btn-info.disabled:hover,
.btn-info[disabled]:hover,
fieldset[disabled] .btn-info:hover,
.btn-info.disabled:focus,
.btn-info[disabled]:focus,
fieldset[disabled] .btn-info:focus,
.btn-info.disabled.focus,
.btn-info[disabled].focus,
fieldset[disabled] .btn-info.focus,
.btn-info.disabled:active,
.btn-info[disabled]:active,
fieldset[disabled] .btn-info:active,
.btn-info.disabled.active,
.btn-info[disabled].active,
fieldset[disabled] .btn-info.active {
  background-color: #37bc9b;
  border-color: #37bc9b;
}
.btn-info .badge {
  color: #37bc9b;
  background-color: #ffffff;
}
.btn-info.btn-outline {
  color: #37bc9b;
  background: #ffffff;
  border-width: 2px;
}
.btn-info.btn-outline:hover,
.btn-info.btn-outline:focus,
.btn-info.btn-outline.focus,
.btn-info.btn-outline:active,
.btn-info.btn-outline.active {
  border-color: #298d74;
}
.btn-warning {
  color: #ffffff;
  background-color: #f6bb42;
  border-color: #f6bb42;
}
.btn-warning:hover,
.btn-warning:focus,
.btn-warning.focus,
.btn-warning:active,
.btn-warning.active,
.open > .dropdown-toggle.btn-warning {
  color: #ffffff;
  background-color: #f8c969;
  border-color: #f8c969;
}
.btn-warning:active,
.btn-warning.active,
.open > .dropdown-toggle.btn-warning {
  background-image: none;
}
.btn-warning.disabled,
.btn-warning[disabled],
fieldset[disabled] .btn-warning,
.btn-warning.disabled:hover,
.btn-warning[disabled]:hover,
fieldset[disabled] .btn-warning:hover,
.btn-warning.disabled:focus,
.btn-warning[disabled]:focus,
fieldset[disabled] .btn-warning:focus,
.btn-warning.disabled.focus,
.btn-warning[disabled].focus,
fieldset[disabled] .btn-warning.focus,
.btn-warning.disabled:active,
.btn-warning[disabled]:active,
fieldset[disabled] .btn-warning:active,
.btn-warning.disabled.active,
.btn-warning[disabled].active,
fieldset[disabled] .btn-warning.active {
  background-color: #f6bb42;
  border-color: #f6bb42;
}
.btn-warning .badge {
  color: #f6bb42;
  background-color: #ffffff;
}
.btn-warning.btn-outline {
  color: #f6bb42;
  background: #ffffff;
  border-width: 2px;
}
.btn-warning.btn-outline:hover,
.btn-warning.btn-outline:focus,
.btn-warning.btn-outline.focus,
.btn-warning.btn-outline:active,
.btn-warning.btn-outline.active {
  border-color: #efa50b;
}
.btn-danger {
  color: #ffffff;
  background-color: #da4453;
  border-color: #da4453;
}
.btn-danger:hover,
.btn-danger:focus,
.btn-danger.focus,
.btn-danger:active,
.btn-danger.active,
.open > .dropdown-toggle.btn-danger {
  color: #ffffff;
  background-color: #e16672;
  border-color: #e16672;
}
.btn-danger:active,
.btn-danger.active,
.open > .dropdown-toggle.btn-danger {
  background-image: none;
}
.btn-danger.disabled,
.btn-danger[disabled],
fieldset[disabled] .btn-danger,
.btn-danger.disabled:hover,
.btn-danger[disabled]:hover,
fieldset[disabled] .btn-danger:hover,
.btn-danger.disabled:focus,
.btn-danger[disabled]:focus,
fieldset[disabled] .btn-danger:focus,
.btn-danger.disabled.focus,
.btn-danger[disabled].focus,
fieldset[disabled] .btn-danger.focus,
.btn-danger.disabled:active,
.btn-danger[disabled]:active,
fieldset[disabled] .btn-danger:active,
.btn-danger.disabled.active,
.btn-danger[disabled].active,
fieldset[disabled] .btn-danger.active {
  background-color: #da4453;
  border-color: #da4453;
}
.btn-danger .badge {
  color: #da4453;
  background-color: #ffffff;
}
.btn-danger.btn-outline {
  color: #da4453;
  background: #ffffff;
  border-width: 2px;
}
.btn-danger.btn-outline:hover,
.btn-danger.btn-outline:focus,
.btn-danger.btn-outline.focus,
.btn-danger.btn-outline:active,
.btn-danger.btn-outline.active {
  border-color: #bc2534;
}
.btn-group .open .dropdown-toggle,
.input-group .open .dropdown-toggle {
  -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.125);
  -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.125);
  box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.125);
}
.btn-toolbar > .btn,
.btn-toolbar > .btn-group,
.btn-toolbar > .input-group {
  margin-bottom: 5px;
}
/* close */
button.close {
  text-shadow: none;
}
/* dropdowns */
.dropdown-menu {
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  border-radius: 0;
  border-color: rgba(0, 0, 0, 0.2);
  -webkit-box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  -moz-box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  font-size: 13px;
}
.dropdown-menu > li {
  margin: 0 5px;
}
.dropdown-menu > li > a {
  padding: 3px 10px;
}
.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
  background: #eee;
}
/* labels, badges */
.label {
  padding: 2px 4px;
  font-weight: normal;
}
label.label-primary,
.badge.badge-primary,
.label.label-info,
.badge.badge-info,
.label.label-success,
.badge.badge-success,
.label.label-warning,
.badge.badge-warning,
.label.label-danger,
.badge.badge-danger,
.label.label-inverse,
.badge.badge-inverse {
  color: #ffffff;
}
.label.label-primary,
.badge.badge-primary {
  background-color: #3bafda;
}
.label.label-info,
.badge.badge-info {
  background-color: #37bc9b;
}
.label.label-success,
.badge.badge-success {
  background-color: #8cc152;
}
.label.label-warning,
.badge.badge-warning {
  background-color: #f6bb42;
}
.label.label-danger,
.badge.badge-danger {
  background-color: #da4453;
}
/* list group */
.list-group-item {
  border: none;
}
.list-group-item + .list-group-item {
  border-top: 1px solid #eee;
}
.list-group-item.active,
.list-group-item.active:hover,
.list-group-item.active:focus {
  background: #eee;
  color: #222222;
  z-index: auto;
  border-color: #eee;
}
a.list-group-item:hover,
a.list-group-item:focus {
  background: #eee;
}
.list_group_sep .list-group-item {
  border: 1px solid #e8e8e8;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
}
.list_group_sep .list-group-item + .list-group-item {
  margin-top: 4px;
}
.list_group_sep .list-group-item a {
  color: #555;
}
.list_group_sep .progress {
  margin: 4px 0 0;
}
.list_group_sep .list_icon {
  color: #f1c40f;
  font-size: 18px;
}
/* modals */
.modal-header {
  padding: 10px 15px;
}
.modal-header h4 {
  font: 400 18px / 22px "Open Sans", Arial, sans-serif;
}
.modal-content {
  border: none;
  -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.4);
  -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.4);
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.4);
  -webkit-border-radius: 6px;
  -moz-border-radius: 6px;
  border-radius: 6px;
}
.modal-footer {
  text-align: center;
  background: #f8f8f8;
  -webkit-border-radius: 0 0 6px 6px;
  -moz-border-radius: 0 0 6px 6px;
  border-radius: 0 0 6px 6px;
}
.modal-backdrop.in {
  opacity: 0.3;
  filter: alpha(opacity= 30 );
}
/* panel group */
.panel-group .panel {
  padding: 0;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  box-shadow: none;
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  border-radius: 0;
  margin-bottom: 0;
  border: none;
}
.panel-group .panel .panel-heading {
  padding: 0;
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  border-radius: 0;
}
.panel-group .panel .panel-heading .panel-title {
  font: 400 14px / 20px "Open Sans", Arial, sans-serif;
}
.panel-group .panel .panel-heading .panel-title a {
  display: block;
  padding: 10px 15px;
  color: #222222;
  position: relative;
}
.panel-group .panel .panel-heading .panel-title a,
.panel-group .panel .panel-heading .panel-title a:hover,
.panel-group .panel .panel-heading .panel-title a:focus {
  text-decoration: none;
}
.panel-group .panel .panel-heading .panel-title a:after {
  position: absolute;
  top: 20px;
  right: 20px;
  content: '';
  display: block;
  width: 0;
  height: 0;
  border: 4px solid transparent;
  border-top-color: rgba(0, 0, 0, 0.4);
}
.panel-group .panel .panel-heading + .panel-collapse .panel-body {
  font-size: 13px;
  border-top: none;
  padding-top: 0;
  color: #222222;
}
.panel-group .panel + .panel {
  margin-top: 2px;
}
.panel-group .panel.panel-default .panel-heading {
  background: #f6f6f6;
}
.panel-group .panel.panel-success .panel-heading a,
.panel-group .panel.panel-danger .panel-heading a,
.panel-group .panel.panel-warning .panel-heading a,
.panel-group .panel.panel-info .panel-heading a {
  color: #ffffff;
}
.panel-group .panel.panel-success .panel-heading {
  background: #8cc152;
}
.panel-group .panel.panel-danger .panel-heading {
  background: #da4453;
}
.panel-group .panel.panel-warning .panel-heading {
  background: #f6bb42;
}
.panel-group .panel.panel-info .panel-heading {
  background: #37bc9b;
}
.panel-group .panel.panel-active .panel-heading {
  background: #ffffff;
}
.panel-group .panel.panel-active .panel-heading .panel-title a {
  font-weight: 700;
}
.panel-group .panel.panel-active .panel-heading .panel-title a:after {
  border-top-color: transparent;
  border-bottom-color: rgba(0, 0, 0, 0.4);
  top: 14px;
}
/* tables */
.table .cw {
  width: 1%;
  white-space: nowrap;
}
.table .cwr {
  text-align: right;
}
.table .cwc {
  text-align: center;
}
.table-yuk {
  border-collapse: separate;
  border-spacing: 2px;
}
.table-yuk > thead > tr > th {
  font-size: 13px;
  background: #dadfe1;
  border: none;
}
.table-yuk > thead > tr > th,
.table-yuk > thead > tr > td,
.table-yuk > tbody > tr > th,
.table-yuk > tbody > tr > td,
.table-yuk > tfoot > tr > th,
.table-yuk > tfoot > tr > td {
  border-top: none;
}
.table-yuk > tbody > tr:nth-child(2n) > td,
.table-yuk > tbody > tr:nth-child(2n) > th {
  background: #f8f8f8;
}
.table-yuk2 > thead > tr > th {
  font-size: 12px;
  text-transform: uppercase;
  border-bottom: 2px solid #aab2bd;
  vertical-align: middle;
}
.table-yuk2 > tbody > tr:nth-child(2n) > td,
.table-yuk2 > tbody > tr:nth-child(2n) > th {
  background: #f8f8f8;
}
.table-yuk2.bg-fill > tbody > tr > td {
  background: #f5f5f5;
}
/* form */
label {
  font-size: 13px;
  font-weight: normal;
}
legend {
  border-width: 0 0 1px;
  border-style: dashed;
  border-color: #ddd;
  padding-bottom: 6px;
  font-size: 15px;
}
.form-control {
  border-width: 1px;
  border-style: solid;
  border-color: #ddd;
  padding: 6px;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  box-shadow: none;
}
.form-control:-moz-placeholder,
.form-control::-moz-placeholder,
.form-control:-ms-input-placeholder,
.form-control::-webkit-input-placeholder,
.form-control.placeholder {
  color: #bdc3c7;
}
.form-control:focus {
  -webkit-backface-visibility: hidden;
  outline: none;
  -webkit-transition: 0.25s;
  transition: 0.25s;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  box-shadow: none;
  border-color: #168cbe;
}
.form-control[disabled],
.form-control[readonly],
fieldset[disabled] .form-control {
  cursor: not-allowed;
  opacity: 0.4;
  filter: alpha(opacity= 40 );
}
.input-group-addon {
  background-color: #d3d7d7;
  border-color: #d3d7d7;
}
.input-group-addon.input-group-success {
  background-color: #fcfefb;
  border-color: #fcfefb;
}
.input-group-addon.input-group-info {
  background-color: #a7e5d6;
  border-color: #a7e5d6;
}
.input-group-addon.input-group-warning {
  background-color: #ffffff;
  border-color: #ffffff;
}
.input-group-addon.input-group-danger {
  background-color: #ffffff;
  border-color: #ffffff;
}
.input-group-addon.input-group-primary {
  background-color: #fcfefe;
  border-color: #fcfefe;
}
.radio,
.radio-inline,
.checkbox,
.checkbox-inline {
  margin-right: 10px;
}
.radio input,
.radio-inline input,
.checkbox input,
.checkbox-inline input {
  margin-top: 2px;
}
.radio label,
.radio-inline label,
.checkbox label,
.checkbox-inline label {
  display: inline-block;
  font-size: 13px;
  vertical-align: 2px;
  margin: 0;
}
.radio-inline + .radio-inline,
.checkbox-inline + .checkbox-inline {
  margin-left: 0;
}
.req:after {
  content: ' *';
  color: #c0392b;
  font-size: 17px;
  line-height: 15px;
}
.help-block {
  font-size: 12px;
  color: #888;
  margin-bottom: 0;
}
.has-warning .form-control,
.has-error .form-control,
.has-info .form-control,
.has-success .form-control,
.has-warning .form-control:focus,
.has-error .form-control:focus,
.has-info .form-control:focus,
.has-success .form-control:focus {
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  box-shadow: none;
}
.has-warning .form-control {
  border: 1px solid #f6bb42;
}
.has-warning .form-control:focus {
  border-color: #e19b0b;
}
.has-warning .help-block,
.has-warning .control-label,
.has-warning .radio,
.has-warning .checkbox,
.has-warning .radio-inline,
.has-warning .checkbox-inline {
  color: #f6bb42;
}
.has-warning .form-control-feedback {
  color: #f6bb42;
}
.has-error .form-control {
  border: 1px solid #da4453;
}
.has-error .form-control:focus {
  border-color: #af2331;
}
.has-error .help-block,
.has-error .control-label,
.has-error .radio,
.has-error .checkbox,
.has-error .radio-inline,
.has-error .checkbox-inline {
  color: #da4453;
}
.has-error .form-control-feedback {
  color: #da4453;
}
.has-info .form-control {
  border: 1px solid #37bc9b;
}
.has-info .form-control:focus {
  border-color: #26816a;
}
.has-info .help-block,
.has-info .control-label,
.has-info .radio,
.has-info .checkbox,
.has-info .radio-inline,
.has-info .checkbox-inline {
  color: #37bc9b;
}
.has-info .form-control-feedback {
  color: #37bc9b;
}
.has-success .form-control {
  border: 1px solid #8cc152;
}
.has-success .form-control:focus {
  border-color: #659234;
}
.has-success .help-block,
.has-success .control-label,
.has-success .radio,
.has-success .checkbox,
.has-success .radio-inline,
.has-success .checkbox-inline {
  color: #8cc152;
}
.has-success .form-control-feedback {
  color: #8cc152;
}
.has-feedback .form-control-feedback {
  top: auto;
  bottom: 0;
}
.input-group {
  width: 100%;
}
/* grid */
.row + .row {
  margin-top: 30px;
}
.row + .row-sm-sep {
  margin-top: 10px;
}
.row_full {
  margin-left: -25px;
  margin-right: -25px;
  padding: 15px 0;
  background: #ecf0f1;
  border-width: 1px 0;
  border-style: solid;
  border-color: #e2e2e2;
}
/* tabs */
.nav-tabs {
  border-bottom-color: #ddd;
}
.nav-tabs > li {
  margin: 0 2px -1px 0;
  background: none;
}
.nav-tabs > li > a {
  background: #f5f5f5;
  padding: 8px 10px 7px;
  margin: 0;
  border: 1px solid transparent;
}
.nav-tabs > li > a:hover,
.nav-tabs > li > a:focus {
  border: 1px solid transparent;
  background: #e8e8e8;
}
.nav-tabs > li.active > a {
  border-top-color: transparent;
  position: relative;
  padding-bottom: 10px;
}
.nav-tabs > li.active > a,
.nav-tabs > li.active > a:hover,
.nav-tabs > li.active > a:focus {
  background: #fff;
  border-color: #ddd;
  border-bottom-color: #fff;
}
.nav-tabs > li.active > a:before {
  content: '';
  display: block;
  width: 100%;
  left: 0;
  top: -2px;
  height: 2px;
  background: #3bafda;
  position: absolute;
}
.nav-tabs > li.disabled > a,
.nav-tabs > li.disabled > a:hover,
.nav-tabs > li.disabled > a:focus {
  background: #fff;
  color: #999;
}
.nav-tabs.nav-justified > li.active > a {
  padding-bottom: 7px;
}
.nav-tabs.nav-justified > li.disabled > a {
  border-bottom: 1px solid #ddd;
}
.tab-content {
  border-width: 0 1px 1px;
  border-style: solid;
  border-color: #ddd;
  padding: 14px 10px;
}
/* progress bars */
.progress {
  -webkit-border-radius: 2px;
  -moz-border-radius: 2px;
  border-radius: 2px;
}
.progress,
.progress .progress-bar {
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  box-shadow: none;
}
.progress {
  height: 12px;
  overflow: hidden;
  background-color: #ecf0f1;
}
.progress + .help-block {
  margin-top: -18px;
  position: relative;
}
.progress .progress-bar {
  background-color: #3bafda;
  font-size: 11px;
  line-height: 12px;
}
.progress-success .progress-bar,
.progress .progress-bar-success,
.progress-success.progress-striped .progress-bar,
.progress-striped .progress-bar-success {
  background-color: #8cc152;
}
.progress-info .progress-bar,
.progress .progress-bar-info,
.progress-info.progress-striped .progress-bar,
.progress-striped .progress-bar-info {
  background-color: #37bc9b;
}
.progress-danger .progress-bar,
.progress .progress-bar-danger,
.progress-danger.progress-striped .progress-bar,
.progress-striped .progress-bar-danger {
  background-color: #da4453;
}
.progress-warning .progress-bar,
.progress .progress-bar-warning,
.progress-warning.progress-striped .progress-bar,
.progress-striped .progress-bar-warning {
  background-color: #f6bb42;
}
/* tooltips */
.tooltip-inner {
  background-color: rgba(0, 0, 0, 0.9);
}
.tooltip.top .tooltip-arrow {
  border-top-color: rgba(0, 0, 0, 0.9);
}
.tooltip.top-left .tooltip-arrow {
  border-top-color: rgba(0, 0, 0, 0.9);
}
.tooltip.top-right .tooltip-arrow {
  border-top-color: rgba(0, 0, 0, 0.9);
}
.tooltip.right .tooltip-arrow {
  border-right-color: rgba(0, 0, 0, 0.9);
}
.tooltip.left .tooltip-arrow {
  border-left-color: rgba(0, 0, 0, 0.9);
}
.tooltip.bottom .tooltip-arrow {
  border-bottom-color: rgba(0, 0, 0, 0.9);
}
.tooltip.bottom-left .tooltip-arrow {
  border-bottom-color: rgba(0, 0, 0, 0.9);
}
.tooltip.bottom-right .tooltip-arrow {
  border-bottom-color: rgba(0, 0, 0, 0.9);
}
.popover {
  z-index: 1010;
}
/* text */
.text-success {
  color: #8cc152;
}
.text-danger {
  color: #da4453;
}
.text-info {
  color: #37bc9b;
}
.text-warning {
  color: #f6bb42;
}
/* pagination */
.pagination {
  margin: 10px 0;
}
.pagination > li > a,
.pagination > li > span {
  display: inline-block;
  color: #3b73af;
  background-color: #ffffff;
  border: 1px solid #ddd;
  font-family: "Open Sans", sans-serif;
}
.pagination > li > a:hover,
.pagination > li > span:hover,
.pagination > li > a:focus,
.pagination > li > span:focus {
  color: #222222;
  background-color: #eee;
  border-color: #ddd;
}
.pagination > .active > a,
.pagination > .active > span,
.pagination > .active > a:hover,
.pagination > .active > span:hover,
.pagination > .active > a:focus,
.pagination > .active > span:focus {
  color: #222222;
  background-color: #eee;
  border-color: #ddd;
}
/* -- 3. Main Styles -- */
/* fixes */
/* remove webkit inner shadow */
textarea,
input[type="text"],
input[type="email"],
input[type="password"],
input[type="submit"] {
  -webkit-appearance: none;
}
/* webkit extra margin fix */
@media screen and (-webkit-min-device-pixel-ratio: 0) {
  button {
    margin: 0;
  }
}
body,
html {
  height: 100%;
  width: 100%;
}
html {
  overflow-y: scroll;
  overflow-x: hidden;
}
body {
  background: #ffffff;
  color: #222222;
  padding-top: 48px;
  width: 100%;
}
a {
  color: #3b73af;
  cursor: pointer;
}
a,
.btn {
  outline: none !important;
}
a:hover,
.btn:hover,
a:focus,
.btn:focus {
  text-decoration: none;
}
h1 {
  font: 400 36px / 1.1 "Open Sans", Arial, sans-serif;
}
h2 {
  font: 400 30px / 1.1 "Open Sans", Arial, sans-serif;
}
h3 {
  font: 400 26px / 1.1 "Open Sans", Arial, sans-serif;
}
h4 {
  font: 400 20px / 1.1 "Open Sans", Arial, sans-serif;
}
h5 {
  font: 400 16px / 1.1 "Open Sans", Arial, sans-serif;
}
.page_heading {
  margin: 0 0 30px;
  font: 400 26px / 36px "Open Sans", Arial, sans-serif;
}
.page_heading > span {
  display: block;
  font: 400 18px / 22px "Open Sans", Arial, sans-serif;
}
.row_full .page_heading,
.row .page_heading {
  margin: 0;
}
.heading_a {
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  margin: 0 0 15px;
  padding: 0 4px 4px;
}
.heading_a .heading_text {
  font: 400 16px / 22px "Open Sans", Arial, sans-serif;
  color: #333;
  text-transform: uppercase;
}
.heading_a .heading_icon {
  font-size: 16px;
  line-height: 22px;
  margin-right: 4px;
  color: #999;
}
.heading_a + .row {
  margin-top: 20px;
}
.heading_b {
  margin: 0 0 10px;
}
.heading_b .heading_text {
  font: 400 14px / 20px "Open Sans", Arial, sans-serif;
  text-transform: uppercase;
}
.text_hr {
  margin: 10px 0;
  text-align: center;
  position: relative;
}
.text_hr > span {
  display: inline-block;
  font-size: 13px;
  padding: 0 10px;
  background: #fff;
  position: relative;
  z-index: 10;
  color: #555;
}
.text_hr:after {
  position: absolute;
  left: 0;
  top: 11px;
  width: 100%;
  border-top: 1px solid #eee;
  height: 0;
  content: '';
  z-index: 1;
}
/* spacing */
.sepH_a {
  margin-bottom: 10px;
}
.sepH_b {
  margin-bottom: 20px;
}
.sepH_c {
  margin-bottom: 30px;
}
/* info box (dashboard) */
.info_box_var_1 {
  color: #ffffff;
}
.info_box_var_1.box_bg_a {
  background: #37BC9B;
}
.info_box_var_1.box_bg_b {
  background: #DA4453;
}
.info_box_var_1.box_bg_c {
  background: #F6BB42;
}
.info_box_var_1.box_bg_d {
  background: #4A89DC;
}
.info_box_var_1 .info_box_body {
  padding: 10px 20px;
  height: 60px;
  font: 300 32px / 38px "Open Sans", Arial, sans-serif;
  position: relative;
}
.info_box_var_1 .info_box_body .info_box_icon {
  position: absolute;
  right: 20px;
  top: 14px;
  font-size: 32px;
  color: #ffffff;
}
.info_box_var_1 .info_box_footer {
  padding: 4px 20px;
  background: rgba(0, 0, 0, 0.2);
}
/* lists */
.list_a,
.list_b,
.list_c,
.list_d {
  margin: 0;
  padding: 0;
  list-style: none;
}
.list_a li,
.list_b li,
.list_c li,
.list_d li {
  position: relative;
  padding-left: 16px;
}
.list_a li:before,
.list_b li:before,
.list_c li:before,
.list_d li:before {
  position: absolute;
  content: '';
  top: 8px;
  left: 2px;
  width: 5px;
  height: 5px;
  display: block;
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  border-radius: 50%;
}
.list_a li:before {
  background: #3bafda;
}
.list_b li:before {
  background: #f6bb42;
}
.list_c li:before {
  background: #da4453;
}
.list_d li:before {
  background: #8cc152;
}
/* main content */
#main_wrapper {
  padding: 25px 10px 40px;
  background: #ffffff;
}
/* fixed width */
@media only screen and (min-width: 1120px) {
  .fixed_layout {
    background: #fafafa;
  }
  .fixed_layout #page_wrapper {
    width: 1100px !important;
    margin: 0 auto;
    border-width: 0 1px;
    border-style: solid;
    border-color: rgba(0, 0, 0, 0.13);
    min-height: 100%;
    background: #fff;
  }
  .fixed_layout.side_menu_expanded #main_menu {
    -webkit-box-shadow: 4px 0 8px rgba(0, 0, 0, 0.25);
    -moz-box-shadow: 4px 0 8px rgba(0, 0, 0, 0.25);
    box-shadow: 4px 0 8px rgba(0, 0, 0, 0.25);
    border-right-color: transparent;
  }
  .fixed_layout.side_menu_collapsed .container,
  .fixed_layout.side_menu_expanded .container,
  .fixed_layout.side_menu_collapsed .container-fluid,
  .fixed_layout.side_menu_expanded .container-fluid {
    width: 1038px !important;
  }
  .fixed_layout #main_header {
    margin-left: -550px;
    left: 50%;
  }
  .fixed_layout #main_header,
  .fixed_layout #main_header .container,
  .fixed_layout #main_header .container-fluid {
    width: 1100px !important;
  }
  .fixed_layout.side_menu_active #main_menu {
    left: 50%;
    margin-left: -549px;
  }
  .fixed_layout.side_menu_expanded #main_wrapper,
  .fixed_layout.side_menu_expanded #breadcrumbs {
    margin-left: 42px;
  }
  .fixed_layout.side_menu_expanded #main_menu .section_active a.act_nav:before,
  .fixed_layout.side_menu_expanded #main_menu .section_active a.act_nav:after {
    display: none !important;
  }
  .fixed_layout .row_full {
    margin-right: -23px;
  }
}
/* -- 4. Main Menu -- */
#main_menu,
#main_menu .submenu-title,
.menu_toggle {
  display: none;
}
.side_menu_active #main_wrapper,
.side_menu_active #breadcrumbs {
  margin-left: 240px;
}
.side_menu_active #main_menu {
  width: 240px;
  height: 100%;
  position: fixed;
  left: 0;
  top: 48px;
  background: #f5f5f5;
  padding: 0 0 50px;
  display: block;
  border-width: 0 1px 0 0;
  border-style: solid;
  border-color: #e2e2e2;
  z-index: 101;
  
}
.side_menu_active #main_menu ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
.side_menu_active #main_menu ul li a:focus,
.side_menu_active #main_menu ul li a:hover {
  text-decoration: none;
}
.side_menu_active #main_menu .menu_wrapper {
  padding-bottom: 35px;
  height: 100%;
  position: relative;
}
.side_menu_active #main_menu .first_level > a {
  line-height: 26px;
  display: block;
  padding: 6px 10px;
  color: #222222;
}
.side_menu_active #main_menu .first_level > a .first_level_icon {
  margin-right: 6px;
  font-size: 16px;
  vertical-align: -1px;
  min-width: 20px;
  text-align: center;
  display: inline-block;
}
.side_menu_active #main_menu .first_level > a .label {
  position: absolute;
  right: 34px;
  top: 12px;
  min-width: 20px;
  text-align: center;
}
.side_menu_active #main_menu .first_level > a:hover {
  background: rgba(0, 0, 0, 0.06);
}
.side_menu_active #main_menu .first_level ul {
  display: none;
}
.side_menu_active #main_menu .has_submenu > a {
  padding-right: 20px;
}
.side_menu_active #main_menu .has_submenu > ul a {
  display: block;
  padding: 6px 20px;
  font-size: 13px;
  line-height: 18px;
  color: #222222;
}
.side_menu_active #main_menu .has_submenu > ul a:hover {
  background: rgba(0, 0, 0, 0.06);
}
.side_menu_active .menu_toggle {
  position: absolute;
  left: 0;
  bottom: 48px;
  width: 100%;
  color: #fff;
  -webkit-transition: all 400ms ease;
  transition: all 400ms ease;
  cursor: pointer;
  padding: 5px 5px 6px;
  z-index: 102;
  text-align: center;
  display: block;
  border-top: 1px solid rgba(0, 0, 0, 0.04);
  background: rgba(0, 0, 0, 0.02);
}
.side_menu_active .menu_toggle .icon_menu_toggle {
  font-size: 18px;
  color: #999;
  vertical-align: middle;
}
.side_menu_active .menu_toggle:hover {
  background: rgba(0, 0, 0, 0.1);
}
.side_menu_active.side_menu_expanded #main_menu .first_level > a {
  position: relative;
}
.side_menu_active.side_menu_expanded #main_menu .first_level.has_submenu > a:after {
  content: '';
  height: 0;
  width: 0;
  border: 4px solid transparent;
  border-top-color: rgba(0, 0, 0, 0.4);
  position: absolute;
  right: 12px;
  top: 18px;
}
.side_menu_active.side_menu_expanded #main_menu .first_level.has_submenu > ul a.act_nav {
  background: rgba(0, 0, 0, 0.06);
  position: relative;
  color: #222222;
}
.side_menu_active.side_menu_expanded #main_menu .first_level.has_submenu > ul a.act_nav:after {
  position: absolute;
  top: 50%;
  content: '';
  display: block;
  right: 0;
  border: 9px solid transparent;
  width: 0;
  height: 0;
  border-right-color: #fff;
  margin-top: -9px;
}
.side_menu_active.side_menu_expanded #main_menu .first_level .has_submenu ul {
  margin-left: 20px;
}
.side_menu_active.side_menu_expanded #main_menu .first_level.section_active {
  border-bottom: 1px solid #ddd;
}
.side_menu_active.side_menu_expanded #main_menu .first_level.section_active > a {
  background: #444;
  color: #fff;
  margin: 0 -1px;
}
.side_menu_active.side_menu_expanded #main_menu .first_level.section_active > a:after {
  border-bottom-color: rgba(255, 255, 255, 0.9);
  border-top-color: transparent;
  top: 13px;
}
.side_menu_active.side_menu_expanded #main_menu .first_level.section_active > a:hover {
  background: #444;
}
.side_menu_active.side_menu_expanded #main_menu .has_submenu .has_submenu {
  position: relative;
}
.side_menu_active.side_menu_expanded #main_menu .has_submenu .has_submenu > a:after {
  content: '';
  height: 0;
  width: 0;
  border: 4px solid transparent;
  border-top-color: rgba(0, 0, 0, 0.3);
  position: absolute;
  right: 10px;
  top: 14px;
}
.side_menu_active.side_menu_expanded #main_menu .has_submenu .has_submenu.submenu_active > a:after {
  border-bottom-color: rgba(0, 0, 0, 0.3);
  border-top-color: transparent;
  top: 9px;
}
.side_menu_active.side_menu_expanded #main_menu .submenu_active {
  background: rgba(0, 0, 0, 0.05);
}
.side_menu_active.side_menu_collapsed #main_wrapper,
.side_menu_active.side_menu_collapsed #breadcrumbs {
  margin-left: 42px;
}
.side_menu_active.side_menu_collapsed #main_menu {
  width: 42px;
}
.side_menu_active.side_menu_collapsed #main_menu .first_level > a {
  padding: 6px 10px;
}
.side_menu_active.side_menu_collapsed #main_menu .first_level > a .first_level_icon {
  margin: 0;
}
.side_menu_active.side_menu_collapsed #main_menu .first_level > a .menu-title {
  display: none;
}
.side_menu_active.side_menu_collapsed #main_menu .first_level > a .label {
  min-width: 4px;
  padding: 1px 2px;
  right: auto;
  top: 2px;
  left: 3px;
}
.side_menu_active.side_menu_collapsed #main_menu .has_submenu {
  position: relative;
}
.side_menu_active.side_menu_collapsed #main_menu .has_submenu > a {
  position: relative;
  z-index: 10;
}
.side_menu_active.side_menu_collapsed #main_menu .has_submenu > ul {
  position: absolute;
  z-index: 5;
  left: 100%;
  top: 0;
  width: 200px;
  border-width: 0 1px 1px 1px;
  border-style: solid;
  border-color: #e2e2e2;
  background: #f5f5f5;
  display: none !important;
}
.side_menu_active.side_menu_collapsed #main_menu .has_submenu > ul li:first-child {
  border-top: 1px solid #e2e2e2;
}
.side_menu_active.side_menu_collapsed #main_menu .has_submenu > ul li.submenu-title {
  display: list-item;
  height: 38px;
  line-height: 38px;
  color: #fff;
  background: #444;
  font-weight: 700;
  font-size: 13px;
  padding: 0  14px;
  margin: 0 -1px;
}
.side_menu_active.side_menu_collapsed #main_menu .has_submenu > ul li.submenu-title,
.side_menu_active.side_menu_collapsed #main_menu .has_submenu > ul li.submenu-title + li {
  border-top: none;
}
.side_menu_active.side_menu_collapsed #main_menu .has_submenu > ul a {
  padding: 6px 16px;
}
.side_menu_active.side_menu_collapsed #main_menu .has_submenu > ul a .act_nav:before,
.side_menu_active.side_menu_collapsed #main_menu .has_submenu > ul a .act_nav:after {
  display: none;
}
.side_menu_active.side_menu_collapsed #main_menu .has_submenu > ul .has_submenu > ul {
  top: -1px;
}
.side_menu_active.side_menu_collapsed #main_menu .has_submenu > ul .has_submenu > a:after {
  content: '';
  height: 0;
  width: 0;
  border: 4px solid transparent;
  border-left-color: rgba(0, 0, 0, 0.4);
  position: absolute;
  right: 6px;
  top: 12px;
}
.side_menu_active.side_menu_collapsed #main_menu .has_submenu > ul .has_submenu:hover > a:after {
  border-left-color: rgba(255, 255, 255, 0.9);
}
.side_menu_active.side_menu_collapsed #main_menu .has_submenu:hover > a {
  background: #444;
  color: #fff;
}
.side_menu_active.side_menu_collapsed #main_menu .has_submenu:hover > ul {
  display: block !important;
}
@media only screen and (max-width: 991px) {
  .side_menu_active #main_wrapper,
  .side_menu_active #breadcrumbs {
    margin-left: 42px;
  }
  .side_menu_active #main_menu .section_active a.act_nav:before,
  .side_menu_active #main_menu .section_active a.act_nav:after {
    display: none !important;
  }
  .side_menu_active.side_menu_expanded #main_menu {
    -webkit-box-shadow: 4px 0 8px rgba(0, 0, 0, 0.25);
    -moz-box-shadow: 4px 0 8px rgba(0, 0, 0, 0.25);
    box-shadow: 4px 0 8px rgba(0, 0, 0, 0.25);
    border-right-color: transparent;
  }
}
.top_menu_active {
  padding-top: 80px;
}
.top_menu_active #main_menu {
  position: fixed;
  top: 48px;
  height: 32px;
  left: 0;
  right: 0;
  display: block;
  background: #f5f5f5;
  border-bottom: 1px solid #ddd;
  zoom: 1;
  z-index: 100;
}
.top_menu_active #main_menu:before,
.top_menu_active #main_menu:after {
  content: "";
  display: table;
}
.top_menu_active #main_menu:after {
  clear: both;
}
.top_menu_active #main_menu ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
.top_menu_active #main_menu ul li a:focus,
.top_menu_active #main_menu ul li a:hover {
  text-decoration: none;
}
.top_menu_active #main_menu .first_level {
  float: left;
  position: relative;
}
.top_menu_active #main_menu .first_level > a {
  line-height: 20px;
  display: block;
  padding: 6px 10px;
  color: #222222;
}
.top_menu_active #main_menu .first_level > a .first_level_icon {
  margin-right: 6px;
  font-size: 16px;
  vertical-align: -1px;
  min-width: 20px;
  text-align: center;
  display: inline-block;
}
@media only screen and (max-width: 767px) {
  .top_menu_active #main_menu .first_level > a .first_level_icon {
    margin-right: 0;
  }
}
.top_menu_active #main_menu .first_level > a .label {
  display: none;
}
.top_menu_active #main_menu .first_level > a:hover {
  background: rgba(0, 0, 0, 0.06);
}
@media only screen and (max-width: 767px) {
  .top_menu_active #main_menu .first_level > a .menu-title {
    display: none;
  }
}
.top_menu_active #main_menu .first_level ul {
  display: none;
}
.top_menu_active #main_menu .first_level.has_submenu > a {
  padding-right: 20px;
}
.top_menu_active #main_menu .first_level.has_submenu > a:after {
  content: '';
  height: 0;
  width: 0;
  border: 4px solid transparent;
  border-top-color: rgba(0, 0, 0, 0.4);
  position: absolute;
  right: 6px;
  top: 14px;
}
@media only screen and (max-width: 767px) {
  .top_menu_active #main_menu .first_level.has_submenu > a:after {
    right: 6px;
  }
}
.top_menu_active #main_menu .first_level.has_submenu > ul {
  top: 32px;
  border-width: 0 1px 1px;
}
.top_menu_active #main_menu .first_level.has_submenu:hover > a:after {
  border-top-color: rgba(255, 255, 255, 0.9);
}
.top_menu_active #main_menu .has_submenu {
  position: relative;
}
.top_menu_active #main_menu .has_submenu:hover > a {
  background: #444 !important;
  color: #fff;
}
.top_menu_active #main_menu .has_submenu:hover > a:after {
  color: rgba(255, 255, 255, 0.8);
}
.top_menu_active #main_menu .has_submenu:hover > ul {
  display: block !important;
}
.top_menu_active #main_menu .has_submenu > ul {
  position: absolute;
  z-index: 5;
  left: 0;
  width: 200px;
  border-style: solid;
  border-color: #e2e2e2;
  background: #f5f5f5;
  display: none !important;
}
.top_menu_active #main_menu .has_submenu > ul a {
  display: block;
  padding: 6px 10px;
  font-size: 13px;
  color: #222222;
}
.top_menu_active #main_menu .has_submenu > ul a:hover {
  background: rgba(0, 0, 0, 0.06);
}
.top_menu_active #main_menu .has_submenu .has_submenu > a:after {
  content: '';
  height: 0;
  width: 0;
  border: 4px solid transparent;
  border-left-color: rgba(0, 0, 0, 0.4);
  position: absolute;
  right: 6px;
  top: 12px;
}
.top_menu_active #main_menu .has_submenu .has_submenu:hover > a:after {
  border-left-color: rgba(255, 255, 255, 0.9);
}
.top_menu_active #main_menu .has_submenu .has_submenu:hover > ul {
  border-width: 1px;
  left: 100%;
  top: -1px;
}
.top_menu_active.fixed_layout #main_menu {
  width: 1100px;
  left: 50%;
  right: auto;
  margin-left: -550px;
  border-width: 0 1px 1px;
  border-style: solid;
  border-color: #e2e2e2;
}
.top_menu_active .row_full {
  margin-right: -25px;
}
/* scrollbar */
.side_menu_active #main_menu .mCustomScrollbar {
  width: 240px;
}
.side_menu_active #main_menu .mCustomScrollbar .mCSB_scrollTools_vertical {
  left: auto;
  right: 0;
  margin: 0 0 35px;
  width: 10px;
}
/* -- 5. Header -- */
#main_header {
  height: 48px;
  background: #20638f;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 1020;
  -webkit-transition: 200ms ease;
  transition: 200ms ease;
}
#main_header .brand_section {
  line-height: 46px;
  color: #ffffff;
  float: left;
  text-align: center;
}
#main_header .header_notifications {
  list-style: none;
  margin: 8px 40px 0 20px;
  padding: 0;
  float: left;
}
#main_header .header_notifications > li {
  float: left;
  position: relative;
  padding: 2px 0 0;
}
#main_header .header_notifications > li > a {
  font-size: 18px;
  line-height: 22px;
  color: #ffffff;
  padding: 3px 12px 2px;
  background: rgba(255, 255, 255, 0.08);
  -webkit-transition: all 400ms ease;
  transition: all 400ms ease;
  display: block;
}
#main_header .header_notifications > li > a:hover,
#main_header .header_notifications > li > a:focus {
  text-decoration: none;
  background: rgba(255, 255, 255, 0.18);
}
#main_header .header_notifications > li > .label {
  position: absolute;
  top: -4px;
  right: -6px;
  -webkit-border-radius: 2px;
  -moz-border-radius: 2px;
  border-radius: 2px;
}
#main_header .header_notifications > li + li {
  margin-left: 14px;
}
#main_header .header_notifications .dropdown.open .dropdown-menu {
  -webkit-animation-duration: 400ms;
  animation-duration: 400ms;
  -webkit-animation-timing-function: cubic-bezier(0.77, 0, 0.175, 1);
  animation-timing-function: cubic-bezier(0.77, 0, 0.175, 1);
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
  -webkit-animation-name: fadeInUp;
  animation-name: fadeInUp;
}
#main_header .header_notifications .dropdown-menu {
  padding: 10px;
  margin-top: 8px;
  width: 260px;
  z-index: 110;
}
#main_header .header_notifications .dropdown-menu:before,
#main_header .header_notifications .dropdown-menu:after {
  position: absolute;
  content: '';
  width: 0;
  height: 0;
  display: block;
  border: 5px solid transparent;
}
#main_header .header_notifications .dropdown-menu:before {
  border-bottom-color: rgba(0, 0, 0, 0.3);
  top: -11px;
  left: 15px;
}
#main_header .header_notifications .dropdown-menu:after {
  border-bottom-color: #ffffff;
  top: -10px;
  left: 15px;
}
#main_header .header_notifications .dropdown-menu ul {
  margin: 0;
  padding: 0;
}
#main_header .header_notifications .dropdown-menu ul li {
  list-style: none;
  overflow: hidden;
  padding: 6px 0;
}
#main_header .header_notifications .dropdown-menu ul li > img {
  float: left;
  -webkit-border-radius: 20px;
  -moz-border-radius: 20px;
  border-radius: 20px;
  margin-right: 10px;
}
#main_header .header_notifications .dropdown-menu ul li small,
#main_header .header_notifications .dropdown-menu ul li p {
  overflow: hidden;
}
#main_header .header_notifications .dropdown-menu ul li small {
  font-size: 11px;
}
#main_header .header_notifications .dropdown-menu ul li p {
  font-size: 13px;
  line-height: 16px;
  margin: 0;
  padding-top: 2px;
}
#main_header .header_notifications .dropdown-menu ul li + li {
  border-top: 1px solid #eee;
}
#main_header .header_notifications .dropdown-menu ul li .label {
  margin-top: 3px;
}
#main_header .header_notifications .dropdown-menu ul li .btn {
  margin-top: 4px;
}
#main_header .search_section {
  float: right;
  width: 200px;
  margin-right: 20px;
  margin-top: 10px;
  position: relative;
}
#main_header .search_section > input {
  border: none;
  height: 26px;
  background: rgba(255, 255, 255, 0.4);
  -webkit-transition: background 400ms ease;
  transition: background 400ms ease;
}
#main_header .search_section > input:focus {
  background: #fff;
}
#main_header .search_section .btn {
  position: absolute;
  right: 0;
  top: 0;
  color: #222222;
  padding: 4px 8px 2px;
}
#main_header .header_user_actions {
  float: right;
}
#main_header .header_user_actions .user_dropdown {
  cursor: pointer;
  overflow: hidden;
  padding: 4px 5px;
  -webkit-transition: background 400ms ease;
  transition: background 400ms ease;
}
#main_header .header_user_actions .user_dropdown:hover {
  background: rgba(255, 255, 255, 0.1);
}
#main_header .header_user_actions .user_dropdown .caret {
  color: #fff;
  margin-top: 18px;
}
#main_header .header_user_actions .user_avatar {
  float: left;
  margin-right: 5px;
}
#main_header .header_user_actions .user_avatar img {
  border: 1px solid #eee;
}
#main_header .header_user_actions .user_body {
  float: left;
  color: #ffffff;
}
#main_header .header_user_actions .user_subinfo {
  display: block;
}
#main_header .header_user_actions .dropdown-menu {
  margin-top: 1px;
}
#main_header #main_search {
  width: 200px;
  margin: 4px 0 0 40px;
  float: left;
}
/* -- 6. Breadcrumbs -- */
#breadcrumbs {
  height: 32px;
  position: relative;
  padding: 0 15px;
  border-width: 0 0 1px 0;
  border-style: solid;
  border-color: #eee;
  background: #fff;
}
#breadcrumbs ul {
  margin: 0;
  padding: 0;
  list-style: none;
  zoom: 1;
}
#breadcrumbs ul:before,
#breadcrumbs ul:after {
  content: "";
  display: table;
}
#breadcrumbs ul:after {
  clear: both;
}
#breadcrumbs ul li {
  float: left;
  font-size: 12px;
  line-height: 32px;
  position: relative;
}
#breadcrumbs ul li,
#breadcrumbs ul li a {
  color: #555;
}
#breadcrumbs ul li + li {
  margin-left: 8px;
  padding-left: 8px;
}
#breadcrumbs ul li + li:before {
  content: '\\';
  display: inline-block;
  position: absolute;
  left: -3px;
  top: 0;
  font-size: 15px;
}
.hide_breadcrumbs #breadcrumbs {
  display: none;
}
/* 7. Plugins */
/* C3 charts */
.c3 svg {
  font: 10px sans-serif;
}
.c3 path,
.c3 line {
  fill: none;
  stroke: #000;
}
.c3 text {
  -webkit-user-select: none;
  -moz-user-select: none;
  user-select: none;
}
.c3-legend-item-tile,
.c3-xgrid-focus,
.c3-ygrid,
.c3-event-rect,
.c3-bars path {
  shape-rendering: crispEdges;
}
.c3-chart-arc path {
  stroke: #ffffff;
}
.c3-chart-arc text {
  fill: #ffffff;
  font-size: 13px;
}
/*-- Grid --*/
.c3-grid line {
  stroke: #ddd;
}
.c3-grid text {
  fill: #ddd;
}
.c3-xgrid,
.c3-ygrid {
  stroke-dasharray: 3 3;
}
/*-- Text on Chart --*/
.c3-text.c3-empty {
  fill: #808080;
  font-size: 22px;
}
/*-- Line --*/
.c3-line {
  stroke-width: 2px;
}
/*-- Point --*/
.c3-circle._expanded_ {
  stroke-width: 2px;
  stroke: white;
}
.c3-selected-circle {
  stroke-width: 2px;
  fill: white;
}
/*-- Bar --*/
.c3-bar {
  stroke-width: 0;
}
.c3-bar._expanded_ {
  fill-opacity: 0.75;
}
/*-- Arc --*/
.c3-chart-arcs-title {
  font-size: 1.3em;
}
.c3-chart-arc text {
  font-size: 11px;
}
/*-- Focus --*/
.c3-target.c3-focused path.c3-line,
.c3-target.c3-focused path.c3-step {
  stroke-width: 2px;
}
/*-- Region --*/
.c3-region {
  fill: steelblue;
  fill-opacity: .1;
}
/*-- Brush --*/
.c3-brush .extent {
  fill-opacity: .1;
}
/*-- Legend --*/
.c3-legend-item {
  font-size: 12px;
}
.c3-legend-background {
  opacity: 0.75;
  fill: white;
  stroke: lightgray;
  stroke-width: 1;
}
.c3-legend-item-hidden {
  opacity: 0.1;
}
/*-- Tooltip --*/
.c3-tooltip {
  border-collapse: collapse;
  border-spacing: 0;
  background-color: rgba(0, 0, 0, 0.9);
  empty-cells: show;
}
.c3-tooltip th {
  font-size: 12px;
  padding: 4px 5px;
  text-align: left;
  color: #ddd;
}
.c3-tooltip td {
  font-size: 12px;
  padding: 3px 6px;
  color: #ffffff;
}
.c3-tooltip td > span {
  display: inline-block;
  width: 10px;
  height: 10px;
  margin-right: 6px;
}
.c3-tooltip td.value {
  text-align: right;
}
.c3-tooltip td + td {
  border-left: 1px solid rgba(255, 255, 255, 0.1);
}
.c3-tooltip tr + tr td {
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}
.c3-area {
  stroke-width: 0;
  opacity: 0.2;
}
.c3-chart-arcs .c3-chart-arcs-background {
  fill: #e0e0e0;
  stroke: none;
}
.c3-chart-arcs .c3-chart-arcs-background .c3-chart-arcs-gauge-unit {
  fill: #000;
  font-size: 16px;
}
.c3-chart-arcs .c3-chart-arcs-background .c3-chart-arcs-gauge-max {
  fill: #777;
}
.c3-chart-arcs .c3-chart-arcs-background .c3-chart-arcs-gauge-min {
  fill: #777;
}
.c3-chart-arc .c3-gauge-value {
  fill: #000;
  font-size: 28px;
}
/* Switchery */
.switchery {
  background-color: #ffffff;
  border: 1px solid #dfdfdf;
  border-radius: 20px;
  cursor: pointer;
  display: inline-block;
  height: 30px;
  position: relative;
  vertical-align: middle;
  width: 50px;
  -webkit-box-sizing: content-box;
  -moz-box-sizing: content-box;
  box-sizing: content-box;
}
.switchery > small {
  background: #ffffff;
  border-radius: 100%;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
  height: 30px;
  position: absolute;
  top: 0;
  width: 30px;
}
.mini-switch + .switchery {
  height: 15px;
  width: 30px;
}
.mini-switch + .switchery > small {
  height: 15px;
  width: 15px;
}
/* jvectormap */
.jvectormap-label {
  position: absolute;
  display: none;
  background: #292929;
  background: rgba(0, 0, 0, 0.8);
  color: #ffffff;
  font-size: 11px;
  padding: 2px 6px;
  z-index: 1000;
}
.jvectormap-zoomin,
.jvectormap-zoomout {
  position: absolute;
  left: 10px;
  background: url(../lib/jvectormap/nav_controls.png) no-repeat 0 0;
  width: 16px;
  height: 16px;
  cursor: pointer;
  text-indent: 9999px;
}
.jvectormap-zoomin {
  bottom: 30px;
  background-position: 0 -16px;
}
.jvectormap-zoomout {
  bottom: 10px;
}
@media only screen and (-webkit-min-device-pixel-ratio: 1.5), only screen and (min-resolution: 144dppx) {
  .jvectormap-zoomin,
  .jvectormap-zoomout {
    background-image: url('../lib/jvectormap/nav_controls@2x.png') !important;
    background-size: 16px !important;
  }
}
/* easy pie chart */
.easy_chart_box {
  padding: 0 8px;
  display: inline-block;
}
.easy_chart_box + .easy_chart_box {
  margin-left: 10px;
}
.easy_chart_box > .easy_chart {
  display: block;
}
.easy_chart {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 60px;
}
.easy_chart > span {
  position: absolute;
  left: 0;
  width: 100%;
  text-align: center;
  color: #444;
}
.easy_chart > .easy_chart_percent {
  top: 21px;
  font: 400 14px / 18px "Open Sans", Arial, sans-serif;
}
.easy_chart > .easy_chart_icon {
  top: 22px;
  font-size: 16px;
}
.easy_chart .easy_chart_percent_text {
  top: 15px;
  font: 400 12px / 16px "Open Sans", Arial, sans-serif;
}
.easy_chart .easy_chart_percent_text small {
  display: block;
  font-size: 10px;
  line-height: 14px;
}
.easy_chart + .easy_chart {
  margin-left: 30px;
}
.easy_chart_wrapper {
  background: #ffffff;
  border: 1px solid rgba(0, 0, 0, 0.1);
  padding: 20px;
  overflow: hidden;
}
.easy_chart_wrapper .easy_chart_info {
  overflow: hidden;
}
.easy_chart_wrapper .easy_chart_info .easy_chart_heading {
  font: 400 22px / 24px "Open Sans", Arial, sans-serif;
  margin: 0 0 8px;
}
.easy_chart_wrapper .easy_chart_info > p {
  font-size: 13px;
  color: #999;
  margin: 0;
}
.easy_chart_wrapper .easy_chart {
  width: 90px;
  height: 90px;
  float: right;
  margin-left: 10px;
}
.easy_chart_wrapper .easy_chart > .easy_chart_percent {
  top: 32px;
  font: 400 20px / 24px "Open Sans", Arial, sans-serif;
}
.easy_chart_wrapper .easy_chart > .easy_chart_icon {
  top: 29px;
  font-size: 32px;
}
/* select2 */
.select2-container {
  padding: 0;
  width: 100%;
  border: 1px solid #ddd;
  display: block;
}
.select2-container.select2-drop-above .select2-choice,
.select2-container .select2-choice {
  background: none;
  border: none;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  box-shadow: none;
  margin: 4px 0;
}
.select2-container.select2-drop-above .select2-choice .select2-arrow,
.select2-container .select2-choice .select2-arrow {
  background: none;
  border: none;
}
.select2-container.select2-drop-above .select2-choice > .select2-chosen [class^="flag-"],
.select2-container .select2-choice > .select2-chosen [class^="flag-"] {
  margin: -2px 4px 0 0;
}
.select2-container-multi .select2-choices,
.select2-choices {
  border: none;
  background: none;
  padding: 1px 0;
}
.select2-container-multi .select2-choices .select2-search-choice,
.select2-choices .select2-search-choice {
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  border-radius: 0;
  background: #e9ebee;
  border: 1px solid #b8b8b8;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  box-shadow: none;
  font-size: 13px;
  padding: 5px 22px 6px 5px;
}
.select2-container-multi .select2-choices .select2-search-choice [class^="flag-"],
.select2-choices .select2-search-choice [class^="flag-"] {
  margin: -4px 4px 0 0;
  height: 14px;
}
.select2-container-multi .select2-search-choice-close {
  left: auto;
  right: 3px;
  color: #ffffff;
  background: none !important;
  top: 6px;
}
.select2-container-multi .select2-search-choice-close:after {
  font-weight: 700;
  font-size: 17px;
  right: 0;
  color: #ccc;
  content: '×';
}
.select2-container-multi .select2-search-choice-close:hover {
  text-decoration: none;
}
.select2-container-multi .select2-search-choice-close:hover:after {
  color: #888;
}
.select2-container-multi.select2-container-active .select2-choices {
  border: none;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  box-shadow: none;
}
.select2-container-multi .select2-choices .select2-search-choice-focus {
  border-color: #cf000f;
}
.select2-drop-mask {
  z-index: 649;
}
.select2-drop {
  z-index: 650;
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  border-radius: 0;
  border-color: transparent #ddd #ddd;
}
.select2-results .select2-highlighted {
  background: #aab2bd;
}
.select2-dropdown-open.select2-drop-above .select2-choices {
  background: #ffffff;
  border: none;
}
.select2-drop.select2-drop-above {
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  border-radius: 0;
  border-color: #ddd #eee transparent #ddd;
}
.select2-drop.select2-drop-above.select2-drop-active {
  border-top: #ddd;
  margin-bottom: -1px;
}
.select2-results .select2-result-label {
  font-size: 13px;
}
.select2-results .select2-result-label [class^="flag-"] {
  margin: -2px 4px 0 0;
}
/* datepicker */
.datepicker table tr td span,
.datepicker.dropdown-menu {
  border-radius: 0;
}
.datepicker table tr td,
.datepicker table tr th {
  font-size: 12px;
}
.datepicker table tr td:hover,
.datepicker table tr th:hover {
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  border-radius: 0;
}
.datepicker table tr td.old,
.datepicker table tr th.old,
.datepicker table tr td.new,
.datepicker table tr th.new {
  color: #bbb;
}
.datepicker table tr:nth-child(2) th {
  border-width: 0 1px 1px 0;
  border-style: solid;
  border-color: #e8e8e8;
  font-weight: normal;
  color: #2574A9;
}
.datepicker table tr:nth-child(2) th:last-child {
  border-right: none;
}
.datepicker table tr td {
  border-width: 0 1px 1px 0;
  border-style: solid;
  border-color: #e8e8e8;
  padding: 0;
}
.datepicker table tr td:last-child {
  border-right: none;
}
.datepicker table tr td.active,
.datepicker table tr td .active {
  background: #2574A9 !important;
  border: none !important;
  -webkit-box-shadow: inset 0 0 0 1px #1a5277 !important;
  -moz-box-shadow: inset 0 0 0 1px #1a5277 !important;
  box-shadow: inset 0 0 0 1px #1a5277 !important;
  -webkit-border-radius: 0 !important;
  -moz-border-radius: 0 !important;
  border-radius: 0 !important;
}
.datepicker table tr td.selected,
.datepicker table tr td .selected {
  background: #2574A9 !important;
  border: none !important;
  -webkit-box-shadow: inset 0 0 0 1px #1a5277 !important;
  -moz-box-shadow: inset 0 0 0 1px #1a5277 !important;
  box-shadow: inset 0 0 0 1px #1a5277 !important;
  -webkit-border-radius: 0 !important;
  -moz-border-radius: 0 !important;
  border-radius: 0 !important;
}
.datepicker table tr td.range,
.datepicker table tr td.range:hover {
  background: #f2f8fc;
}
.datepicker table tr:last-child td {
  border-bottom: none;
}
.datepicker table tr td span {
  width: 25%;
  margin: 0;
  border-width: 0 1px 1px 0;
  border-style: solid;
  border-color: #e8e8e8;
}
.datepicker table tr td span:nth-child(4n) {
  border-right: none;
}
.datepicker table tr td span:nth-last-child(-n+4) {
  border-bottom: none;
}
.datepicker.datepicker-inline {
  border: 1px solid #eee;
}
.open .dropdown-toggle.datepicker table tr td.active,
.open .dropdown-toggle.datepicker table tr td .active {
  background: #2574A9 !important;
  border: none !important;
  -webkit-box-shadow: inset 0 0 0 1px #1a5277 !important;
  -moz-box-shadow: inset 0 0 0 1px #1a5277 !important;
  box-shadow: inset 0 0 0 1px #1a5277 !important;
  -webkit-border-radius: 0 !important;
  -moz-border-radius: 0 !important;
  border-radius: 0 !important;
}
.open .dropdown-toggle.datepicker table tr td.selected,
.open .dropdown-toggle.datepicker table tr td .selected {
  background: #2574A9 !important;
  border: none !important;
  -webkit-box-shadow: inset 0 0 0 1px #1a5277 !important;
  -moz-box-shadow: inset 0 0 0 1px #1a5277 !important;
  box-shadow: inset 0 0 0 1px #1a5277 !important;
  -webkit-border-radius: 0 !important;
  -moz-border-radius: 0 !important;
  border-radius: 0 !important;
}
/* rangeSlider */
.irs-line {
  background: #e4e4e4;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
}
.irs-line-left,
.irs-line-mid,
.irs-line-right {
  background: none;
}
.irs-min,
.irs-max {
  color: #777;
}
.irs-diapason {
  background: #aab2bd;
}
.irs-slider {
  background: #8d98a7;
  width: 4px;
  height: 18px;
}
.irs-from,
.irs-to,
.irs-single {
  background: #20638f;
}
.irs-from:after,
.irs-to:after,
.irs-single:after {
  border-top-color: #20638f;
}
/* daterangepicker */
.daterangepicker .ranges .input-mini {
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  border-radius: 0;
}
.daterangepicker .ranges li {
  color: #222222;
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  border-radius: 0;
}
.daterangepicker .ranges li.active,
.daterangepicker .ranges li:hover {
  background: #aab2bd;
  border-color: #8d98a7;
}
.daterangepicker .calendar-date {
  border-color: #eee;
}
.daterangepicker table tr:nth-child(2) th {
  border-width: 0 1px 1px 0;
  border-style: solid;
  border-color: #e8e8e8;
  font-weight: normal;
  color: #2574A9;
}
.daterangepicker table tr:nth-child(2) th:last-child {
  border-right: none;
}
.daterangepicker table th.month {
  font-size: 12px;
}
.daterangepicker table tr td,
.daterangepicker table tr th {
  font-size: 12px;
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  border-radius: 0;
}
.daterangepicker table tr td {
  border-width: 0 1px 1px 0;
  border-style: solid;
  border-color: #e8e8e8;
}
.daterangepicker table tr td:last-child {
  border-right: none;
}
.daterangepicker table tr td.off {
  color: #bbb;
}
.daterangepicker table tr td.active,
.daterangepicker table tr td.active:hover {
  background: #2574A9;
  border: none;
  -webkit-box-shadow: inset 0 0 0 1px #1a5277 !important;
  -moz-box-shadow: inset 0 0 0 1px #1a5277 !important;
  box-shadow: inset 0 0 0 1px #1a5277 !important;
}
.daterangepicker table tr td.in-range {
  background: #f2f8fc;
}
.daterangepicker table tr td.in-range:hover {
  background: #ddedf7;
}
.daterangepicker table tr:last-child td {
  border-bottom: none;
}
/* gridforms */
.gf fieldset + fieldset {
  margin-top: 40px;
}
.gf fieldset legend {
  margin-bottom: 0;
  font: 400 15px / 22px "Open Sans", Arial, sans-serif;
  border-bottom-width: 3px;
  text-transform: uppercase;
}
.gf fieldset .gf-error[class^="gf-col-"],
.gf fieldset .gf-error[class*=" gf-col-"] {
  background: #f3c4c8;
}
.gf fieldset .gf-error[class^="gf-col-"]:hover,
.gf fieldset .gf-error[class*=" gf-col-"]:hover {
  background: #fceef0;
}
.gf fieldset .gf-success[class^="gf-col-"],
.gf fieldset .gf-success[class*=" gf-col-"] {
  background: #d7e9c3;
}
.gf fieldset .gf-success[class^="gf-col-"]:hover,
.gf fieldset .gf-success[class*=" gf-col-"]:hover {
  background: #f0f7e8;
}
.gf fieldset [class^="gf-col-"],
.gf fieldset [class*=" gf-col-"],
.gf fieldset [class^="gf-row-"],
.gf fieldset [class*=" gf-row-"] {
  border-color: #aaa !important;
}
.gf fieldset fieldset {
  margin-top: 20px;
}
/* parsley validation */
.parsley-error,
.parsley-error:focus {
  border-color: #da4453;
}
.parsley-errors-list.filled {
  padding: 5px;
}
.parsley-errors-list > span {
  display: block;
  font-size: 12px;
  font-weight: 700;
  color: #da4453;
}
/* plupload */
.plupload_container {
  padding: 0;
}
.plupload_header_content {
  background: #aab2bd;
  padding-left: 20px;
}
/* wizard */
.wizard .steps ul {
  zoom: 1;
  margin: 0;
  padding: 0;
  list-style: none;
  border-width: 1px 0;
  border-style: solid;
  border-color: #eee;
}
.wizard .steps ul:before,
.wizard .steps ul:after {
  content: "";
  display: table;
}
.wizard .steps ul:after {
  clear: both;
}
.wizard .steps ul li {
  float: left;
  margin: 2px 0;
  border-right: 1px solid #eee;
}
.wizard .steps ul li a {
  display: block;
  padding: 4px 10px;
  text-align: center;
  line-height: 32px;
  color: #999;
  position: relative;
  font: 400 13px / 16px "Open Sans", Arial, sans-serif;
}
.wizard .steps ul li a:hover,
.wizard .steps ul li a:focus {
  text-decoration: none;
}
.wizard .steps ul li a .title {
  vertical-align: 0;
}
.wizard .steps ul li a .title span {
  display: inline-block;
  font-size: 12px;
  padding-right: 4px;
  font-weight: 700;
}
.wizard .steps ul li a .current-info {
  display: none;
}
.wizard .steps ul li a:before,
.wizard .steps ul li a:after {
  position: absolute;
  left: 50%;
  content: '';
  display: block;
  height: 0;
  width: 0;
}
.wizard .steps ul li a:before {
  bottom: -20px;
  margin-left: -10px;
  border: 10px solid transparent;
}
.wizard .steps ul li a:after {
  bottom: -14px;
  margin-left: -7px;
  border: 7px solid transparent;
}
.wizard .steps ul li.done a {
  color: #222222;
}
.wizard .steps ul li.current a {
  color: #fff;
  background: #3bafda;
}
.wizard .steps ul li.current a:before {
  border-top-color: #fff;
}
.wizard .steps ul li.current a:after {
  border-top-color: #3bafda;
}
.wizard .steps ul li.error a {
  color: #fff;
  background: #da4453;
}
.wizard .steps ul li.error a:before {
  border-top-color: #fff;
}
.wizard .steps ul li.error a:after {
  border-top-color: #da4453;
}
.wizard .steps ul li:last-child {
  border-right: none;
}
.wizard > .content {
  position: relative;
  overflow: hidden;
  -webkit-transition: height 375ms ease-in-out;
  transition: height 375ms ease-in-out;
}
.wizard > .content > .title {
  left: -999em;
  position: absolute;
}
.wizard > .content > .body {
  float: left;
  width: 100%;
  padding: 20px 0;
  position: absolute;
}
.wizard .wizard_pagination li.disabled .btn {
  border-color: #d3d7d7;
  background-color: #d3d7d7;
  opacity: 0.45;
  filter: alpha(opacity= 45 );
}
.wizard .wizard_pagination li.disabled .btn-link {
  color: #333;
}
.wizard .actions {
  border-top: 1px solid #eee;
  padding-top: 10px;
}
.wizard .actions ul,
.wizard .actions li {
  list-style: none;
  margin-left: 0;
  padding: 0;
}
.wizard .actions li.disabled a {
  color: #999;
}
/* footable */
.table > thead > tr > th.footable_toggler {
  padding-left: 0;
  padding-right: 0;
}
.footable tfoot > tr > td {
  padding-top: 20px;
}
.footable.breakpoint > tbody > tr:hover:not(.footable-row-detail) {
  cursor: auto;
}
.footable.breakpoint > tbody > tr > td > span.footable-toggle {
  cursor: pointer;
}
.footable.breakpoint > tbody > tr.footable-detail-show > td {
  background: #fff;
}
.footable.breakpoint > tbody > tr.footable-detail-show + .footable-row-detail > td {
  background: #fff;
  border-top: none;
  padding-top: 0;
}
/* listnav */
.listNav,
.ln-letters {
  zoom: 1;
}
.listNav:before,
.ln-letters:before,
.listNav:after,
.ln-letters:after {
  content: "";
  display: table;
}
.listNav:after,
.ln-letters:after {
  clear: both;
}
.listNavHide,
.listNavShow {
  -webkit-animation-duration: 400ms;
  animation-duration: 400ms;
  -webkit-animation-timing-function: cubic-bezier(0.77, 0, 0.175, 1);
  animation-timing-function: cubic-bezier(0.77, 0, 0.175, 1);
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
}
.listNavHide {
  display: none;
}
.listNavShow {
  display: list-item;
  -webkit-animation-name: fadeInRight;
  animation-name: fadeInRight;
}
.letterCountShow {
  display: block;
}
.listNav {
  margin-right: 20px;
  float: left;
}
.listNav .ln-letters a {
  font-size: 12px;
  line-height: 22px;
  display: block;
  padding: 0 8px;
  background: #eee;
  margin: 0 2px 2px;
  position: relative;
  text-align: center;
}
.listNav .ln-letters a:hover,
.listNav .ln-letters a.ln-selected {
  background-color: #3bafda;
  color: #ffffff;
}
.listNav .ln-letters a.ln-disabled {
  background: #f8f8f8;
  color: #ccc;
  cursor: default;
}
.listNav .ln-letter-count {
  position: absolute;
  top: 0;
  left: 0;
  width: 20px;
  text-align: center;
  font-size: 10px;
  line-height: 13px;
  color: #222222;
  margin-left: 2px;
}
/* magnific popup */
.mfp-nav {
  color: #fff;
  cursor: pointer;
  font-size: 32px;
  margin-top: -16px;
  position: absolute;
  top: 50%;
  z-index: 1050;
  opacity: 0.65;
  filter: alpha(opacity=65);
}
.mfp-nav.el-icon-chevron-left {
  left: 0;
  margin-left: 20px;
}
.mfp-nav.el-icon-chevron-right {
  margin-right: 20px;
  right: 0;
}
.mfp-nav:hover {
  opacity: 1;
  filter: alpha(opacity=100);
}
/* ====== Zoom effect ====== */
.mfp-zoom-in {
  /* start state */
  /* animate in */
  /* animate out */
}
.mfp-zoom-in .mfp-with-anim {
  opacity: 0;
  transition: all 0.2s ease-in-out;
  transform: scale(0.8);
}
.mfp-zoom-in.mfp-bg {
  opacity: 0;
  transition: all 0.3s ease-out;
}
.mfp-zoom-in.mfp-ready .mfp-with-anim {
  opacity: 1;
  transform: scale(1);
}
.mfp-zoom-in.mfp-ready.mfp-bg {
  opacity: 0.8;
}
.mfp-zoom-in.mfp-removing .mfp-with-anim {
  transform: scale(0.8);
  opacity: 0;
}
.mfp-zoom-in.mfp-removing.mfp-bg {
  opacity: 0;
}
/*

	====== Move-from-top effect ======

	*/
.mfp-move-from-top .mfp-content {
  vertical-align: top;
}
.mfp-move-from-top .mfp-with-anim {
  opacity: 0;
  transition: all 0.2s;
  transform: translateY(-100px);
}
.mfp-move-from-top.mfp-bg {
  opacity: 0;
  transition: all 0.2s;
}
.mfp-move-from-top.mfp-ready .mfp-with-anim {
  opacity: 1;
  transform: translateY(0);
}
.mfp-move-from-top.mfp-ready.mfp-bg {
  opacity: 0.8;
}
.mfp-move-from-top.mfp-removing .mfp-with-anim {
  transform: translateY(-50px);
  opacity: 0;
}
.mfp-move-from-top.mfp-removing.mfp-bg {
  opacity: 0;
}
/*

	====== 3d unfold ======

	*/
.mfp-3d-unfold .mfp-content {
  perspective: 2000px;
}
.mfp-3d-unfold .mfp-with-anim {
  opacity: 0;
  transition: all 0.3s ease-in-out;
  transform-style: preserve-3d;
  transform: rotateY(-60deg);
}
.mfp-3d-unfold.mfp-bg {
  opacity: 0;
  transition: all 0.5s;
}
.mfp-3d-unfold.mfp-ready .mfp-with-anim {
  opacity: 1;
  transform: rotateY(0deg);
}
.mfp-3d-unfold.mfp-ready.mfp-bg {
  opacity: 0.8;
}
.mfp-3d-unfold.mfp-removing .mfp-with-anim {
  transform: rotateY(60deg);
  opacity: 0;
}
.mfp-3d-unfold.mfp-removing.mfp-bg {
  opacity: 0;
}
/*

	====== Zoom-out effect ======

	*/
.mfp-zoom-out .mfp-with-anim {
  opacity: 0;
  transition: all 0.3s ease-in-out;
  transform: scale(1.3);
}
.mfp-zoom-out.mfp-bg {
  opacity: 0;
  transition: all 0.3s ease-out;
}
.mfp-zoom-out.mfp-ready .mfp-with-anim {
  opacity: 1;
  transform: scale(1);
}
.mfp-zoom-out.mfp-ready.mfp-bg {
  opacity: 0.8;
}
.mfp-zoom-out.mfp-removing .mfp-with-anim {
  transform: scale(1.3);
  opacity: 0;
}
.mfp-zoom-out.mfp-removing.mfp-bg {
  opacity: 0;
}
.magnific-popup-open {
  margin-right: 0 !important;
}
.mfp-figure small {
  padding-top: 2px;
}
/* jBox */
#jBox-overlay {
  opacity: 0.3;
  filter: alpha(opacity= 30 );
}
.jBox-Modal .jBox-title {
  font: 400 16px / 20px "Open Sans", Arial, sans-serif;
  color:#FFFFFF;
}
/* growl-2 */
.growl-container.growl-fixed.top-right,
.growl-container.growl-fixed.top-left {
  top: 56px;
}
/* fullcalendar */
.fc-header-title h2 {
  font: 400 22px / 28px "Open Sans", Arial, sans-serif;
}
/* buttons edges butting together */
.fc-header {
  margin-bottom: 20px;
}
.fc-header .fc-button {
  margin: 0;
}
.fc-button {
  padding: 0 10px;
  height: 28px;
  line-height: 28px;
  font-size: 12px;
  font-weight: normal;
}
.fc-button > span:before {
  line-height: 26px;
}
.fc-button .fc-icon {
  margin: 0;
  font-size: 16px;
  font-family: inherit;
  vertical-align: middle;
}
.fc-state-default {
  border: none;
  background: #e6e6e6;
  -webkit-border-radius: 0 !important;
  -moz-border-radius: 0 !important;
  border-radius: 0 !important;
  background-color: #f5f5f5;
  color: #222222;
  text-shadow: none;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  box-shadow: none;
}
.fc-state-hover,
.fc-state-down,
.fc-state-active,
.fc-state-disabled {
  color: #ffffff;
  background: #3bafda;
}
.fc-state-hover {
  color: #ffffff;
  background: #3bafda;
}
.fc-state-down,
.fc-state-active {
  background: #3bafda;
  outline: 0;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  box-shadow: none;
}
.fc-state-disabled {
  cursor: default;
  background: none;
  opacity: 1;
  filter: alpha(opacity= 100 );
  color: #999;
}
.fc-border-separate th {
  border-top: none;
  font: 400 14px / 28px "Open Sans", Arial, sans-serif;
  color: #2574A9;
}
.fc-border-separate th,
.fc-border-separate td {
  border-color: #e2e2e2;
}
.fc-border-separate th.fc-first,
.fc-border-separate td.fc-first {
  border-left: none;
}
.fc-border-separate th.fc-last,
.fc-border-separate td.fc-last {
  border-right: none;
}
.fc-border-separate tr.fc-last td {
  border-bottom: none;
}
.fc-grid .fc-other-month {
  background: #f5f5f5;
}
.fc-grid .fc-day-number {
  font-size: 18px;
  color: #999;
  float: left;
}
.fc-event {
  border: none;
  font-size: 12px;
  -webkit-border-radius: 0 !important;
  -moz-border-radius: 0 !important;
  border-radius: 0 !important;
  line-height: 16px;
  padding: 0 3px;
  background: #277ab0;
}
.fc-event:hover {
  color: #fff;
  background: #20638f;
}
.fc-state-highlight {
  background: #fcf8e3;
}
.fc-cell-overlay {
  background: #bedcf0;
}
/* gmaps */
.gmaps_wrapper {
  padding: 5px;
  -webkit-box-shadow: 0 0 5px rgba(0, 0, 0, 0.15);
  -moz-box-shadow: 0 0 5px rgba(0, 0, 0, 0.15);
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.15);
}
.gmaps_wrapper > .gmap {
  height: 300px;
  overflow: hidden;
  width: 100%;
}
.gmaps_wrapper .infoWindow_content {
  max-width: 200px;
  font-size: 12px;
}
/* datatables */
div.dataTables_length label {
  font-weight: normal;
  float: left;
  text-align: left;
}
div.dataTables_length select {
  width: 75px;
}
div.dataTables_filter label {
  font-weight: normal;
  float: right;
}
div.dataTables_filter input {
  width: 16em;
}
div.dataTables_info {
  padding-top: 8px;
}
div.dataTables_paginate {
  float: right;
  margin: 0;
}
div.dataTables_paginate ul.pagination {
  margin: 2px 0;
  white-space: nowrap;
}
table.dataTable {
  clear: both;
  margin-top: 6px !important;
  margin-bottom: 6px !important;
  max-width: none !important;
}
table.dataTable td,
table.dataTable th {
  -webkit-box-sizing: content-box;
  -moz-box-sizing: content-box;
  box-sizing: content-box;
}
table.dataTable thead .sorting,
table.dataTable thead .sorting_asc,
table.dataTable thead .sorting_desc,
table.dataTable thead .sorting_asc_disabled,
table.dataTable thead .sorting_desc_disabled {
  cursor: pointer;
}
table.dataTable thead .sorting {
  background: url('../img/dt_sort_both.png') no-repeat center right;
}
table.dataTable thead .sorting_asc {
  background: url('../img/dt_sort_asc.png') no-repeat center right;
}
table.dataTable thead .sorting_desc {
  background: url('../img/dt_sort_desc.png') no-repeat center right;
}
table.dataTable thead .sorting_asc_disabled {
  background: url('../img/dt_sort_asc_disabled.png') no-repeat center right;
}
table.dataTable thead .sorting_desc_disabled {
  background: url('../img/dt_sort_desc_disabled.png') no-repeat center right;
}
table.dataTable thead > tr > th {
  padding-left: 8px;
  padding-right: 18px;
  vertical-align: middle;
}
table.dataTable th:active {
  outline: none;
}
/* Scrolling */
div.dataTables_scrollHead table {
  margin-bottom: 0 !important;
  border-bottom-left-radius: 0;
  border-bottom-right-radius: 0;
}
div.dataTables_scrollHead table thead tr:last-child th:first-child {
  border-bottom-left-radius: 0 !important;
  border-bottom-right-radius: 0 !important;
}
div.dataTables_scrollBody table {
  border-top: none;
  margin-top: 0 !important;
  margin-bottom: 0 !important;
}
div.dataTables_scrollBody table tbody tr:first-child th,
div.dataTables_scrollBody table tbody tr:first-child td {
  border-top: none;
}
div.dataTables_scrollFoot table {
  margin-top: 0 !important;
  border-top: none;
}
table.table-bordered.dataTable {
  border-collapse: separate !important;
}
table.table-bordered thead th,
table.table-bordered thead td {
  border-left-width: 0;
  border-top-width: 0;
}
table.table-bordered tbody th,
table.table-bordered tbody td {
  border-left-width: 0;
  border-bottom-width: 0;
}
table.table-bordered th:last-child,
table.table-bordered td:last-child {
  border-right-width: 0;
}
div.dataTables_scrollHead table.table-bordered {
  border-bottom-width: 0;
}
.table tbody tr.active td,
.table tbody tr.active th {
  background-color: #08C;
  color: #ffffff;
}
.table tbody tr.active:hover td,
.table tbody tr.active:hover th {
  background-color: #0075b0 !important;
}
.table tbody tr.active a {
  color: #ffffff;
}
.table-striped tbody tr.active:nth-child(odd) td,
.table-striped tbody tr.active:nth-child(odd) th {
  background-color: #017ebc;
}
table.DTTT_selectable tbody tr {
  cursor: pointer;
}
div.DTTT .btn {
  color: #333 !important;
  font-size: 12px;
}
div.DTTT .btn:hover {
  text-decoration: none !important;
}
ul.DTTT_dropdown.dropdown-menu {
  z-index: 2003;
}
ul.DTTT_dropdown.dropdown-menu li {
  position: relative;
}
ul.DTTT_dropdown.dropdown-menu li:hover a {
  background-color: #0088cc;
  color: #ffffff !important;
}
div.DTTT_collection_background {
  z-index: 2002;
}
div.DTTT_print_info.modal {
  height: 150px;
  margin-top: -75px;
  text-align: center;
}
div.DTTT_print_info h6 {
  font-weight: normal;
  font-size: 28px;
  line-height: 28px;
  margin: 1em;
}
div.DTTT_print_info p {
  font-size: 14px;
  line-height: 20px;
}
div.dataTables_processing {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100%;
  height: 40px;
  margin-left: -50%;
  margin-top: -25px;
  padding-top: 20px;
  text-align: center;
  font-size: 1.2em;
  background-color: #ffffff;
}
div.DTFC_LeftHeadWrapper table,
div.DTFC_LeftFootWrapper table,
div.DTFC_RightHeadWrapper table,
div.DTFC_RightFootWrapper table,
table.DTFC_Cloned tr.even {
  background-color: white;
  margin-bottom: 0;
}
div.DTFC_RightHeadWrapper table,
div.DTFC_LeftHeadWrapper table {
  margin-bottom: 0 !important;
  border-top-right-radius: 0 !important;
  border-bottom-left-radius: 0 !important;
  border-bottom-right-radius: 0 !important;
}
div.DTFC_RightHeadWrapper table thead tr:last-child th:first-child,
div.DTFC_RightHeadWrapper table thead tr:last-child td:first-child,
div.DTFC_LeftHeadWrapper table thead tr:last-child th:first-child,
div.DTFC_LeftHeadWrapper table thead tr:last-child td:first-child {
  border-bottom-left-radius: 0 !important;
  border-bottom-right-radius: 0 !important;
}
div.DTFC_RightBodyWrapper table,
div.DTFC_LeftBodyWrapper table {
  border-top: none;
  margin: 0 !important;
}
div.DTFC_RightBodyWrapper tbody tr:first-child th,
div.DTFC_RightBodyWrapper tbody tr:first-child td,
div.DTFC_LeftBodyWrapper tbody tr:first-child th,
div.DTFC_LeftBodyWrapper tbody tr:first-child td {
  border-top: none;
}
div.DTFC_RightFootWrapper table,
div.DTFC_LeftFootWrapper table {
  border-top: none;
}
div.FixedHeader_Cloned table {
  margin: 0 !important;
}
div.FixedHeader_Cloned th,
div.FixedHeader_Cloned td {
  background-color: #ffffff !important;
}
.ms-container {
  background-image: url("../img/2col_switch.png");
  background-position: 50% 50%;
  background-repeat: no-repeat;
  zoom: 1;
}
@media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min--moz-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 2/1), only screen and (min-device-pixel-ratio: 2), only screen and (min-resolution: 192dppx), only screen and (min-resolution: 2dppx) {
  .ms-container {
    background-image: url("../img/2col_switch@2x.png");
    background-size: 26px 12px;
  }
}
.ms-container:before,
.ms-container:after {
  content: "";
  display: table;
}
.ms-container:after {
  clear: both;
}
.ms-container .ms-selectable,
.ms-container .ms-selection {
  background: #fff;
  color: #55;
  float: left;
  width: 46%;
}
.ms-container .ms-selection {
  float: right;
}
.ms-container .ms-list {
  -webkit-transition: all 375ms cubic-bezier(0.55, 0.055, 0.675, 0.19);
  transition: all 375ms cubic-bezier(0.55, 0.055, 0.675, 0.19);
  border: 1px solid #ccc;
  position: relative;
  height: 200px;
  padding: 0;
  overflow-y: auto;
  font-size: 13px;
  -webkit-overflow-scrolling: touch;
}
.ms-container .ms-list.ms-focus {
  border-color: #20638f;
  outline: 0;
  outline: thin dotted \9;
}
.ms-container ul {
  margin: 0;
  list-style-type: none;
  padding: 0;
}
.ms-container .ms-optgroup-container {
  width: 100%;
}
.ms-container .ms-optgroup-label {
  margin: 0;
  padding: 5px 0px 0px 5px;
  cursor: pointer;
  color: #999;
}
.ms-container .ms-selectable li.ms-elem-selectable,
.ms-container .ms-selection li.ms-elem-selection {
  border-bottom: 1px #eee solid;
  padding: 3px 10px;
  color: #555;
  font-size: 12px;
}
.ms-container .ms-selectable li.ms-hover,
.ms-container .ms-selection li.ms-hover {
  cursor: pointer;
  color: #fff;
  text-decoration: none;
  background-color: #aab2bd;
}
.ms-container .ms-selectable li.disabled,
.ms-container .ms-selection li.disabled,
.ms-container .ms-selectable li.disabled,
.ms-container .ms-selection li.disabled {
  background-color: #eee;
  color: #aaa;
  cursor: text;
}
.ms-container .ms-header,
.ms-container .ms-footer {
  background: #444;
  color: #fff;
  font-size: 12px;
  line-height: 28px;
  padding: 0 10px;
}
.ms-container .ms-header-search,
.ms-container .ms-footer-search {
  padding: 4px 6px;
  background: #f5f5f5;
}
.ms-container .ms-header-search input,
.ms-container .ms-footer-search input {
  margin: 4px 0;
}
.ms-wrapper {
  position: relative;
}
.ms-wrapper .ms_select_all,
.ms-wrapper .ms_deselect_all {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 26px;
  line-height: 16px;
  margin-left: -13px;
}
.ms-wrapper .ms_select_all {
  margin-top: -86px;
}
.ms-wrapper .ms_deselect_all {
  margin-top: -60px;
}
/* ace editor */
.ace_editor {
  padding: 0;
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  border-radius: 0;
  height: 300px;
  -webkit-box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.08);
  -moz-box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.08);
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.08);
  font-family: "Source Code Pro", "Monaco", "Menlo", "Ubuntu Mono", "Consolas", "source-code-pro", monospace !important;
}
/* typeahead */
.search_section .twitter-typeahead {
  display: block !important;
}
.tt-input,
.tt-query,
.tt-hint {
  border: none;
  height: 26px;
  background: #fff;
  -webkit-transition: background 400ms ease;
  transition: background 400ms ease;
  width: 100%;
}
.tt-hint {
  color: #777;
  background: rgba(255, 255, 255, 0.7) !important;
}
.tt-dropdown-menu {
  margin-top: 4px;
  width: 100%;
  background: #fff;
  border: 1px solid #ccc;
  border: 1px solid rgba(0, 0, 0, 0.2);
  -webkit-box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  -moz-box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  padding: 0;
  max-height: 150px;
  overflow-x: hidden;
  overflow-y: auto;
}
.tt-dropdown-menu .tt-suggestion {
  padding: 4px 8px;
  font-size: 12px;
  cursor: pointer;
  margin: 2px;
}
.tt-dropdown-menu .tt-suggestion p {
  margin: 0;
}
.tt-dropdown-menu .tt-suggestion.tt-cursor {
  background-color: #eee;
}
.tt-dropdown-menu .tt-highlight {
  color: #8cc152;
}
/* ClockPicker v0.0.7 for Bootstrap (http://weareoutman.github.io/clockpicker/) Copyright 2014 <NAME> */
.clockpicker .input-group-addon {
  cursor: pointer;
}
.clockpicker-moving {
  cursor: move;
}
.clockpicker-align-left.popover > .arrow {
  left: 25px;
}
.clockpicker-align-top.popover > .arrow {
  top: 17px;
}
.clockpicker-align-right.popover > .arrow {
  left: auto;
  right: 25px;
}
.clockpicker-align-bottom.popover > .arrow {
  top: auto;
  bottom: 6px;
}
.clockpicker-popover .popover-title {
  background-color: #fff;
  color: #999;
  font-size: 24px;
  font-weight: bold;
  line-height: 30px;
  text-align: center;
}
.clockpicker-popover .popover-title span {
  cursor: pointer;
}
.clockpicker-popover .popover-content {
  background-color: #f8f8f8;
  padding: 12px;
  font-size: 13px;
}
.clockpicker-popover .popover-content:last-child {
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
}
.clockpicker-plate {
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 50%;
  width: 200px;
  height: 200px;
  overflow: visible;
  position: relative;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
.clockpicker-canvas,
.clockpicker-dial {
  width: 200px;
  height: 200px;
  position: absolute;
  left: -1px;
  top: -1px;
}
.clockpicker-minutes {
  visibility: hidden;
}
.clockpicker-tick {
  border-radius: 50%;
  color: #666;
  line-height: 26px;
  text-align: center;
  width: 26px;
  height: 26px;
  position: absolute;
  cursor: pointer;
}
.clockpicker-tick.active,
.clockpicker-tick:hover {
  background-color: #c0e5f7;
  background-color: rgba(0, 149, 221, 0.25);
}
.clockpicker-button {
  background-image: none;
  background-color: #fff;
  border-width: 1px 0 0;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
  margin: 0;
  padding: 10px 0;
}
.clockpicker-button:hover {
  background-image: none;
  background-color: #ebebeb;
}
.clockpicker-button:focus {
  outline: none!important;
}
.clockpicker-dial {
  -webkit-transition: -webkit-transform 350ms, opacity 350ms;
  -moz-transition: -moz-transform 350ms, opacity 350ms;
  -ms-transition: -ms-transform 350ms, opacity 350ms;
  -o-transition: -o-transform 350ms, opacity 350ms;
  transition: transform 350ms, opacity 350ms;
}
.clockpicker-dial-out {
  opacity: 0;
}
.clockpicker-hours.clockpicker-dial-out {
  -webkit-transform: scale(1.2, 1.2);
  -moz-transform: scale(1.2, 1.2);
  -ms-transform: scale(1.2, 1.2);
  -o-transform: scale(1.2, 1.2);
  transform: scale(1.2, 1.2);
}
.clockpicker-minutes.clockpicker-dial-out {
  -webkit-transform: scale(0.8, 0.8);
  -moz-transform: scale(0.8, 0.8);
  -ms-transform: scale(0.8, 0.8);
  -o-transform: scale(0.8, 0.8);
  transform: scale(0.8, 0.8);
}
.clockpicker-canvas {
  -webkit-transition: opacity 175ms;
  transition: opacity 175ms;
}
.clockpicker-canvas-out {
  opacity: 0.25;
}
.clockpicker-canvas-bearing,
.clockpicker-canvas-fg {
  stroke: none;
  fill: none;
}
.clockpicker-canvas-bg {
  stroke: none;
  fill: #c0e5f7;
}
.clockpicker-canvas-bg-trans {
  fill: rgba(0, 149, 221, 0.25);
}
.clockpicker-canvas line {
  stroke: rgba(0, 149, 221, 0.25);
  stroke-width: 1;
  stroke-linecap: round;
}
.clockpicker-button.am-button {
  margin: 1px;
  padding: 5px;
  border: 1px solid rgba(0, 0, 0, 0.2);
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
}
.clockpicker-button.pm-button {
  margin: 1px 1px 1px 136px;
  padding: 5px;
  border: 1px solid rgba(0, 0, 0, 0.2);
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
}
/* show/hide password */
::-ms-reveal,
::-ms-clear {
  display: none !important;
}
.hideShowPassword-toggle {
  background: none;
  border: none;
  color: #888;
  cursor: pointer;
  font-size: 11px;
  padding: 2px 4px;
  margin: 2px 4px 2px 2px;
  text-transform: uppercase;
  -moz-appearance: none;
  -webkit-appearance: none;
}
.hideShowPassword-toggle:hover,
.hideShowPassword-toggle:focus {
  background-color: #eee;
  color: #555;
  outline: transparent;
}
/* icheck checkboxes & radio buttons */
.icheck_label {
  margin: 0 0 0 6px;
  font-size: 13px;
}
/* selectize.js */
.selectize-input,
.selectize-input:focus,
.selectize-input.focus {
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  box-shadow: none;
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  border-radius: 0;
  border: 1px solid #ddd;
}
.selectize-dropdown .optgroup-header {
  background: #f5f5f5;
  font-size: 11px;
  text-transform: uppercase;
}
.selectize-dropdown [data-selectable] span.label {
  display: block;
  font-size: 13px;
  text-align: left;
  color: #222222;
  padding: 0 0 4px;
  margin: 0;
}
.selectize-dropdown [data-selectable] span.caption {
  color: #888;
  font-size: 12px;
}
.selectize-dropdown [data-selectable] .highlight {
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  border-radius: 0;
}
.selectize-dropdown .active {
  background: #aab2bd;
  color: #fff;
}
.selectize-dropdown .active > span {
  color: #fff !important;
}
.selectize-control.multi .selectize-input.has-items {
  padding: 6px 6px 3px;
}
.selectize-control.multi .selectize-input > div {
  background: #e9ebee;
}
.selectize-control.multi .selectize-input > div,
.selectize-control.multi .selectize-input > div.active {
  border: 1px solid #b8b8b8;
}
.selectize-control.multi .selectize-input > div.active {
  background: #ccd1d8;
}
.selectize-control.multi .selectize-input span.name {
  font-weight: 700;
}
.selectize-control.multi .selectize-input span.name + span.email {
  padding-left: 4px;
}
.selectize-control.multi .selectize-input span.email {
  color: #888;
  font-size: 12px;
}
.selectize-control.multi .selectize-input > input {
  height: 20px;
}
/*
jQuery.ganttView v.0.8.0
Copyright (c) 2010 <NAME> - <EMAIL>
MIT License Applies
*/
div.ganttview-wrapper {
  margin: 0 auto;
  overflow: hidden;
}
div.ganttview-slide-container *,
div.ganttview-vtheader *,
div.ganttview-slide-container *:before,
div.ganttview-vtheader *:before,
div.ganttview-slide-container *:after,
div.ganttview-vtheader *:after {
  -webkit-box-sizing: content-box;
  -moz-box-sizing: content-box;
  box-sizing: content-box;
}
div.ganttview-hzheader-month,
div.ganttview-hzheader-day,
div.ganttview-vtheader,
div.ganttview-grid,
div.ganttview-grid-row-cell {
  float: left;
}
div.ganttview-hzheader-month,
div.ganttview-hzheader-day {
  text-align: center;
}
div.ganttview-grid-row-cell.last,
div.ganttview-hzheader-day.last,
div.ganttview-hzheader-month.last {
  border-right: none;
}
div.ganttview {
  border: 1px solid #bbb;
}
/* Horizontal Header */
div.ganttview-hzheader-month {
  width: 60px;
  height: 20px;
  border-right: 1px solid #d0d0d0;
  line-height: 20px;
  font-size: 11px;
  font-weight: 700;
  text-transform: uppercase;
  color: #555;
}
div.ganttview-hzheader-day {
  width: 20px;
  height: 20px;
  border-right: 1px solid #f0f0f0;
  border-top: 1px solid #d0d0d0;
  line-height: 20px;
  color: #999;
  font-size: 11px;
}
div.ganttview-hzheader-day.ganttview-weekend {
  background: #f8f8f8;
}
/* Vertical Header */
div.ganttview-vtheader {
  margin-top: 41px;
  width: 240px;
  background-color: #fff;
}
div.ganttview-vtheader-item {
  color: #666;
  border-top: 1px solid #bbb;
}
div.ganttview-vtheader-item:last-child {
  border-bottom: 1px solid #bbb;
}
div.ganttview-vtheader-item-name {
  line-height: 20px;
  font-size: 12px;
  text-transform: uppercase;
  height: 20px;
  padding: 0 5px;
  background: #eee;
  cursor: pointer;
  position: relative;
}
div.ganttview-vtheader-item-name:before {
  position: absolute;
  right: 7px;
  top: 7px;
  content: '';
  display: block;
  width: 7px;
  height: 7px;
  background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHAQMAAAD+nMWQAAAABlBMVEUAAACRkZG25HOBAAAAAXRSTlMAQObYZgAAAA1JREFUCNdjgIB/EAoABwAA/3pWUyMAAAAASUVORK5CYII=");
}
div.ganttview-vtheader-item-name.projectHidden:before {
  background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHAQMAAAD+nMWQAAAABlBMVEUAAACRkZG25HOBAAAAAXRSTlMAQObYZgAAAA5JREFUCNdjEADDfxAaAAmgAV/uzh22AAAAAElFTkSuQmCC");
}
div.ganttview-vtheader-series-name {
  height: 30px;
  line-height: 15px;
  padding: 2px 5px;
  border-top: 1px solid #eee;
  font-size: 12px;
}
div.ganttview-vtheader-series-name:first-child {
  border-top-color: #ddd;
}
div.ganttview-vtheader-series-name > span {
  display: block;
  color: #bbb;
}
/* Slider */
div.ganttview-slide-container {
  overflow-y: auto;
  overflow-x: scroll;
  border-left: 1px solid #bbb;
  -webkit-overflow-scrolling: touch;
}
/* Grid */
.ganttview-grid-row {
  zoom: 1;
}
.ganttview-grid-row:before,
.ganttview-grid-row:after {
  content: "";
  display: table;
}
.ganttview-grid-row:after {
  clear: both;
}
div.ganttview-grid-item {
  background: #eee;
  height: 20px;
  border-top: 1px solid #bbb;
}
div.ganttview-grid-item + .ganttview-grid-row > div.ganttview-grid-row-cell {
  border-top-color: #ddd;
}
div.ganttview-grid-row-cell {
  width: 20px;
  height: 34px;
  border-right: 1px solid #f0f0f0;
  border-top: 1px solid #f0f0f0;
}
div.ganttview-grid-row-cell.ganttview-weekend {
  background-color: #fafafa;
}
/* Blocks */
div.ganttview-blocks {
  margin-top: 41px;
}
div.ganttview-block-item {
  height: 21px;
}
div.ganttview-block-container {
  padding: 4px 0;
}
div.ganttview-block {
  position: relative;
  height: 25px;
  background-color: #bbb;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
  border: 1px solid rgba(0, 0, 0, 0.18);
}
div.ganttview-block-text {
  position: absolute;
  font-size: 11px;
  color: #fff;
  padding: 2px 4px;
}
/* Adjustments for jQuery UI Styling */
div.ganttview-block div.ui-resizable-handle.ui-resizable-s {
  bottom: 0;
}
.ui-resizable {
  position: relative;
}
.ui-resizable-handle {
  display: block;
  font-size: 0.1px;
  position: absolute;
}
.ui-resizable-disabled .ui-resizable-handle,
.ui-resizable-autohide .ui-resizable-handle {
  display: none;
}
.ui-resizable-e {
  cursor: e-resize;
  height: 100%;
  right: -5px;
  top: 0;
  width: 7px;
}
.ui-resizable-w {
  cursor: w-resize;
  height: 100%;
  left: -5px;
  top: 0;
  width: 7px;
}
@media only screen and (min-width: 768px) {
  div.ganttview-wrapper {
    width: 100%;
  }
  div.ganttview-slide-container {
    width: 75%;
  }
  div.ganttview-vtheader {
    width: 25%;
  }
}
@media only screen and (max-width: 991px) {
  div.ganttview-wrapper {
    position: relative;
  }
  div.ganttview-vtheader {
    position: absolute;
    left: 0;
    top: 1px;
    background: none;
    width: 100%;
    z-index: 2;
  }
  div.ganttview-vtheader div.ganttview-vtheader-item-name {
    background: none;
  }
  div.ganttview-vtheader div.ganttview-vtheader-series-name {
    height: 22px;
    line-height: 20px;
    border: none;
    margin-bottom: 31px;
  }
  div.ganttview-vtheader div.ganttview-vtheader-series-name > span {
    display: inline;
    padding-left: 8px;
  }
  .ganttview-grid-row {
    margin-top: 21px;
  }
  div.ganttview-grid-item + .ganttview-grid-row > div.ganttview-grid-row-cell {
    border-top-color: #f0f0f0;
  }
  .ganttview-grid-row div.ganttview-grid-row-cell {
    border-bottom: 1px solid #f0f0f0;
  }
  .ganttview-grid-row:last-child div.ganttview-grid-row-cell {
    border-bottom: none;
  }
  .ganttview-block-container {
    margin-top: 22px;
  }
  div.ganttview-wrapper,
  div.ganttview-slide-container {
    width: 100%;
  }
  div.ganttview-slide-container {
    border-left: none;
  }
  div.ganttview-vtheader-item:last-child {
    border-bottom: none;
  }
}
/* 8. Pages */
/* Login Page */
body.login_page {
  background: #ececec;
  padding: 0;
}
body.login_page .login_header {
  background: #164a66;
  padding: 20px 0;
  text-align: center;
  border-bottom: 1px solid rgba(0, 0, 0, 0.8);
}
body.login_page .login_register_form {
  width: 320px;
  margin: 0 auto;
  position: relative;
  zoom: 1;
}
body.login_page .login_register_form:before,
body.login_page .login_register_form:after {
  content: "";
  display: table;
}
body.login_page .login_register_form:after {
  clear: both;
}
body.login_page .login_register_form .form_wrapper {
  position: absolute;
  top: 20px;
  left: 0;
  right: 0;
}
body.login_page2 {
  background: #ecf0f1;
  padding: 40px 10px 0;
}
body.login_page2 .heading_a {
  margin-bottom: 20px;
}
body.login_page2 .login_container {
  width: 400px;
  margin: 0 auto;
  position: relative;
  max-width: 100%;
}
body.login_page2 .login_container > form {
  width: 400px;
  max-width: 100%;
  position: absolute;
  top: 0;
  left: 0;
  padding: 20px;
  background: #fff;
  border: 1px solid #ddd;
}
@media only screen and (max-width: 991px) {
  body.login_page2 [class*="col-"] {
    margin-bottom: 6px;
  }
}
/* -- Chat -- */
.chat_users ul {
  margin: 0;
  padding: 0;
  list-style: none;
  padding: 0 0 10px;
}
.chat_users ul li {
  padding: 2px 0;
  overflow: hidden;
}
.chat_users ul li a {
  display: block;
  color: #222222;
  overflow: hidden;
  padding: 4px;
}
.chat_users ul li a > img {
  display: inline-block;
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  border-radius: 50%;
  margin-right: 10px;
  float: left;
}
.chat_users ul li + li {
  border-top: 1px solid #eee;
}
.chat_users ul li.online,
.chat_users ul li.offline {
  position: relative;
}
.chat_users ul li.online:before,
.chat_users ul li.offline:before,
.chat_users ul li.online:after,
.chat_users ul li.offline:after {
  position: absolute;
  content: '';
}
.chat_users ul li.online:after,
.chat_users ul li.offline:after {
  left: 3px;
  top: 8px;
  height: 8px;
  width: 8px;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
}
.chat_users ul li.online:before,
.chat_users ul li.offline:before {
  left: 1px;
  top: 6px;
  height: 12px;
  width: 12px;
  -webkit-border-radius: 6px;
  -moz-border-radius: 6px;
  border-radius: 6px;
}
.chat_users ul li.online:after {
  background: #8cc152;
}
.chat_users ul li.online:before {
  background: #fff;
}
.chat_users ul li.offline:after {
  background: #da4453;
}
.chat_users ul li.offline:before {
  background: #fff;
}
.chat_messages {
  max-height: 600px;
  overflow-x: hidden;
  overflow-y: auto;
}
.chat_messages .message_date {
  font-size: 12px;
  color: #999;
  text-align: center;
  margin-bottom: 10px;
}
.chat_messages ul {
  overflow: hidden;
  margin: 0;
  padding: 0;
  list-style: none;
}
.chat_messages ul li {
  list-style: none;
  clear: both;
}
.chat_messages ul li + li {
  margin-top: 8px;
}
.chat_messages ul .msg_user {
  font-size: 10px;
  font-weight: 700;
  margin: 0 0 4px;
  color: rgba(0, 0, 0, 0.6);
  text-transform: uppercase;
}
.chat_messages ul .msg_left,
.chat_messages ul .msg_right {
  max-width: 80%;
  padding: 10px;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
}
.chat_messages ul .msg_left {
  background: #edf3db;
  float: left;
}
.chat_messages ul .msg_right {
  background: #deecf5;
  float: right;
}
.chat_messages ul + .message_date {
  margin-top: 30px;
}
.chat_message_send {
  margin-top: 40px;
  position: relative;
}
.chat_message_send textarea {
  resize: none;
  height: 74px;
  margin-bottom: 10px;
  overflow-y: scroll;
  padding-right: 90px;
}
.chat_message_send .btn {
  position: absolute;
  top: 10px;
  right: 26px;
}
/* invoices */
.inv_list a {
  display: block;
  color: #3b73af;
}
.inv_list a .inv_list_company {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  display: block;
  font: 400 14px / 18px "Open Sans", Arial, sans-serif;
}
.inv_list a .inv_list_nb,
.inv_list a .inv_list_date {
  color: #999;
  font-size: 12px;
}
.qrcode canvas,
.qrcode img {
  max-width: 100%;
}
.table-invoices tfoot {
  border-top: 2px solid #eee;
}
.table-invoices tfoot > tr > td {
  border-top: none;
  padding: 6px 8px;
}
.table-invoices tfoot > tr.grand_total > td {
  font-size: 16px;
  padding: 8px;
}
/* mailbox */
.mailbox_menu {
  margin-top: 40px;
}
@media (max-width: 991px) {
  .mailbox_menu {
    margin-top: 0;
  }
}
.mailbox_menu > a {
  font-size: 14px;
}
.mailbox_menu .badge {
  font-weight: normal;
  padding: 3px 6px;
  font-size: 11px;
  -webkit-border-radius: 6px;
  -moz-border-radius: 6px;
  border-radius: 6px;
}
.mailbox_menu a.list-group-item.active > .badge {
  color: #222222;
}
.mailbox_menu .menu_icon {
  margin-right: 10px;
  width: 22px;
  text-align: center;
  font-size: 16px;
}
#mailbox_table {
  font-size: 13px;
}
#mailbox_table tbody tr.selected td,
#mailbox_table tbody tr.selected + .footable-row-detail > td {
  background: #ffc;
}
#mailbox_table tbody tr td a {
  color: #222222;
}
#mailbox_table tbody tr td input {
  margin-top: 3px;
}
#mailbox_table .mbox_star {
  color: #ccc;
}
#mailbox_table .mbox_star.marked {
  color: #f1c40f;
}
#mailbox_table .mbox_star span {
  cursor: pointer;
}
#mailbox_table tr.unreaded td {
  background: #fff;
  font-weight: 700;
}
.mail_details_top {
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
  margin-bottom: 20px;
}
.mail_details_top .mail_user_image img {
  display: inline-block;
  margin-right: 16px;
  margin-top: 4px;
  float: left;
}
.mail_details_top .mail_user_info h2 {
  font: 400 22px / 28px "Open Sans", Arial, sans-serif;
  margin: 0;
}
.mail_details_top .mail_user_info span {
  font: 400 13px / 18px "Open Sans", Arial, sans-serif;
}
.mail_details_top .mail_date {
  float: right;
  font-size: 12px;
  color: #999;
  padding-top: 4px;
}
.mail_details_content {
  margin-bottom: 50px;
}
/* search page */
.search_results ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
.search_results ul li {
  padding: 10px;
}
.search_results ul li + li {
  border-top: 1px solid #eee;
}
.search_results ul li h4 {
  font: 400 20px / 24px "Open Sans", Arial, sans-serif;
}
.search-pagination {
  margin-top: 20px;
  border-top: 1px solid #eee;
}
/* user list */
#user_list {
  margin: 0;
  padding: 0;
  list-style: none;
  overflow: hidden;
  border-bottom: 1px solid #eee;
}
#user_list li {
  padding: 10px;
  border-top: 1px solid #eee;
}
#user_list li .ul_userName {
  font: 400 20px / 24px "Open Sans", Arial, sans-serif;
  margin: 0 0 4px;
}
#user_list li p {
  margin: 0;
}
#user_list li p + p {
  margin-top: 10px;
}
.ul_main_info {
  font-size: 12px;
  padding-bottom: 20px;
  color: #999;
  overflow: hidden;
}
/* user profile */
.user_profile_img {
  border: 1px solid #999;
  float: left;
  margin-right: 20px;
  -webkit-border-radius: 38px;
  -moz-border-radius: 38px;
  border-radius: 38px;
}
.user_profile_name {
  font: 400 26px / 32px "Open Sans", Arial, sans-serif;
  margin: 0 0 6px;
}
.user_profile_info {
  font-size: 12px;
  margin: 0;
  font: 400 13px / 16px "Open Sans", Arial, sans-serif;
}
.user_profile_info + .user_profile_info {
  margin-top: 4px;
}
.user_profile_list_a {
  margin: 0;
  padding: 0;
  list-style: none;
  margin-bottom: 20px;
}
.user_profile_list_a li {
  padding: 8px;
  overflow: hidden;
}
.user_profile_list_a li img {
  float: left;
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  border-radius: 50%;
  margin-right: 8px;
}
.user_profile_list_a li p {
  padding-top: 2px;
  margin: 0;
  font: 400 14px / 18px "Open Sans", Arial, sans-serif;
  overflow: hidden;
}
.user_profile_list_a li p > span {
  display: block;
  font-size: 11px;
}
.user_profile_list_a li + li {
  border-top: 1px dashed #eee;
}
.timeline {
  list-style: none;
  position: relative;
  max-width: 1200px;
  padding: 20px;
  margin: 0 auto 20px auto !important;
  overflow: hidden;
}
.timeline:after {
  content: "";
  position: absolute;
  top: 0;
  left: 2%;
  margin-left: -2px;
  background-color: #eee;
  height: 100%;
  width: 4px;
  border-radius: 2px;
  display: block;
}
.timeline .timeline-row {
  padding-left: 50%;
  position: relative;
  z-index: 10;
}
.timeline .timeline-row .timeline-time {
  position: absolute;
  right: 50%;
  top: 34px;
  text-align: right;
  margin-right: 40px;
  font-size: 16px;
  font: 400 16px / 20px "Open Sans", Arial, sans-serif;
}
.timeline .timeline-row .timeline-time small {
  display: block;
  text-transform: uppercase;
  font-size: 11px;
  line-height: 13px;
}
.timeline .timeline-row .timeline-icon {
  position: absolute;
  top: 30px;
  left: 50%;
  margin-left: -20px;
  width: 40px;
  height: 40px;
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  border-radius: 50%;
  background-color: #ffffff;
  text-align: center;
  -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  -moz-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  padding: 3px;
  color: #ffffff;
  font-size: 14px;
  z-index: 100;
}
.timeline .timeline-row .timeline-icon > div {
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  border-radius: 50%;
  line-height: 34px;
  font-size: 16px;
  height: 34px;
  overflow: hidden;
}
.timeline .timeline-row .timeline-icon > div.bg-primary {
  background: #3bafda;
}
.timeline .timeline-row .timeline-icon > div.bg-info {
  background: #37bc9b;
}
.timeline .timeline-row .timeline-icon > div.bg-success {
  background: #8cc152;
}
.timeline .timeline-row .timeline-icon > div.bg-warning {
  background: #f6bb42;
}
.timeline .timeline-row .timeline-icon > div.bg-danger {
  background: #da4453;
}
.timeline .timeline-row .timeline-icon > div > i {
  line-height: 33px;
}
.timeline .timeline-row .timeline-content {
  margin-left: 40px;
  background-color: #ffffff;
  color: #222222;
  position: relative;
  left: 0;
  border: 1px solid #eee;
  z-index: 10;
  -webkit-box-shadow: 2px 3px 5px rgba(0, 0, 0, 0.1);
  -moz-box-shadow: 2px 3px 5px rgba(0, 0, 0, 0.1);
  box-shadow: 2px 3px 5px rgba(0, 0, 0, 0.1);
}
.timeline .timeline-row .timeline-content:after {
  content: "";
  position: absolute;
  top: 48px;
  left: -41px;
  height: 4px;
  width: 40px;
  background-color: #eee;
  z-index: -1;
}
.timeline .timeline-row .timeline-content h2 {
  font: 400 20px / 26px "Open Sans", Arial, sans-serif;
  margin: 0 0 12px;
}
.timeline .timeline-row .timeline-content .timeline-inner-content {
  z-index: 10;
  background: #ffffff;
  padding: 15px;
}
.timeline .timeline-row .timeline-content .comment {
  position: relative;
}
.timeline .timeline-row .timeline-content .comment:before {
  content: '"';
  position: absolute;
  left: 0;
  top: 0;
  color: #999;
  display: block;
  font-size: 18px;
}
.timeline .timeline-row:nth-child(odd) {
  padding-left: 0;
  padding-right: 50%;
}
.timeline .timeline-row:nth-child(odd) .timeline-time {
  right: auto;
  left: 50%;
  text-align: left;
  margin-right: 0;
  margin-left: 40px;
}
.timeline .timeline-row:nth-child(odd) .timeline-content {
  margin-right: 40px;
  margin-left: 0;
  left: 0;
  -webkit-box-shadow: -2px 3px 5px rgba(0, 0, 0, 0.1);
  -moz-box-shadow: -2px 3px 5px rgba(0, 0, 0, 0.1);
  box-shadow: -2px 3px 5px rgba(0, 0, 0, 0.1);
}
.timeline .timeline-row:nth-child(odd) .timeline-content:after {
  left: auto;
  right: -41px;
}
@media (max-width: 1200px) {
  .timeline {
    padding: 15px 10px;
  }
  .timeline:after {
    left: 28px;
  }
  .timeline .timeline-row {
    padding-left: 0;
    margin-bottom: 16px;
  }
  .timeline .timeline-row .timeline-time {
    position: relative;
    right: auto;
    top: 0;
    text-align: left;
    margin: 0 0 6px 56px;
  }
  .timeline .timeline-row .timeline-time small {
    display: inline-block;
    margin-right: 6px;
  }
  .timeline .timeline-row .timeline-icon {
    top: 52px;
    left: -2px;
    margin-left: 0;
  }
  .timeline .timeline-row .timeline-content {
    margin-left: 56px;
    position: relative;
  }
  .timeline .timeline-row .timeline-content:after {
    right: auto !important;
    left: -20px !important;
    top: 42px;
  }
  .timeline .timeline-row:nth-child(odd) {
    padding-right: 0;
  }
  .timeline .timeline-row:nth-child(odd) .timeline-time {
    position: relative;
    right: auto;
    left: auto;
    top: 0;
    text-align: left;
    margin: 0 0 6px 56px;
  }
  .timeline .timeline-row:nth-child(odd) .timeline-content {
    margin-right: 0;
    margin-left: 55px;
    left: 0;
    -webkit-box-shadow: 2px 3px 5px rgba(0, 0, 0, 0.1);
    -moz-box-shadow: 2px 3px 5px rgba(0, 0, 0, 0.1);
    box-shadow: 2px 3px 5px rgba(0, 0, 0, 0.1);
  }
}
/* gallery */
.gallery_grid {
  margin: 0;
  padding: 0;
  list-style: none;
  zoom: 1;
}
.gallery_grid:before,
.gallery_grid:after {
  content: "";
  display: table;
}
.gallery_grid:after {
  clear: both;
}
.gallery_grid li {
  width: 20%;
  float: left;
  overflow: hidden;
  padding: 10px;
  border: 1px solid #eee;
  margin: -1px -1px 0 0;
  position: relative;
}
.gallery_grid li > a.img_wrapper {
  height: 220px;
  overflow: hidden;
  text-align: center;
  display: block;
}
.gallery_grid li > a.img_wrapper img {
  height: 100%;
  width: auto;
}
.gallery_grid li > a.img_wrapper .gallery_image_zoom {
  opacity: 0;
  filter: alpha(opacity= 0 );
  position: absolute;
  left: 50%;
  top: 50%;
  font-size: 22px;
  background: rgba(0, 0, 0, 0.8);
  color: #eee;
  width: 42px;
  height: 42px;
  text-align: center;
  margin: -21px 0 0 -21px;
  -webkit-transform: scale(0.3);
  -moz-transform: scale(0.3);
  -ms-transform: scale(0.3);
  -o-transform: scale(0.3);
  transform: scale(0.3);
  -webkit-transition: all 200ms cubic-bezier(0.77, 0, 0.175, 1);
  transition: all 200ms cubic-bezier(0.77, 0, 0.175, 1);
  display: block;
}
.gallery_grid li > a.img_wrapper .gallery_image_zoom > span {
  display: block;
  line-height: 40px;
}
.gallery_grid li:hover a.img_wrapper .gallery_image_zoom {
  opacity: 1;
  filter: alpha(opacity= 100 );
  -webkit-transform: scale(1);
  -moz-transform: scale(1);
  -ms-transform: scale(1);
  -o-transform: scale(1);
  transform: scale(1);
}
@media only screen and (max-width: 1199px) {
  .gallery_grid li {
    width: 25%;
  }
}
@media only screen and (max-width: 991px) {
  .gallery_grid li {
    width: 33.3333333%;
  }
}
@media only screen and (max-width: 767px) {
  .gallery_grid li {
    width: 100%;
  }
}
/* error page */
body.error_page {
  background: #ecf0f1;
  text-align: center;
}
#error_wrapper {
  height: 100%;
  text-align: center;
  width: 500px;
  max-width: 100%;
  margin: 0 auto;
}
#error_wrapper_inner {
  padding: 30px 20px;
}
#error_wrapper_inner .error_heading {
  font: 400 72px/80px "Open Sans", sans-serif;
  margin: 0 0 20px;
}
#error_wrapper_inner .error_subheading {
  font: 400 24px/30px "Open Sans", sans-serif;
  margin: 0 0 40px;
}
#error_wrapper_inner .error_subheading span {
  color: #c0392b;
}
#error_wrapper_inner p {
  font-size: 14px;
  margin: 0;
}
#error_wrapper_inner a {
  background: #8cc152;
  color: #fff;
  display: inline-block;
  padding: 6px 16px;
  font-size: 12px;
  font-weight: 700;
  text-decoration: none;
}
.shuffle--container {
  position: relative;
  overflow: hidden;
}
.contact_list {
  margin: 0;
  padding: 0;
  list-style: none;
  zoom: 1;
  overflow: hidden;
}
.contact_list:before,
.contact_list:after {
  content: "";
  display: table;
}
.contact_list:after {
  clear: both;
}
.contact_list li {
  width: 25%;
  float: left;
  display: block;
  padding: 5px;
}
@media only screen and (max-width: 1199px) {
  .contact_list li {
    width: 33.333333%;
  }
}
@media only screen and (max-width: 991px) {
  .contact_list li {
    width: 50%;
  }
}
@media only screen and (max-width: 767px) {
  .contact_list li {
    width: 100%;
  }
}
.contact_list li > a {
  display: block;
  border: 1px dashed #eee;
  padding: 10px;
}
.contact_list li > a > img {
  float: left;
  margin-right: 10px;
}
.contact_list li > a small {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  display: block;
}
.contact_list li > a:hover {
  background: #3bafda;
  color: #ffffff;
  border: 1px solid #3bafda;
}
.contact_list li > a:hover small,
.contact_list li > a:hover .contact_content span {
  color: #ffffff;
}
.contact_list li h2 {
  font: 400 16px / 20px "Open Sans", Arial, sans-serif;
  margin: 0;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
.contact_list li .contact_content {
  overflow: hidden;
  display: block;
}
.contact_list li .contact_content span {
  display: block;
  line-height: 1.3;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  margin-bottom: 6px;
}
/* -- 9. CSS3 Animations -- */
.animated {
  -webkit-animation-duration: 400ms;
  animation-duration: 400ms;
  -webkit-animation-timing-function: cubic-bezier(0.77, 0, 0.175, 1);
  animation-timing-function: cubic-bezier(0.77, 0, 0.175, 1);
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
}
.animated-short {
  -webkit-animation-duration: 300ms;
  animation-duration: 300ms;
  -webkit-animation-timing-function: cubic-bezier(0.47, 0.66, 0, 0.84);
  animation-timing-function: cubic-bezier(0.47, 0.66, 0, 0.84);
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
}
@-webkit-keyframes fadeInLeft {
  0% {
    opacity: 0;
    -webkit-transform: translate3d(-10%, 0, 0);
    transform: translate3d(-10%, 0, 0);
  }
  100% {
    opacity: 1;
    -webkit-transform: none;
    transform: none;
  }
}
@keyframes fadeInLeft {
  0% {
    opacity: 0;
    -webkit-transform: translate3d(-10%, 0, 0);
    -ms-transform: translate3d(-10%, 0, 0);
    transform: translate3d(-10%, 0, 0);
  }
  100% {
    opacity: 1;
    -webkit-transform: none;
    -ms-transform: none;
    transform: none;
  }
}
.fadeInLeft {
  -webkit-animation-name: fadeInLeft;
  animation-name: fadeInLeft;
}
@-webkit-keyframes fadeOutRight {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
    -webkit-transform: translate3d(10%, 0, 0);
    transform: translate3d(10%, 0, 0);
  }
}
@keyframes fadeOutRight {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
    -webkit-transform: translate3d(10%, 0, 0);
    -ms-transform: translate3d(10%, 0, 0);
    transform: translate3d(10%, 0, 0);
  }
}
.fadeOutRight {
  -webkit-animation-name: fadeOutRight;
  animation-name: fadeOutRight;
}
@-webkit-keyframes fadeInRight {
  0% {
    opacity: 0;
    -webkit-transform: translate3d(10%, 0, 0);
    transform: translate3d(10%, 0, 0);
  }
  100% {
    opacity: 1;
    -webkit-transform: none;
    transform: none;
  }
}
@keyframes fadeInRight {
  0% {
    opacity: 0;
    -webkit-transform: translate3d(10%, 0, 0);
    -ms-transform: translate3d(10%, 0, 0);
    transform: translate3d(10%, 0, 0);
  }
  100% {
    opacity: 1;
    -webkit-transform: none;
    -ms-transform: none;
    transform: none;
  }
}
.fadeInRight {
  -webkit-animation-name: fadeInRight;
  animation-name: fadeInRight;
}
@-webkit-keyframes fadeInUp {
  0% {
    opacity: 0;
    -webkit-transform: translate3d(0, 10%, 0);
    transform: translate3d(0, 10%, 0);
  }
  100% {
    opacity: 1;
    -webkit-transform: none;
    transform: none;
  }
}
@keyframes fadeInUp {
  0% {
    opacity: 0;
    -webkit-transform: translate3d(0, 10%, 0);
    -ms-transform: translate3d(0, 10%, 0);
    transform: translate3d(0, 10%, 0);
  }
  100% {
    opacity: 1;
    -webkit-transform: none;
    -ms-transform: none;
    transform: none;
  }
}
.fadeInUp {
  -webkit-animation-name: fadeInUp;
  animation-name: fadeInUp;
}
@-webkit-keyframes fadeInDown {
  0% {
    opacity: 0;
    -webkit-transform: translate3d(0, -10%, 0);
    transform: translate3d(0, -10%, 0);
  }
  100% {
    opacity: 1;
    -webkit-transform: none;
    transform: none;
  }
}
@keyframes fadeInDown {
  0% {
    opacity: 0;
    -webkit-transform: translate3d(0, -10%, 0);
    -ms-transform: translate3d(0, -10%, 0);
    transform: translate3d(0, -10%, 0);
  }
  100% {
    opacity: 1;
    -webkit-transform: none;
    -ms-transform: none;
    transform: none;
  }
}
.fadeInDown {
  -webkit-animation-name: fadeInDown;
  animation-name: fadeInDown;
}
@-webkit-keyframes fadeOutDownBig {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
    -webkit-transform: translate3d(0, 2000px, 0);
    transform: translate3d(0, 2000px, 0);
  }
}
@keyframes fadeOutDownBig {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
    -webkit-transform: translate3d(0, 2000px, 0);
    transform: translate3d(0, 2000px, 0);
  }
}
.fadeOutDownBig {
  -webkit-animation-name: fadeOutDownBig;
  animation-name: fadeOutDownBig;
}
@-webkit-keyframes fadeInUpBig {
  0% {
    opacity: 0;
    -webkit-transform: translate3d(0, 2000px, 0);
    transform: translate3d(0, 2000px, 0);
  }
  100% {
    opacity: 1;
    -webkit-transform: none;
    transform: none;
  }
}
@keyframes fadeInUpBig {
  0% {
    opacity: 0;
    -webkit-transform: translate3d(0, 2000px, 0);
    transform: translate3d(0, 2000px, 0);
  }
  100% {
    opacity: 1;
    -webkit-transform: none;
    transform: none;
  }
}
.fadeInUpBig {
  -webkit-animation-name: fadeInUpBig;
  animation-name: fadeInUpBig;
}
/* -- 11. style switcher -- */
#style_switcher {
  position: fixed;
  z-index: 1000;
  top: 100px;
  right: -191px;
  margin-right: 0;
  padding: 10px;
  border-width: 1px 0 1px 1px;
  border-style: solid;
  border-color: #e1e1e1;
  border-color: rgba(0, 0, 0, 0.2);
  background: #fff;
  width: 191px;
  -webkit-transition: all 200ms cubic-bezier(0.55, 0.055, 0.675, 0.19);
  transition: all 200ms cubic-bezier(0.55, 0.055, 0.675, 0.19);
}
#style_switcher.switcher_open {
  right: 0;
}
#style_switcher .switcher_toggle {
  position: absolute;
  left: -32px;
  top: 10px;
  width: 32px;
  height: 30px;
  line-height: 30px;
  padding-left: 7px;
  border-width: 1px 0 1px 1px;
  border-style: solid;
  border-color: #e1e1e1;
  border-color: rgba(0, 0, 0, 0.1);
  background: rgba(0, 0, 0, 0.7);
  font-size: 16px;
  color: #fff;
  -webkit-border-radius: 4px 0 0 4px;
  -moz-border-radius: 4px 0 0 4px;
  border-radius: 4px 0 0 4px;
}
#style_switcher ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
#style_switcher ul li {
  list-style: none;
  float: left;
  width: 26px;
  height: 26px;
  margin-bottom: 10px;
  text-indent: -9999px;
  cursor: pointer;
  -webkit-box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.2);
  -moz-box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.2);
  box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.2);
}
#style_switcher ul li + li {
  margin-left: 10px;
}
#style_switcher ul li:nth-child(5n+6) {
  clear: left;
  margin-left: 0;
}
#style_switcher .style_items + .style_items {
  margin-top: 20px;
}
#style_switcher .style_title {
  font-size: 12px;
  margin-bottom: 12px;
  padding-bottom: 2px;
  border-bottom: 1px dashed #e1e1e1;
}
#style_switcher .radio {
  font-size: 12px;
  padding-top: 0;
}
#style_switcher .radio input {
  margin-top: 2px;
}
#style_switcher .style_active,
#style_switcher .pattern_active {
  -webkit-border-radius: 26px;
  -moz-border-radius: 26px;
  border-radius: 26px;
}
#style_reset {
  margin-top: 20px;
}
/* -- 12. themes -- */
/* top bar colors */
.sw_tb_style_0 {
  background: #20638f;
}
#main_header.topBar_style_1,
.sw_tb_style_1 {
  background: #02779e;
}
#main_header.topBar_style_2,
.sw_tb_style_2 {
  background: #ab0743;
}
#main_header.topBar_style_3,
.sw_tb_style_3 {
  background: #51445f;
}
#main_header.topBar_style_4,
.sw_tb_style_4 {
  background: #44392e;
}
#main_header.topBar_style_5,
.sw_tb_style_5 {
  background: #036564;
}
#main_header.topBar_style_6,
.sw_tb_style_6 {
  background: #a30006;
}
#main_header.topBar_style_7,
.sw_tb_style_7 {
  background: #518090;
}
#main_header.topBar_style_8,
.sw_tb_style_8 {
  background: #4b1139;
}
#main_header.topBar_style_9,
.sw_tb_style_9 {
  background: #007251;
}
#main_header.topBar_style_10,
.sw_tb_style_10 {
  background: #684d94;
}
#main_header.topBar_style_11,
.sw_tb_style_11 {
  background: #933c60;
}
#main_header.topBar_style_12,
.sw_tb_style_12 {
  background: #cc6633;
}
#main_header.topBar_style_13,
.sw_tb_style_13 {
  background: #333333;
}
#main_header.topBar_style_14,
.sw_tb_style_14 {
  background: #555555;
}
/* background (fixed layout) */
.sw_bg_0 {
  background: #fafafa;
}
.fixed_layout.bg_1 {
  background-image: url("../img/background/fabric_of_squares_gray.png");
  background-repeat: no-repeat;
  background-repeat: repeat;
}
@media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min--moz-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 2/1), only screen and (min-device-pixel-ratio: 2), only screen and (min-resolution: 192dppx), only screen and (min-resolution: 2dppx) {
  .fixed_layout.bg_1 {
    background-image: url("../img/background/fabric_of_squares_gray@2x.png");
    background-size: 410px 410px;
  }
}
.sw_bg_1 {
  background: url(../img/background/fabric_of_squares_gray_tn.png) no-repeat 0 0;
}
.fixed_layout.bg_2 {
  background-image: url("../img/background/bedge_grunge.png");
  background-repeat: no-repeat;
  background-repeat: repeat;
}
@media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min--moz-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 2/1), only screen and (min-device-pixel-ratio: 2), only screen and (min-resolution: 192dppx), only screen and (min-resolution: 2dppx) {
  .fixed_layout.bg_2 {
    background-image: url("../img/background/bedge_grunge@2x.png");
    background-size: 588px 375px;
  }
}
.sw_bg_2 {
  background: url(../img/background/bedge_grunge_tn.png) no-repeat 0 0;
}
.fixed_layout.bg_3 {
  background-image: url("../img/background/grey_wash_wall.png");
  background-repeat: no-repeat;
  background-repeat: repeat;
}
@media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min--moz-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 2/1), only screen and (min-device-pixel-ratio: 2), only screen and (min-resolution: 192dppx), only screen and (min-resolution: 2dppx) {
  .fixed_layout.bg_3 {
    background-image: url("../img/background/grey_wash_wall@2x.png");
    background-size: 350px 259px;
  }
}
.sw_bg_3 {
  background: url(../img/background/grey_wash_wall_tn.png) no-repeat 0 0;
}
.fixed_layout.bg_4 {
  background-image: url("../img/background/mooning.png");
  background-repeat: no-repeat;
  background-repeat: repeat;
}
@media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min--moz-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 2/1), only screen and (min-device-pixel-ratio: 2), only screen and (min-resolution: 192dppx), only screen and (min-resolution: 2dppx) {
  .fixed_layout.bg_4 {
    background-image: url("../img/background/mooning@2x.png");
    background-size: 350px 259px;
  }
}
.sw_bg_4 {
  background: url(../img/background/mooning_tn.png) no-repeat 0 0;
}
.fixed_layout.bg_5 {
  background-image: url("../img/background/shattered.png");
  background-repeat: no-repeat;
  background-repeat: repeat;
}
@media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min--moz-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 2/1), only screen and (min-device-pixel-ratio: 2), only screen and (min-resolution: 192dppx), only screen and (min-resolution: 2dppx) {
  .fixed_layout.bg_5 {
    background-image: url("../img/background/shattered@2x.png");
    background-size: 350px 259px;
  }
}
.sw_bg_5 {
  background: url(../img/background/shattered_tn.png) no-repeat 0 0;
}
.fixed_layout.bg_6 {
  background-image: url("../img/background/grid.png");
  background-repeat: no-repeat;
  background-repeat: repeat;
}
@media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min--moz-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 2/1), only screen and (min-device-pixel-ratio: 2), only screen and (min-resolution: 192dppx), only screen and (min-resolution: 2dppx) {
  .fixed_layout.bg_6 {
    background-image: url("../img/background/grid@2x.png");
    background-size: 350px 259px;
  }
}
.sw_bg_6 {
  background: url(../img/background/grid_tn.png) no-repeat 0 0;
}
.fixed_layout.bg_7 {
  background-image: url("../img/background/wall4.png");
  background-repeat: no-repeat;
  background-repeat: repeat;
}
@media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min--moz-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 2/1), only screen and (min-device-pixel-ratio: 2), only screen and (min-resolution: 192dppx), only screen and (min-resolution: 2dppx) {
  .fixed_layout.bg_7 {
    background-image: url("../img/background/wall4@2x.png");
    background-size: 350px 259px;
  }
}
.sw_bg_7 {
  background: url(../img/background/wall4_tn.png) no-repeat 0 0;
}
.bg_1,
.bg_2,
.bg_3,
.bg_4,
.bg_5,
.bg_6,
.bg_7 {
  background-repeat: repeat;
  background-attachment: fixed;
}
/* -- 13. media queries -- */
@media only screen and (max-width: 1199px) {
  [class*='col-lg'] {
    margin-bottom: 14px;
  }
}
@media only screen and (min-width: 992px) {
  .col-sep-md {
    border-left: 1px solid #eee;
  }
  .text-right-md {
    text-align: right;
  }
}
@media only screen and (max-width: 991px) {
  [class*='col-md'] {
    margin-bottom: 14px;
  }
}
@media only screen and (min-width: 768px) {
  .text-right-sm {
    text-align: right;
  }
}
@media only screen and (max-width: 767px) {
  [class*='col-sm'] {
    margin-bottom: 14px;
  }
}
/* -- 14. Demo classes -- */
.demo_grid .row {
  margin-bottom: 10px;
  text-align: center;
  font: 400 14px / 18px "Open Sans", Arial, sans-serif;
}
.demo_grid .row [class*='col-'] .col-wrapper {
  padding: 8px 0;
  background: #f5f5f5;
}
.demo_grid .row .row [class*='col-'] .col-wrapper {
  margin-top: 8px;
  background: #e8e8e8;
}
.demo_grid .row .row .row [class*='col-'] .col-wrapper {
  background: #dcdcdc;
}
.icon_list {
  margin: 0;
  padding: 0;
  list-style: none;
  display: block;
  margin-bottom: 10px;
  zoom: 1;
}
.icon_list:before,
.icon_list:after {
  content: "";
  display: table;
}
.icon_list:after {
  clear: both;
}
.icon_list li {
  float: left;
  width: 42px;
  height: 42px;
  margin: 2px;
  background: #f5f5f5;
  text-align: center;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
  -webkit-box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.08);
  -moz-box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.08);
  box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.08);
}
.icon_list li > span {
  font-size: 20px;
  line-height: 44px;
  color: #383f47;
}
.icon_list.list_small li {
  width: 34px;
  height: 34px;
}
.icon_list.list_small li > span {
  margin-top: 10px;
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sl/ExpertReview.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sl;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author <NAME>
 */
@Entity
public class ExpertReview implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private Long expertReviewID;
    private Long userID;
    private Long userExpertID;
    private String reviewDescription;
    private String reviewDate;
    private int reviewStatusID;
    
    private String startDate;
    private String endDate;

    private String requestType;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof ExpertReview)) {
            return false;
        }
        ExpertReview other = (ExpertReview) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.sl.ExpertReview[ id=" + id + " ]";
    }

    /**
     * @return the expertReviewID
     */
    public Long getExpertReviewID() {
        return expertReviewID;
    }

    /**
     * @param expertReviewID the expertReviewID to set
     */
    public void setExpertReviewID(Long expertReviewID) {
        this.expertReviewID = expertReviewID;
    }

    /**
     * @return the userID
     */
    public Long getUserID() {
        return userID;
    }

    /**
     * @param userID the userID to set
     */
    public void setUserID(Long userID) {
        this.userID = userID;
    }

    /**
     * @return the userExpertID
     */
    public Long getUserExpertID() {
        return userExpertID;
    }

    /**
     * @param userExpertID the userExpertID to set
     */
    public void setUserExpertID(Long userExpertID) {
        this.userExpertID = userExpertID;
    }

    /**
     * @return the reviewDescription
     */
    public String getReviewDescription() {
        return reviewDescription;
    }

    /**
     * @param reviewDescription the reviewDescription to set
     */
    public void setReviewDescription(String reviewDescription) {
        this.reviewDescription = reviewDescription;
    }

    /**
     * @return the reviewDate
     */
    public String getReviewDate() {
        return reviewDate;
    }

    /**
     * @param reviewDate the reviewDate to set
     */
    public void setReviewDate(String reviewDate) {
        this.reviewDate = reviewDate;
    }

    /**
     * @return the requestType
     */
    public String getRequestType() {
        return requestType;
    }

    /**
     * @param requestType the requestType to set
     */
    public void setRequestType(String requestType) {
        this.requestType = requestType;
    }

    /**
     * @return the reviewStatusID
     */
    public int getReviewStatusID() {
        return reviewStatusID;
    }

    /**
     * @param reviewStatusID the reviewStatusID to set
     */
    public void setReviewStatusID(int reviewStatusID) {
        this.reviewStatusID = reviewStatusID;
    }

    /**
     * @return the startDate
     */
    public String getStartDate() {
        return startDate;
    }

    /**
     * @param startDate the startDate to set
     */
    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }

    /**
     * @return the endDate
     */
    public String getEndDate() {
        return endDate;
    }

    /**
     * @param endDate the endDate to set
     */
    public void setEndDate(String endDate) {
        this.endDate = endDate;
    }

    
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/RecommendationExplanation.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author <NAME>
 */
@Entity
public class RecommendationExplanation implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private Long recommendationExplanationID;
    private Long recommendationID;
    private String factExplanation;
    private int factCategoryID;
    private String factCategoryDescription;
    

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof RecommendationExplanation)) {
            return false;
        }
        RecommendationExplanation other = (RecommendationExplanation) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.sc.RecommendationExplanation[ id=" + id + " ]";
    }

    /**
     * @return the recommendationExplanationID
     */
    public Long getRecommendationExplanationID() {
        return recommendationExplanationID;
    }

    /**
     * @param recommendationExplanationID the recommendationExplanationID to set
     */
    public void setRecommendationExplanationID(Long recommendationExplanationID) {
        this.recommendationExplanationID = recommendationExplanationID;
    }

    /**
     * @return the recommendationID
     */
    public Long getRecommendationID() {
        return recommendationID;
    }

    /**
     * @param recommendationID the recommendationID to set
     */
    public void setRecommendationID(Long recommendationID) {
        this.recommendationID = recommendationID;
    }

    /**
     * @return the factExplanation
     */
    public String getFactExplanation() {
        return factExplanation;
    }

    /**
     * @param factExplanation the factExplanation to set
     */
    public void setFactExplanation(String factExplanation) {
        this.factExplanation = factExplanation;
    }

    /**
     * @return the factCategoryID
     */
    public int getFactCategoryID() {
        return factCategoryID;
    }

    /**
     * @param factCategoryID the factCategoryID to set
     */
    public void setFactCategoryID(int factCategoryID) {
        this.factCategoryID = factCategoryID;
    }

    /**
     * @return the factCategoryDescription
     */
    public String getFactCategoryDescription() {
        return factCategoryDescription;
    }

    /**
     * @param factCategoryDescription the factCategoryDescription to set
     */
    public void setFactCategoryDescription(String factCategoryDescription) {
        this.factCategoryDescription = factCategoryDescription;
    }
    
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/HLCReasoner/ContextClassifier.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.HLCReasoner;
import org.mindswap.pellet.jena.PelletInfGraph;
import org.mindswap.pellet.jena.PelletReasonerFactory;

import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.ModelFactory;

import mm.icl.hlc.OntologyTools.HLCA;
import mm.icl.hlc.OntologyTools.InferredContextOntology;
import mm.icl.hlc.OntologyTools.NutritionContext;
import mm.icl.hlc.OntologyTools.ClinicalContext;
import mm.icl.hlc.OntologyTools.PhysicalActivityContext;
/**
 * Context Classifier: Subcomponent of the HLC Reasoner which performs the
 * classification or identification of the context type to which the
 * unclassified PhysicalActivity and Nutrition Context instance belongs.
 * 
 * @author <NAME> and <NAME>
 * @version 2.5
 * @since 2015-10-28
 */
public class ContextClassifier {
	/**
	 * Inferred version of the Context Ontology which represents the Mining
	 * Minds Context Model.
	 */
	private InferredContextOntology ont;
	/**
	 * Constructor of a new Context Classifier.
	 * 
	 * @param ont
	 *            Inferred version of the Context Ontology which represents the
	 *            Mining Minds Context Model.
	 */
	public ContextClassifier(InferredContextOntology ont) {
		this.ont = ont;
	}
	/**
	 * Method to classify a PhysicalActivity Context instance, i.e., to identify the
	 * context type to which the unclassified PhysicalActivity Context instance
	 * belongs.
	 * 
	 * @param unclassifiedHlc
	 *            Unclassified PhysicalActivity Context instance.
	 * @return Classified PhysicalActivity Context instance.
	 */
	public PhysicalActivityContext classify(PhysicalActivityContext unclassifiedHlc) {
		PhysicalActivityContext classifiedHlc = new PhysicalActivityContext(unclassifiedHlc.getCtxModel(), ont);
		if (!classifiedHlc.isClassified()) {
			OntModel hlcInst = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC,
					unclassifiedHlc.getCtxModel());
			hlcInst.addSubModel(ont.getCtxModel());
			((PelletInfGraph) hlcInst.getGraph()).classify();
			OntClass c = hlcInst.getIndividual(unclassifiedHlc.getCtxInstanceName()).listOntClasses(true).next();
			if (!c.getURI().equals(HLCA.pacClassName))    
				classifiedHlc.setHlcClass(c);
			((PelletInfGraph) hlcInst.getGraph()).close(false);
		}
		return classifiedHlc;
	}
	/**
	 * Method to classify a Nutrition Context instance, i.e., to identify the
	 * context type to which the unclassified Nutrition Context instance
	 * belongs.
	 * 
	 * @param unclassifiedHlc
	 *            Unclassified Nutrition Context instance.
	 * @return Classified Nutrition Context instance.
	 */
	public NutritionContext classify (NutritionContext unclassifiedNutHlc) {
		NutritionContext classifiedNutHlc = new NutritionContext (unclassifiedNutHlc.getCtxModel(), ont);
		if (!classifiedNutHlc.isClassified()) {
			OntModel hlcInst = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC,
					unclassifiedNutHlc.getCtxModel());
			hlcInst.addSubModel(ont.getCtxModel());
			((PelletInfGraph) hlcInst.getGraph()).classify();
			OntClass c = hlcInst.getIndividual(unclassifiedNutHlc.getCtxInstanceName()).listOntClasses(true).next();
			if (!c.getURI().equals(HLCA.nutrClassName))     
				classifiedNutHlc.setHlcClass(c);
			((PelletInfGraph) hlcInst.getGraph()).close(false);
		}
		return classifiedNutHlc;
	}
	/**
	 * Method to classify a Nutrition Context instance, i.e., to identify the
	 * context type to which the unclassified Nutrition Context instance
	 * belongs.
	 * 
	 * @param unclassifiedHlc
	 *            Unclassified Nutrition Context instance.
	 * @return Classified Nutrition Context instance.
	 */
	public ClinicalContext classify (ClinicalContext unclassifiedCliHlc) {
		ClinicalContext classifiedCliHlc = new ClinicalContext (unclassifiedCliHlc.getCtxModel(), ont);
		if (!classifiedCliHlc.isClassified()) {
			OntModel hlcInst = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC,
					unclassifiedCliHlc.getCtxModel());
			hlcInst.addSubModel(ont.getCtxModel());
			((PelletInfGraph) hlcInst.getGraph()).classify();
			OntClass c = hlcInst.getIndividual(unclassifiedCliHlc.getCtxInstanceName()).listOntClasses(true).next();
			if (!c.getURI().equals(HLCA.clinicalClassName))     
				classifiedCliHlc.setHlcClass(c);
			((PelletInfGraph) hlcInst.getGraph()).close(false);
		}
		return classifiedCliHlc;
	}
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/Facts.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author <NAME>
 */
@Entity
public class Facts implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private Long factID;
    private Long situationID;
    private String factDescription;
    private String supportingLinks;
    private String factDate;
    private int factStatusID;
    
    private String factStatusDescription;
    
    private Long userID;
    private String requestType;
    private String startDate;
    private String endDate;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Facts)) {
            return false;
        }
        Facts other = (Facts) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.sc.Facts[ id=" + id + " ]";
    }

    /**
     * @return the factID
     */
    public Long getFactID() {
        return factID;
    }

    /**
     * @param factID the factID to set
     */
    public void setFactID(Long factID) {
        this.factID = factID;
    }

    /**
     * @return the situationID
     */
    public Long getSituationID() {
        return situationID;
    }

    /**
     * @param situationID the situationID to set
     */
    public void setSituationID(Long situationID) {
        this.situationID = situationID;
    }

    /**
     * @return the factDescription
     */
    public String getFactDescription() {
        return factDescription;
    }

    /**
     * @param factDescription the factDescription to set
     */
    public void setFactDescription(String factDescription) {
        this.factDescription = factDescription;
    }

    /**
     * @return the supportingLinks
     */
    public String getSupportingLinks() {
        return supportingLinks;
    }

    /**
     * @param supportingLinks the supportingLinks to set
     */
    public void setSupportingLinks(String supportingLinks) {
        this.supportingLinks = supportingLinks;
    }

    /**
     * @return the factDate
     */
    public String getFactDate() {
        return factDate;
    }

    /**
     * @param factDate the factDate to set
     */
    public void setFactDate(String factDate) {
        this.factDate = factDate;
    }

    /**
     * @return the factStatusID
     */
    public int getFactStatusID() {
        return factStatusID;
    }

    /**
     * @param factStatusID the factStatusID to set
     */
    public void setFactStatusID(int factStatusID) {
        this.factStatusID = factStatusID;
    }

    /**
     * @return the factStatusDescription
     */
    public String getFactStatusDescription() {
        return factStatusDescription;
    }

    /**
     * @param factStatusDescription the factStatusDescription to set
     */
    public void setFactStatusDescription(String factStatusDescription) {
        this.factStatusDescription = factStatusDescription;
    }

    /**
     * @return the userID
     */
    public Long getUserID() {
        return userID;
    }

    /**
     * @param userID the userID to set
     */
    public void setUserID(Long userID) {
        this.userID = userID;
    }

    /**
     * @return the requestType
     */
    public String getRequestType() {
        return requestType;
    }

    /**
     * @param requestType the requestType to set
     */
    public void setRequestType(String requestType) {
        this.requestType = requestType;
    }

    /**
     * @return the startDate
     */
    public String getStartDate() {
        return startDate;
    }

    /**
     * @param startDate the startDate to set
     */
    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }

    /**
     * @return the endDate
     */
    public String getEndDate() {
        return endDate;
    }

    /**
     * @param endDate the endDate to set
     */
    public void setEndDate(String endDate) {
        this.endDate = endDate;
    }
    
}


<|start_filename|>service-curation-layer/recommendation-builder/src/test/java/org/uclab/scl/framework/recbuilder/TypeComparatorTest.java<|end_filename|>
package org.uclab.scl.framework.recbuilder;

import static org.junit.Assert.assertEquals;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class TypeComparatorTest {
  
  @BeforeClass
  public static void setup(){
  }
  
  @AfterClass
  public static void releaseResources(){
    //. release resources if any
  }
  
  @Test
  public void testCompareString1(){
    String v1 = "setting";
    String v2 = "setting";
    String op = "=";
    
    assertEquals(true, TypeComparator.compare(v1, v2, op));
  }
  
  @Test
  public void testCompareString2(){
    String v1 = "setting";
    String v2 = "standing";
    String op = "=";
    
    assertEquals(false, TypeComparator.compare(v1, v2, op));  
  }
  
  @Test
  public void testCompareString3(){
    String v1 = "setting";
    String v2 = "standing";
    String op = "!=";
    
    assertEquals(true, TypeComparator.compare(v1, v2, op)); 
  }
  
  @Test
  public void testCompareInt1(){
    int seconds1 = 45;
    int seconds2 = 45;
    String op = "=";
    
    assertEquals(true, TypeComparator.compare(seconds1, seconds2, op));
  }
  @Test
  public void testCompareInt2(){
    int seconds1 = 125;
    int seconds2 = 130;
    String op = "!=";
    
    assertEquals(true, TypeComparator.compare(seconds1, seconds2, op));
  }
  
  @Test
  public void testCompareInt3(){
    int seconds1 = 45;
    int seconds2 = 35;
    String op = ">";
    
    assertEquals(true, TypeComparator.compare(seconds1, seconds2, op));
  }
  
  @Test
  public void testCompareInt4(){
    int seconds1 = 125;
    int seconds2 = 130;
    String op = "<";
    
    assertEquals(true, TypeComparator.compare(seconds1, seconds2, op));
  }
  
  @Test
  public void testCompareBoolean1(){
    boolean v1 = true;
    boolean v2 = true;
    String op = "=";
    
    assertEquals(true, TypeComparator.compare(v1, v2, op));
  }
  
  @Test
  public void testCompareBoolean2(){
    boolean v1 = true;
    boolean v2 = false;
    String op = "=";
    
    assertEquals(false, TypeComparator.compare(v1, v2, op));
  }
  
  @Test
  public void testCompareBoolean3(){
    boolean v1 = true;
    boolean v2 = false;
    String op = "!=";
    
    assertEquals(true, TypeComparator.compare(v1, v2, op));
  }
}


<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/objectmodel/Violations.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */
package org.uclab.mm.dcl.llm.objectmodel;

/**
 *This class provide the data model for the representation of the violations 
 * that are persisted in log to the help and view of expert.
 * @author Rizvi
 */
public class Violations{

  private String UserID;
  private String ActivityID;
  private String RecordedTime;
  private String ActivityTargetDuration;
  private String LogID;

  private String TotalViolations;

  /**
   * @return the UserID
   */
  public String getUserID(){
    return UserID;
  }

  /**
   * @param UserID the UserID to set
   */
  public void setUserID(String UserID){
    this.UserID = UserID;
  }

  /**
   * @return the ActivityID
   */
  public String getActivityID(){
    return ActivityID;
  }

  /**
   * @param ActivityID the ActivityID to set
   */
  public void setActivityID(String ActivityID){
    this.ActivityID = ActivityID;
  }

  /**
   * @return the StartTime
   */
  public String getStartTime(){
    return RecordedTime;
  }

  /**
   * @param StartTime the StartTime to set
   */
  public void setStartTime(String RecordedTime){
    this.RecordedTime = RecordedTime;
  }

  /**
   * @return the ActivityTargetDuration
   */
  public String getActivityTargetDuration(){
    return ActivityTargetDuration;
  }

  /**
   * @param ActivityTargetDuration the ActivityTargetDuration to set
   */
  public void setActivityTargetDuration(String ActivityTargetDuration){
    this.ActivityTargetDuration = ActivityTargetDuration;
  }

  /**
   * @return the LogID
   */
  public String getLogID(){
    return LogID;
  }

  /**
   * @param LogID the LogID to set
   */
  public void setLogID(String LogID){
    this.LogID = LogID;
  }

  /**
   * @return the TotalViolations
   */
  public String getTotalViolations(){
    return TotalViolations;
  }

  /**
   * @param TotalViolations the TotalViolations to set
   */
  public void setTotalViolations(String TotalViolations){
    this.TotalViolations = TotalViolations;
  }

}


<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/objectmodel/SituationNotification.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */
package org.uclab.mm.dcl.llm.objectmodel;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Rizvi
 */
public class SituationNotification{

  private String UserID;
  private SituationEvent situationEvent = new SituationEvent();

  /**
   * @return the SituationID
   */
  public String getUserID(){
    return UserID;
  }

  /**
   * 
   * @param UserID 
   */
  public void setUserID(String UserID){
    this.UserID = UserID;
  }

  /**
   * @return the situationEvent
   */
  public SituationEvent getSituationEvent(){
    return situationEvent;
  }

  /**
   * @param situationEvent the situationEvent to set
   */
  public void setSituationEvent(SituationEvent situationEvent){
    this.situationEvent = situationEvent;
  }

}


<|start_filename|>knowledge-curation-layer/i-kat/src/main/java/org/uclab/mm/kcl/edkat/controller/RulesController.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.kcl.edkat.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.uclab.mm.kcl.edkat.dao.RuleDAOImpl;
import org.uclab.mm.kcl.edkat.datamodel.Condition;
import org.uclab.mm.kcl.edkat.datamodel.Rule;
import org.uclab.mm.kcl.edkat.datamodel.SituationRuleWrapper;
import org.uclab.mm.kcl.edkat.datamodel.Situations;
import org.uclab.mm.kcl.edkat.datamodel.User;
import org.uclab.mm.kcl.edkat.datamodel.dclcommunication.SituationConditions;
import org.uclab.mm.kcl.edkat.datamodel.dclcommunication.SituationEvent;
import org.uclab.mm.kcl.edkat.datamodel.dclcommunication.SituationEvents;
import org.uclab.mm.kcl.edkat.service.ConditionService;
import org.uclab.mm.kcl.edkat.service.RuleService;
import org.uclab.mm.kcl.edkat.service.SituationService;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

/**
 * This is controller class for the rule this controller handles 
 * create, update, retrieve of rules, conditions, conclusions, and situation
 * @author  <NAME>
 * @version 1.0
 * @since   2015-08-16
*/

@Controller
@SessionAttributes("user")
public class RulesController {

	/**
	 * Object creation of RuleService, SituationService, and ConditionService
	*/
	private RuleService objRuleService;
	private SituationService objSituationService;
	private ConditionService objConditionService;
	
	 private static final Logger logger = LoggerFactory.getLogger(RulesController.class);

	/**
	 * Getter of Object of ConditionService
	*/
	public ConditionService getObjConditionService() {
		return objConditionService;
	}

	
	/**
	 * Setter of Object of ConditionService
	*/
	@Autowired(required=true)
	@Qualifier(value="objConditionService")
	public void setObjConditionService(ConditionService objConditionService) {
		this.objConditionService = objConditionService;
	}

	/**
	 * Getter of Object of RuleService
	*/
	public RuleService getObjRuleService() {
		return objRuleService;
	}

	/**
	 * Getter of Object of SituationService
	*/
	public SituationService getObjSituationService() {
		return objSituationService;
	}

	/**
	 * Setter of Object of SituationService
	*/
	@Autowired(required=true)
	@Qualifier(value="objSituationService")
	public void setObjSituationService(SituationService objSituationService) {
		this.objSituationService = objSituationService;
	}
	
	/**
	 * Setter of Object of SituationService
	*/
	@Autowired(required=true)
    @Qualifier(value="objRuleService")
	public void setObjRuleService(RuleService objRuleService) {
		this.objRuleService = objRuleService;
	}
	
	/**
	 * This function renders and lists all rules on the dashboard
	 * @return view of dashboard to show rules
	*/
	@RequestMapping(value = "/rules", method = RequestMethod.GET)
    public String listRules(Model model) {
		try
		{
			Rule rule = new Rule();
			model.addAttribute("situationRuleWrapper", rule);
	        model.addAttribute("listRules", this.objRuleService.listRules());
	        logger.info("Rules are loaded successfully");
		}
		catch(Exception ex)
		{
			 logger.info("Error in loading rules");
		}
		return "RulesDashboard";
    }
	
	
	/**
	 * This function get all rules in list
	 * @return List of rules
	*/
	@RequestMapping(value = "/allrules", method = RequestMethod.GET)
    public @ResponseBody List<Rule> listRules() {
		List<Rule> rule = new ArrayList<Rule>();
		try
		{
			rule =  this.objRuleService.listRules();
	        logger.info("Rules are loaded successfully");
		}
		catch(Exception ex)
		{
			 logger.info("Error in loading rules");
		}
        return rule;
    }
	
  /**
	 * This method is physically add the rule with corresponding conditions, conclusions and situations into the knowledge base
	 * but this function internally also check the duplication for conditions, conclusions and situations.
	 * @param situationRuleWrapper 
	 * @return view for rule in edit mode.
	*/
    @RequestMapping(value= "/rules/add", method = RequestMethod.POST)
    public String addRule(@ModelAttribute("situationRuleWrapper") SituationRuleWrapper situationRuleWrapper,  Model model){
    	Rule objRule = new Rule();
        Situations objSituation = new Situations();
        User objUser = new User();
        ObjectMapper mapper = new ObjectMapper();
    	try
		{
            objSituation = situationRuleWrapper.getSituations();
            objRule = situationRuleWrapper.getRule();
            objUser = situationRuleWrapper.getUser();
            
            // Start Preparation of Situation and Existing conditions
            
            String strSituationDesc = "";
            boolean blnIsSituationAttached = false;
        	for(int i = 0; i < objRule.getConditionList().size(); i++){
        		Condition objCondition = objRule.getConditionList().get(i);
        		boolean blnIsItSituation = objCondition.getIsItSituation();
            	objCondition = objConditionService.getConditionByFields(objCondition);
            	objRule.getConditionList().get(i).setConditionID(objCondition.getConditionID());
            	objRule.getConditionList().get(i).setConditionKey(objCondition.getConditionKey());
            	objRule.getConditionList().get(i).setConditionValue(objCondition.getConditionValue());
            	objRule.getConditionList().get(i).setConditionValueOperator(objCondition.getConditionValueOperator());
            	
            	if(blnIsItSituation)
            	{
            		blnIsSituationAttached = true;
            		objSituation.getSituationConditionList().add(objCondition);
            		if(strSituationDesc.equals(""))
            		{
            			strSituationDesc = objCondition.getConditionKey() + " " + objCondition.getConditionValueOperator() + " " + objCondition.getConditionValue();
            		}
            		else
            		{
            			strSituationDesc = strSituationDesc + " and " +  objCondition.getConditionKey() + " " + objCondition.getConditionValueOperator() + " " + objCondition.getConditionValue();
            		}
            	}
            	
            }
          
            // End Preparation of Situation and Existing conditions
               	
        	if(blnIsSituationAttached)
        	{ 
        		objSituation = objSituationService.getExistingSituation(objSituation);
        		Situations objNewSituation = new Situations();
        		objSituation.setSituationDescription(strSituationDesc);
        		if(objSituation.getSituationID() == 0){
                    //new rule, add it
            		objNewSituation = this.objSituationService.addSituation(objSituation);
            		
            		/* Client for the DCL to add situations-- Start */
            		SituationEvent objSituationEvent = new SituationEvent();
            		SituationEvents objSituationEvents = new SituationEvents();
            		List<SituationConditions> objListSituationConditions = new ArrayList<SituationConditions>();
            		List<SituationEvent> objListSituationEvent = new ArrayList<SituationEvent>();
            		
            		
            		try
            		{
            			for(int k = 0; k < objNewSituation.getSituationConditionList().size(); k++)
            			{
            				SituationConditions  objSituationConditions  = new SituationConditions();
            				objSituationConditions.setConditionKey(objNewSituation.getSituationConditionList().get(k).getConditionKey());
            				objSituationConditions.setConditionValue(objNewSituation.getSituationConditionList().get(k).getConditionValue());
            				objSituationConditions.setConditionValueOperator(objNewSituation.getSituationConditionList().get(k).getConditionValueOperator());
            				objSituationConditions.setConditionType("String");
            				objListSituationConditions.add(objSituationConditions);
            			}
            			
            			objSituationEvent.setListSConditions(objListSituationConditions);
            			objSituationEvent.setSituationID( Integer.toString(objNewSituation.getSituationID()));
            			objListSituationEvent.add(objSituationEvent);
            			objSituationEvents.setListSEvents(objListSituationEvent);
            			
            	         
            		}
            		catch(Exception ex)
            		{
            			System.out.println("****** Exception **********" + ex.getMessage());
            		}
            		
                }else{
                    //existing rule, call update
                	objNewSituation = objSituation;
                }
        		objRule.setSituationID(objNewSituation.getSituationID()); 
        		for(int i = 0; i < objRule.getConditionList().size(); i++){
            		Condition objCondition = objRule.getConditionList().get(i);
                	objCondition = objConditionService.getConditionByFields(objCondition);
                	if(objCondition.getConditionID() != 0)
                	{ 
                		 objRule.getConditionList().set(i, objCondition);
                	}
        		}
        	}
        	else
        	{ objRule.setSituationID(0); }
        	
            if(objRule.getRuleID() == 0){
                //new rule, add it
            	objRule.setRuleCreatedBy(objUser.getUserID());
            	objRule = this.objRuleService.addRule(objRule);
            }else{
                //existing rule, call update
            	objRule.setRuleUpdatedBy(objUser.getUserID());
            	Date todayDate = new Date();
            	objRule.setRuleLastUpdatedDate(todayDate);
            	objRule = this.objRuleService.updateRule(objRule);
            }
            
	        logger.info("Rule is saved successfully");
		}
		catch(Exception ex)
		{
			 logger.info("Error in saving rule");
		}
        
        model.addAttribute("isSaved", "yes");
        return "redirect:/edit/" + objRule.getRuleID();
    }
    
    
    /**
	 * This method is physically add the rule with corresponding conditions, conclusions and situations into the knowledge base
	 * but this function internally also check the duplication for conditions, conclusions and situations.
	 * @param situationRuleWrapper 
	 * @return successfully added rule id.
	*/
    @RequestMapping(value= "/rules/addRule", method = RequestMethod.POST)
    public @ResponseBody  String addRuleForService(@RequestBody SituationRuleWrapper situationRuleWrapper){
    	Rule objRule = new Rule();
        Situations objSituation = new Situations();
        User objUser = new User();
        
    	try
		{
            objSituation = situationRuleWrapper.getSituations();
            objRule = situationRuleWrapper.getRule();
            objUser = situationRuleWrapper.getUser();
            
            String strSituationDesc = "";
            boolean blnIsSituationAttached = false;
        	for(int i = 0; i < objRule.getConditionList().size(); i++){
        		Condition objCondition = objRule.getConditionList().get(i);
        		boolean blnIsItSituation = objCondition.getIsItSituation();
            	objCondition = objConditionService.getConditionByFields(objCondition);
            	objRule.getConditionList().get(i).setConditionID(objCondition.getConditionID());
            	objRule.getConditionList().get(i).setConditionKey(objCondition.getConditionKey());
            	objRule.getConditionList().get(i).setConditionValue(objCondition.getConditionValue());
            	objRule.getConditionList().get(i).setConditionValueOperator(objCondition.getConditionValueOperator());
            	
            	if(blnIsItSituation)
            	{
            		blnIsSituationAttached = true;
            		objSituation.getSituationConditionList().add(objCondition);
            		if(strSituationDesc.equals(""))
            		{
            			strSituationDesc = objCondition.getConditionKey() + " " + objCondition.getConditionValueOperator() + " " + objCondition.getConditionValue();
            		}
            		else
            		{
            			strSituationDesc = strSituationDesc + " and " +  objCondition.getConditionKey() + " " + objCondition.getConditionValueOperator() + " " + objCondition.getConditionValue();
            		}
            	}
            	
            }
          
            // End Preparation of Situation and Existing conditions
               	
        	if(blnIsSituationAttached)
        	{ 
        		objSituation = objSituationService.getExistingSituation(objSituation);
        		Situations objNewSituation = new Situations();
        		objSituation.setSituationDescription(strSituationDesc);
        		if(objSituation.getSituationID() == 0){
                    //new rule, add it
            		objNewSituation = this.objSituationService.addSituation(objSituation);
            		
            		/* Client for the DCL to add situations-- Start */
            		SituationEvent objSituationEvent = new SituationEvent();
            		SituationEvents objSituationEvents = new SituationEvents();
            		List<SituationConditions> objListSituationConditions = new ArrayList<SituationConditions>();
            		List<SituationEvent> objListSituationEvent = new ArrayList<SituationEvent>();
            		
            		
            		try
            		{
            			for(int k = 0; k < objNewSituation.getSituationConditionList().size(); k++)
            			{
            				SituationConditions  objSituationConditions  = new SituationConditions();
            				objSituationConditions.setConditionKey(objNewSituation.getSituationConditionList().get(k).getConditionKey());
            				objSituationConditions.setConditionValue(objNewSituation.getSituationConditionList().get(k).getConditionValue());
            				objSituationConditions.setConditionValueOperator(objNewSituation.getSituationConditionList().get(k).getConditionValueOperator());
            				objSituationConditions.setConditionType("String");
            				objListSituationConditions.add(objSituationConditions);
            			}
            			
            			objSituationEvent.setListSConditions(objListSituationConditions);
            			objSituationEvent.setSituationID( Integer.toString(objNewSituation.getSituationID()));
            			objListSituationEvent.add(objSituationEvent);
            			objSituationEvents.setListSEvents(objListSituationEvent);
            			
            	         
            		}
            		catch(Exception ex)
            		{
            			System.out.println("****** Exception **********" + ex.getMessage());
            		}
            		
                }else{
                    //existing rule, call update
                	objNewSituation = objSituation;
                }
        		objRule.setSituationID(objNewSituation.getSituationID()); 
        		for(int i = 0; i < objRule.getConditionList().size(); i++){
            		Condition objCondition = objRule.getConditionList().get(i);
                	objCondition = objConditionService.getConditionByFields(objCondition);
                	if(objCondition.getConditionID() != 0)
                	{ 
                		 objRule.getConditionList().set(i, objCondition);
                	}
        		}
        	}
        	else
        	{ objRule.setSituationID(0); }
        	
            if(objRule.getRuleID() == 0){
                //new rule, add it
            	objRule.setRuleCreatedBy(objUser.getUserID());
            	objRule = this.objRuleService.addRule(objRule);
            }else{
                //existing rule, call update
            	objRule.setRuleUpdatedBy(objUser.getUserID());
            	Date todayDate = new Date();
            	objRule.setRuleLastUpdatedDate(todayDate);
            	objRule = this.objRuleService.updateRule(objRule);
            }
            
	        logger.info("Rule saved successfully");
	        return "Rule saved succussfully with ID: " + objRule.getRuleID();
		}
		catch(Exception ex)
		{
			 logger.info("Error in saving rule");
			 return "Error in saving rule";
		}
    }
    
    /**
	 * This function delete the selected rule and render the updated list of rules
	 * @param id
	 * @return redirect to rules with updated list
	*/
    @RequestMapping("/remove/{id}")
    public String removeRule(@PathVariable("id") int id){
    	try
		{
    		 this.objRuleService.removeRule(id);
	        logger.info("Rule is deleted successfully");
		}
		catch(Exception ex)
		{
			 logger.info("Error in deleting rule");
		}
        return "redirect:/rules";
    }
    
    /**
	 * This function edits the exiting selected rule with updated conditions, conclusions, and situations.
	 * @param id
	 * @param user
	 * @return String Rule Editor
	*/
    @RequestMapping("/edit/{id}")
    public String editRule(@PathVariable("id") int id, @ModelAttribute("user") User user, Model model){
    	SituationRuleWrapper situationRuleWrapper = new SituationRuleWrapper();
    	Rule objRule = new Rule();
    	Situations objSituations = new Situations();
    	try
		{
    		objRule = this.objRuleService.getRuleById(id);
        	situationRuleWrapper.setRule(objRule);
        	situationRuleWrapper.setUser(user);
        	if(situationRuleWrapper.getRule().getSituationID() != 0)
        	{
        		objSituations = this.objSituationService.getSituationById(objRule.getSituationID());
        		situationRuleWrapper.setSituations(objSituations);
        	}
        	for(int i = 0; i < objRule.getConditionList().size(); i++)
        	{
        		for(int j = 0; j < objSituations.getSituationConditionList().size(); j++)
        		{
        			if(objRule.getConditionList().get(i).getConditionID() == objSituations.getSituationConditionList().get(j).getConditionID())
        			{
        				objRule.getConditionList().get(i).setIsItSituation(true);
        			}
        		}
        	}
	        logger.info("Rule is updated successfully");
		}
		catch(Exception ex)
		{
			 logger.info("Error in updating rule");
		}
        model.addAttribute("situationRuleWrapper", situationRuleWrapper);
        return "RuleEditor";
    }
    
    /**
	 * This function renders the Rule Editor screen in add mode, when clicks the "add new rule" button. 
	 * @param user
	 * @return string RuleEditor
	 * 
	*/
    @RequestMapping("/addNewRule")
    public String addNewRule(@ModelAttribute("user") User user, Model model){
    	SituationRuleWrapper situationRuleWrapper = new SituationRuleWrapper();
    	try
		{
        	Rule objRule = new Rule();
        	Date todayDate = new Date();
        	objRule.setRuleCreatedDate(todayDate);
        	situationRuleWrapper.setRule(objRule);
        	situationRuleWrapper.setUser(user);
	        logger.info("Rule editor is opened successfully");
		}
		catch(Exception ex)
		{
			 logger.info("Error in opening Rule editor");
		}
    	model.addAttribute("situationRuleWrapper", situationRuleWrapper);
        return "RuleEditor";
    }
    
    /**
	 * This function calls at initialization of application and set some custom settings for Date, String and long
	*/
    @InitBinder
    public void initBinder(WebDataBinder binder) {
    	try
		{
    		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
            sdf.setLenient(true);
            binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
            binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
            binder.registerCustomEditor(Long.class, new CustomNumberEditor(Long.class, true));
            
	        logger.info("Initial binding successfully");
		}
		catch(Exception ex)
		{
			 logger.info("Error in initial binding");
		}
        
    }
    
	
}


<|start_filename|>knowledge-curation-layer/DDKAT/src/main/java/org/uclab/mm/kcl/ddkat/datapreprocessor/MissingValueHandler.java<|end_filename|>
/**
 * Copyright [2017] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.mm.kcl.ddkat.datapreprocessor;

import java.io.File;
import java.util.ArrayList;

import weka.core.Instances;
import weka.core.Range;
import weka.core.converters.ArffSaver;
import weka.core.converters.CSVLoader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// TODO: Auto-generated Javadoc
/**
 * This class identifies missing values, replaces them with attribute mean values, and stores the filled data.
 */
public class MissingValueHandler {
	
	/** The confirmation message. */
	private ArrayList<String> confirmationMessage;
	
	/** The Constant log. */
	private static final Logger log = LoggerFactory.getLogger(MissingValueHandler.class);
	
	/** base directory to store resource data files */
	private static final String BASE_DIR = System.getProperty("user.home") + "/DDKAT/resources/";

	/**
	 * Constructor to instantiate a new MissingValueHandler object.
	 *
	 * @throws Exception the exception
	 */
	public MissingValueHandler() throws Exception {
		
		replaceMissingValues();
	}
	
	/**
	 * Method to replace the identified missing values.
	 *
	 * @throws Exception the exception
	 */
	public void replaceMissingValues() throws Exception {
		
		this.confirmationMessage = new ArrayList<String>();
		
		Instances outputData;
		
		String inputFile = BASE_DIR + "OriginalDataSet.csv";
			
        // load CSV file
		CSVLoader fileLoader=new CSVLoader();
		fileLoader.setSource(new File(inputFile));
	    outputData = fileLoader.getDataSet();
         
        int numInstances = outputData.numInstances();
        int numAttributes = outputData.numAttributes();      
        
        final int NON_NUMERIC = -1;
        int[] m_AttributeIndices = null;
        
        Range m_Attributes = new Range("first-last");

        // attributes must be numeric
        m_Attributes.setUpper(outputData.numAttributes() - 1);
        m_AttributeIndices = m_Attributes.getSelection();
       
        for (int i = 0; i < m_AttributeIndices.length; i++) {
            // ignore class
            if (m_AttributeIndices[i] == outputData.classIndex()) {
                m_AttributeIndices[i] = NON_NUMERIC;
                continue;
                }
            // not numeric -> ignore it
            if (!outputData.attribute(m_AttributeIndices[i]).isNumeric())
                m_AttributeIndices[i] = NON_NUMERIC;
            }
        
        double sum;
        int missingCounter;
        double attributeMean;
        
        // identify the missing values               
        for (int attributeIndex = 0; attributeIndex < numAttributes; attributeIndex++) {
        	
        	// non-numeric attribute?
            if (m_AttributeIndices[attributeIndex] == NON_NUMERIC){
            	continue;
                }
                
            double tempArr[] = outputData.attributeToDoubleArray(attributeIndex);
            sum = 0;
            missingCounter = 0;
            for (int i = 0; i < tempArr.length; i++) {
            	sum = sum + tempArr[i];
            	if(tempArr[i]==0)
            		missingCounter++;                     
                }
                           
            attributeMean = sum / (numInstances-missingCounter);
                
            for (int instanceIndex = 0; instanceIndex < numInstances; instanceIndex++) {
            	
            	// replace the missing values with attribute mean values
            	if(outputData.instance(instanceIndex).value(attributeIndex)==0){
            		outputData.instance(instanceIndex).setValue(attributeIndex, attributeMean);
                	}
                }
            }
               
        outputData.deleteAttributeAt(outputData.numAttributes()-1);        
        outputData.deleteAttributeAt(outputData.numAttributes()-1);
        
        saveFilledData(inputFile, outputData); 
        
	}
	
	/**
	 * Method to store the filled data.
	 *
	 * @param filePath the file path
	 * @param outputData the output data
	 * @throws Exception the exception
	 */
	public void saveFilledData(String filePath, Instances outputData) throws Exception {
		
		// save ARFF file
		log.info("Input file : "+filePath);
        String outputFile = filePath.substring(0,filePath.lastIndexOf('/'));
        outputFile = outputFile + "/ProcessedDataSet.arff";
        log.info("Output file : "+outputFile);
  
        ArffSaver saver = new ArffSaver();
        saver.setInstances(outputData);
        saver.setFile(new File(outputFile));
        saver.writeBatch();
        
        String confirmationMessageStr = "Data is successfully cleaned and is stored at : "+outputFile;
        log.info(confirmationMessageStr);
        this.confirmationMessage.add(confirmationMessageStr);
        
	}

	/**
	 * Method to get the confirmation message of filled data.
	 *
	 * @return the confirmation message
	 */
	public ArrayList<String> getConfirmationMessage() {
		return confirmationMessage;
	}

	/**
	 * Method to set the confirmation message of filled data.
	 *
	 * @param confirmationMessage the new confirmation message
	 */
	public void setConfirmationMessage(ArrayList<String> confirmationMessage) {
		this.confirmationMessage = confirmationMessage;
	}

}



<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/Recommendation.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author <NAME>
 */
@Entity
public class Recommendation implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private Long recommendationID;
    private String recommendationIdentifier;
    private Long situationID;
    private String recommendationDescription;
    private int recommendationTypeID;
    private String conditionValue;
    private int recommendationLevelID;
    private int recommendationStatusID;
    private String recommendationDate;
    
    private String recommendationTypeDescription;
    private String recommendationLevelDescription;
    private String recommendationStatusDescription;
    
    private int situationCategoryID;
    private String situationCategoryDescription;
    private String situationCategoryIDs;
    
    private Long userID;
    private String requestType;
    private String startDate;
    private String endDate;
    
    

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Recommendation)) {
            return false;
        }
        Recommendation other = (Recommendation) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.sc.Recommendation[ id=" + id + " ]";
    }

    /**
     * @return the recommendationID
     */
    public Long getRecommendationID() {
        return recommendationID;
    }

    /**
     * @param recommendationID the recommendationID to set
     */
    public void setRecommendationID(Long recommendationID) {
        this.recommendationID = recommendationID;
    }

    /**
     * @return the recommendationIdentifier
     */
    public String getRecommendationIdentifier() {
        return recommendationIdentifier;
    }

    /**
     * @param recommendationIdentifier the recommendationIdentifier to set
     */
    public void setRecommendationIdentifier(String recommendationIdentifier) {
        this.recommendationIdentifier = recommendationIdentifier;
    }

    /**
     * @return the situationID
     */
    public Long getSituationID() {
        return situationID;
    }

    /**
     * @param situationID the situationID to set
     */
    public void setSituationID(Long situationID) {
        this.situationID = situationID;
    }

    /**
     * @return the recommendationDescription
     */
    public String getRecommendationDescription() {
        return recommendationDescription;
    }

    /**
     * @param recommendationDescription the recommendationDescription to set
     */
    public void setRecommendationDescription(String recommendationDescription) {
        this.recommendationDescription = recommendationDescription;
    }

    /**
     * @return the recommendationTypeID
     */
    public int getRecommendationTypeID() {
        return recommendationTypeID;
    }

    /**
     * @param recommendationTypeID the recommendationTypeID to set
     */
    public void setRecommendationTypeID(int recommendationTypeID) {
        this.recommendationTypeID = recommendationTypeID;
    }

    /**
     * @return the conditionValue
     */
    public String getConditionValue() {
        return conditionValue;
    }

    /**
     * @param conditionValue the conditionValue to set
     */
    public void setConditionValue(String conditionValue) {
        this.conditionValue = conditionValue;
    }

    /**
     * @return the recommendationLevelID
     */
    public int getRecommendationLevelID() {
        return recommendationLevelID;
    }

    /**
     * @param recommendationLevelID the recommendationLevelID to set
     */
    public void setRecommendationLevelID(int recommendationLevelID) {
        this.recommendationLevelID = recommendationLevelID;
    }

    /**
     * @return the recommendationStatusID
     */
    public int getRecommendationStatusID() {
        return recommendationStatusID;
    }

    /**
     * @param recommendationStatusID the recommendationStatusID to set
     */
    public void setRecommendationStatusID(int recommendationStatusID) {
        this.recommendationStatusID = recommendationStatusID;
    }

    /**
     * @return the recommendationDate
     */
    public String getRecommendationDate() {
        return recommendationDate;
    }

    /**
     * @param recommendationDate the recommendationDate to set
     */
    public void setRecommendationDate(String recommendationDate) {
        this.recommendationDate = recommendationDate;
    }

    /**
     * @return the requestType
     */
    public String getRequestType() {
        return requestType;
    }

    /**
     * @param requestType the requestType to set
     */
    public void setRequestType(String requestType) {
        this.requestType = requestType;
    }

    /**
     * @return the startDate
     */
    public String getStartDate() {
        return startDate;
    }

    /**
     * @param startDate the startDate to set
     */
    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }

    /**
     * @return the endDate
     */
    public String getEndDate() {
        return endDate;
    }

    /**
     * @param endDate the endDate to set
     */
    public void setEndDate(String endDate) {
        this.endDate = endDate;
    }

    /**
     * @return the userID
     */
    public Long getUserID() {
        return userID;
    }

    /**
     * @param userID the userID to set
     */
    public void setUserID(Long userID) {
        this.userID = userID;
    }

    /**
     * @return the recommendationTypeDescription
     */
    public String getRecommendationTypeDescription() {
        return recommendationTypeDescription;
    }

    /**
     * @param recommendationTypeDescription the recommendationTypeDescription to set
     */
    public void setRecommendationTypeDescription(String recommendationTypeDescription) {
        this.recommendationTypeDescription = recommendationTypeDescription;
    }

    /**
     * @return the recommendationLevelDescription
     */
    public String getRecommendationLevelDescription() {
        return recommendationLevelDescription;
    }

    /**
     * @param recommendationLevelDescription the recommendationLevelDescription to set
     */
    public void setRecommendationLevelDescription(String recommendationLevelDescription) {
        this.recommendationLevelDescription = recommendationLevelDescription;
    }

    /**
     * @return the recommendationStatusDescription
     */
    public String getRecommendationStatusDescription() {
        return recommendationStatusDescription;
    }

    /**
     * @param recommendationStatusDescription the recommendationStatusDescription to set
     */
    public void setRecommendationStatusDescription(String recommendationStatusDescription) {
        this.recommendationStatusDescription = recommendationStatusDescription;
    }

    /**
     * @return the situationCategoryID
     */
    public int getSituationCategoryID() {
        return situationCategoryID;
    }

    /**
     * @param situationCategoryID the situationCategoryID to set
     */
    public void setSituationCategoryID(int situationCategoryID) {
        this.situationCategoryID = situationCategoryID;
    }

    /**
     * @return the situationCategoryDescription
     */
    public String getSituationCategoryDescription() {
        return situationCategoryDescription;
    }

    /**
     * @param situationCategoryDescription the situationCategoryDescription to set
     */
    public void setSituationCategoryDescription(String situationCategoryDescription) {
        this.situationCategoryDescription = situationCategoryDescription;
    }

    /**
     * @return the situationCategoryIDs
     */
    public String getSituationCategoryIDs() {
        return situationCategoryIDs;
    }

    /**
     * @param situationCategoryIDs the situationCategoryIDs to set
     */
    public void setSituationCategoryIDs(String situationCategoryIDs) {
        this.situationCategoryIDs = situationCategoryIDs;
    }
    
}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/Utilities/UtilityFacade.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.Utilities;

/**
 * A Utility Holder, Holds singleton instances of the all utility classes used 
 * in this application.
 * <p>
 */
public class UtilityFacade {
  
  /**
   * prepares and returns ComputationUtilityMethods Instance
   * <p>
   * 
   * @return ComputationUtilityMethods
   */
  public static ComputationUtilityMethods getComputationUtility(){
    return ComputationUtilityMethods.getComputationUtilityMethods();
  }
  /**
   * prepares and returns DisibilitiesUtility Instance
   * <p>
   * 
   * @return DisibilitiesUtility
   */
  public static DisibilitiesUtility getDisibilityUtility(){
    return DisibilitiesUtility.getDisibilitiesUtility();
  }
  
  /**
   * prepares and returns FactsDictionary Instance
   * <p>
   * 
   * @return FactsDictionary
   */
  public static FactsDictionary getFactsDictionaryUtility(){
    return FactsDictionary.getFactsDictionary();
  }
  
  /**
   * prepares and returns RiskFactorFinderUtility Instance
   * <p>
   * 
   * @return RiskFactorFinderUtility
   */
  public static RiskFactorFinderUtility getRiskFinderUtility(){
    return RiskFactorFinderUtility.getRiskFactorFinderUtility();
  }
  
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/OntologyTools/AbstractOntology.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.OntologyTools;

import com.hp.hpl.jena.ontology.OntModel;
/**
 * Abstract Ontology contains all Function required by Context Ontologies
 * for handling and manipulation of Ontologies.  It provides Most Common methods 
 * for  * re-use purpose by implementing Pattern
 * 
 * @author <NAME>
 * @version 2.5
 * @since 2016-10-28
 */
public abstract class AbstractOntology {
	
	public abstract OntModel getCtxModel();
	public abstract void setCtxModel(OntModel ctxModel);
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/utils/FileUtil.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Kang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.utils;

public class FileUtil {
	
	String path = "./log";
	/*
	public static String getPath(){
		String curPath = FileUtil.class.getProtectionDomain().getCodeSource().getLocation().getFile()+"";
		
		return System.getProperty("user.dir")+"";
	}*/
	
	final static String webPath;
	final static String rootPath;
	
	public static String getWebPath(){
		return webPath;
	}
	public static String getRootPath(){
		return rootPath;
	}
	static{
		webPath = FileUtil.class.getProtectionDomain().getCodeSource().getLocation().getFile()+"";
		
		int cnt = 0;
		String temp = "";
		for(int i = webPath.length()-1; i>=0; i--){
			System.out.print(webPath.charAt(i));
			if(webPath.charAt(i) == '/')cnt++;
			
			if(cnt == 3){
				temp = webPath.substring(0, i+1);
				break;
			}
		}
		rootPath = temp;
	}
}


<|start_filename|>information-curation-layer/low-level-context-awareness/FILES/iclconfig.json<|end_filename|>
{"WindowConfig":{"Activity":6,"Emotion":9,"Location":12},"HLCAddress":"http://localhost:8080/icl_whole/icl/llc/","DCLAddress":"http://172.16.31.10:8080/MMDataCurationRestfulService/webresources/InformationCuration/","HLCDelay":20,"LLCAddress":"http://localhost:8080/icl_whole/icl/llc/","ActiveRecognizers":{"SER":true,"VAR":true,"LR":true,"IAR":true,"ER":true}}

<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/restservices/RestClients.java<|end_filename|>
/*
Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.mm.icl.llc.restservices;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.uclab.mm.icl.llc.LLCManager.LLCNotifier;
import org.uclab.mm.icl.llc.LLCManager.ContextLabel;
import org.uclab.mm.icl.llc.config.ContextType;
import org.uclab.mm.icl.llc.config.ICLConfig;
import org.uclab.mm.icl.utils.TimeUtil;

public class RestClients {
	private final static Logger logger = Logger.getLogger(RestClients.class);
	
	public static String[] labels = {"Running","Walking","Sitting","Subway","Bus","Cycling","LyingDown","Standing", "Jogging", "Hiking" ,"ClimbingStairs", "Descending","Stretching", "Dancing", "Sweeping", "Eating" ,"Escalator", "Elevator", "Resting", "UnidentifiedActivity", "NoActivity"};
	
	/**
	 * 
	 * @param str String which will be converted into predefined integer, which is used through Mining Minds project
	 * @return integer corresponding to the String Activity
	 */
	public static synchronized int getIndex(String str)  {
		int ret = 21;
		for(int i = 0; i<labels.length; i++){
			if(labels[i].equals(str)){
				return i+1;
			}
		}
		return ret;
	}
	
	
	
	
	
	/**
	 * This function calls the rest service of DCL to send user detected location
	 * @param loc Location which will be transfered into DCL
	 * @return State string describing the operation
	 * @throws Exception exception caused during the transfer, mainly HTTP exception
	 */
	public static synchronized String addUserDetectedLoc(ContextLabel loc) throws Exception{
		URL url = new URL(ICLConfig.DCLAddress+"AddUserDetectedLocation");
		URLConnection connection = url.openConnection();
		connection.setDoOutput(true);
		connection.setRequestProperty("Content-Type", "application/json");
		connection.setConnectTimeout(5000);
		connection.setReadTimeout(5000);
		
		OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
		//String input = new String("{\"points\": [{\"X\": 33.3333,\"Y\": 33.3333,\"Z\": 33.3333,\"FrameIndex\": 1}],\"timestamp_kinect\": \"its string\",\"user_id\": 123}"); 
		
		JSONObject json = new JSONObject();
		//json.put("userDetectedLocationId", "1");
		json.put("userId", Long.toString(loc.getUserID()));
		json.put("locationLabel", loc.getLabel());
		json.put("startTime", loc.getTimeStamp());
		out.write(json.toString());
		out.close();
		BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		String str = in.readLine();
		return str;
	}
	
	/**
	 * This function calls the rest service of DCL to send user detected emotion
	 * @param emo loc Emotion which will be transfered into DCL
	 * @return State string describing the operation
	 * @throws Exception  exception caused during the transfer, mainly HTTP exception
	 */ 
	public static synchronized String addUserRecognizedEmotion(ContextLabel emo) throws Exception{
		URL url = new URL(ICLConfig.DCLAddress+"AddUserRecognizedEmotion");
		URLConnection connection = url.openConnection();
		connection.setDoOutput(true);
		connection.setRequestProperty("Content-Type", "application/json");
		connection.setConnectTimeout(5000);
		connection.setReadTimeout(5000);
		
		OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
		//String input = new String("{\"points\": [{\"X\": 33.3333,\"Y\": 33.3333,\"Z\": 33.3333,\"FrameIndex\": 1}],\"timestamp_kinect\": \"its string\",\"user_id\": 123}"); 
		
		JSONObject json = new JSONObject();
		
		//json.put("userDetectedLocationId", "1");
		json.put("userId", Long.toString(emo.getUserID()));
		json.put("emotionLabel", emo.getLabel());
		json.put("startTime", emo.getTimeStamp());
		out.write(json.toString());
		out.close();

		BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		String str = in.readLine();
		return str;
	}
	
	/**
	 * 
	 * @param userID user ID which will be transfered into DCL
	 * @param hlcdesc description of high level context
	 * @param StartTime start time of high level context
	 * @return State string describing the operation
	 * @throws Exception exception caused during the transfer, mainly HTTP exception
	 */
	public static synchronized String addUserRecognizedHLC(long userID, String hlcdesc, String StartTime) throws Exception{
		
		
		URL url = new URL(ICLConfig.DCLAddress+"AddUserRecognizedHLC");
		URLConnection connection = url.openConnection();
		connection.setDoOutput(true);
		connection.setRequestProperty("Content-Type", "application/json");
		connection.setConnectTimeout(5000);
		connection.setReadTimeout(5000);
		
		OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
		//String input = new String("{\"points\": [{\"X\": 33.3333,\"Y\": 33.3333,\"Z\": 33.3333,\"FrameIndex\": 1}],\"timestamp_kinect\": \"its string\",\"user_id\": 123}"); 
		
		JSONObject json = new JSONObject();
		
		//json.put("userDetectedLocationId", "1");
		json.put("userId", Long.toString(userID));
		json.put("hLCLabel", hlcdesc);
		json.put("startTime", StartTime);
		out.write(json.toString());
		out.close();

		BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		
		String str=in.readLine();
		/**/
		
		return str;
	}
	
	/**
	 * 
	 * @param act low level activity which will be transfered into DCL
	 * @return State string describing the operation
	 * @throws Exception exception caused during the transfer, mainly HTTP exception
	 */
	public static synchronized String addUserRecognizedAct(ContextLabel act) throws Exception{
		URL url = new URL(ICLConfig.DCLAddress+"AddUserRecognizedActivity");
		URLConnection connection = url.openConnection();
		connection.setDoOutput(true);
		connection.setRequestProperty("Content-Type", "application/json");
		connection.setConnectTimeout(5000);
		connection.setReadTimeout(5000);
		
		OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
		
		JSONObject json = new JSONObject();
		
		json.put("userId", Long.toString(act.getUserID()));
		json.put("activityId", getIndex(act.getLabel()));
		json.put("startTime", act.getTimeStamp());
		out.write(json.toString());
		out.close();

		BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		String str = in.readLine();
		return str;
	}
	
	
	
	public static synchronized void sendDemo(String userID, String act, String emo, String loc, String food, String con, String cate, String timeStamp) throws Exception{
		//http://192.168.127.12/gathering.php?userid=36&time=10:50:09&act=Standing&emo=Happiness&loc=Home&food=Meat&con=Fat
		
		
		String actG = LLCNotifier.noActivity;
		String emoG = LLCNotifier.noEmotion;
		String locG = LLCNotifier.noLocation;
		String fdG = LLCNotifier.noFood;
		String conG = LLCNotifier.noHLC;
		String foodCate = LLCNotifier.noCat;
		
		if(!act.equals(LLCNotifier.noActivity))actG = act;
		if(!emo.equals(LLCNotifier.noEmotion))emoG = emo;
		if(!loc.equals(LLCNotifier.noLocation))locG = loc;
		if(!food.equals(LLCNotifier.noFood))fdG = food;
		if(!con.equals(LLCNotifier.noHLC)){
			conG = con;
		}
		if(!cate.equals(LLCNotifier.noCat)){
			foodCate = cate;
		}
		/*
		Random r = new Random();
		String[] foods = {"Grain", "Meat", "SeaFood", "Eggs", "MilkAndDairyProducts", "Legumes", "Nuts", "Fruits", "Vegetable", "Snacks" };
		fdG = foods[(Math.abs(r.nextInt()))%(foods.length)];
		*/
		
		
		try {
			
			TimeUtil tutil = new TimeUtil();
			String ts = tutil.toDemoStr(Calendar.getInstance());
			String query = "?userid="+userID+"&"+"time="+ts+"&act="+actG+"&emo="+emoG+"&loc="+locG+"&food="+fdG+"&con="+conG+"&foodCate="+foodCate;//"?time="+timeStamp+"&act="+actG+"&emo="+emoG+"&loc="+locG+"&con=NoHighLevel";
			
			 String ENDPOINT ="http://163.180.116.210/gathering.php";
	         String charset = "UTF-8";
	         logger.info("query to Jaehun's visualization module is " + ENDPOINT + query);
	         java.net.URLConnection connection = new URL(ENDPOINT + query).openConnection();
	         connection.setRequestProperty("Accept-Charset", charset);
	         //actG = emoG = locG = conG = "no";
	         if ( connection instanceof HttpURLConnection)
	         {
	            HttpURLConnection httpConnection = (HttpURLConnection) connection;
	            logger.info("result of query : " + httpConnection.getResponseCode() + " " + httpConnection.getResponseMessage());
	         }
	         
		} catch (Exception e) {
			
			logger.error(e);
		}
		
	}
	
	/**
	 * Counter class, for demo
	 * @author Nailbrainz
	 *
	 */
	
	/*
	static class Counter implements Runnable{
		@Override
		public synchronized void run() {
			try {
				wait(1500);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
			// TODO Auto-generated method stub
				while(true){
					try {
						wait(3000);
						TimeUtil tutil = new TimeUtil();
						String timeStamp = tutil.toDemoStr(Calendar.getInstance());
						String query = "?time="+timeStamp+"&act="+actG+"&emo="+emoG+"&loc="+locG+"&con="+conG;//"?time="+timeStamp+"&act="+actG+"&emo="+emoG+"&loc="+locG+"&con=NoHighLevel";
						actG = "noActivity";
						emoG = "noEmotion";
						locG = "noLocation";
						conG = "NoHighLevel";
						System.out.println("query is " + query);
						 String ENDPOINT ="http://163.180.116.210/gathering.php";
				         String charset = "UTF-8";
				         java.net.URLConnection connection = new URL(ENDPOINT + query).openConnection();
				         connection.setRequestProperty("Accept-Charset", charset);
				         //actG = emoG = locG = conG = "no";
				         if ( connection instanceof HttpURLConnection)
				         {
				            HttpURLConnection httpConnection = (HttpURLConnection) connection;
				            System.out.println(httpConnection.getResponseCode() + " " + httpConnection.getResponseMessage());
				         }
				         else
				         {
				        	 System.out.println("error!");
				         }
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
				
			}
		}

	
	/**
	 * 
	 * @param label label to notify DCL
	 * @param userID corresponding user ID
	 * @param timeStamp corresponding TimeStamp
	 * @throws IOException exception related to socket
	 */
    public static void notifyChange(String label, long userID, String timeStamp) throws IOException{
    	
    	logger.info("notifyChange called with "+ label + " " + userID + " " + timeStamp);
    	
   	URL url = null;
		try {
			url = new URL(ICLConfig.LLCAddress+"updatellc");
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			logger.error(e);
		}
		URLConnection connection = null;
		try {
			connection = url.openConnection();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.error("Error at ");
			logger.error(e);
		}
		connection.setDoOutput(true);
		connection.setRequestProperty("Content-Type", "application/json");
		connection.setConnectTimeout(5000);
		connection.setReadTimeout(5000);
		
		OutputStreamWriter out = null;
		try {
			out = new OutputStreamWriter(connection.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.error(e);
		}
		//String input = new String("{\"points\": [{\"X\": 33.3333,\"Y\": 33.3333,\"Z\": 33.3333,\"FrameIndex\": 1}],\"timestamp_kinect\": \"its string\",\"user_id\": 123}"); 
		try {
			JSONObject llc = new JSONObject();
			llc.put("label", label);
			llc.put("userID", Long.toString(userID));
			llc.put("timeStamp", timeStamp);
			out.write(llc.toString());
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.error(e);
		}
		

		BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		String str = in.readLine();
		in.close();
		logger.info("result of notifyChange = " + str);
   }
    
    
    /**
	 * @throws IOException exception related to socket
	 */
    public static String getVarVersion() throws IOException{
    	
    	//if(label.equals("Sitting"))label = "Eating";
    	
   	URL url = null;
		try {
			url = new URL(ICLConfig.LLCAddress+"VARService/version");
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			logger.error(e);
		}
		URLConnection connection = null;
		try {
			connection = url.openConnection();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.error(e);
		}
		connection.setDoOutput(true);
		connection.setRequestProperty("Content-Type", "application/json");
		connection.setConnectTimeout(5000);
		connection.setReadTimeout(5000);
		/*
		OutputStreamWriter out = null;
		try {
			out = new OutputStreamWriter(connection.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//String input = new String("{\"points\": [{\"X\": 33.3333,\"Y\": 33.3333,\"Z\": 33.3333,\"FrameIndex\": 1}],\"timestamp_kinect\": \"its string\",\"user_id\": 123}"); 
		try {
			JSONObject llc = new JSONObject();
			llc.put("label", label);
			llc.put("userID", Long.toString(userID));
			llc.put("timeStamp", timeStamp);
			out.write(llc.toString());
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
*/
		BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		String str = in.readLine();
		in.close();
		return str;
   }
    
    public static synchronized String AddFoodLog(ContextLabel food) throws Exception{
		
    	
    	URL url = new URL("http://172.16.17.32:8080/testWeb/webresources/testweb/AddFoodLog");
		URLConnection connection = url.openConnection();
		connection.setDoOutput(true);
		connection.setRequestProperty("Content-Type", "application/json");
		connection.setConnectTimeout(5000);
		connection.setReadTimeout(5000);
		
		OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
		//String input = new String("{\"points\": [{\"X\": 33.3333,\"Y\": 33.3333,\"Z\": 33.3333,\"FrameIndex\": 1}],\"timestamp_kinect\": \"its string\",\"user_id\": 123}"); 
		
		JSONObject json = new JSONObject();
		//json.put("userDetectedLocationId", "1");
		json.put("userId", Long.toString(food.getUserID()));
		json.put("foodName", food.getLabel());
		json.put("eatingTime", food.getTimeStamp());
		out.write(json.toString());
		out.close();
		BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		String str = in.readLine();
		return str;
	}
	
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/test/HLC_SPARQL.java<|end_filename|>
/**
* http://stackoverflow.com/questions/37497621/jena-tdb-querying-a-named-model 
* https://github.com/giuseppefutia/lod-hackathon-2015/blob/master/csv-to-rdf/src/main/java/org/dvcama/csvtordf/triplify/Step04.java
* 
Copyright [2016] [<NAME> & <NAME>q]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.test;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.apache.jena.ext.com.google.common.collect.Lists;

import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ReadWrite;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.tdb.TDBFactory;

import mm.icl.hlc.ContextOntologyManager.ContextHandler;
import mm.icl.hlc.ContextOntologyManager.ContextOntologyManager;
import mm.icl.hlc.OntologyTools.Context;

public class HLC_SPARQL {
	
	static final String directory ="E:\\ICL_LOG\\TDB";         
	
/*	if (new File(directory).exists()) {
		for (File file : new File(directory).listFiles()) {
			file.delete();
		}
	} else {
		new File(directory).mkdirs();
	}
	*/
	
	
	static final String sparqlQueryHlc = 
			"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> "
			+ "PREFIX owl: <http://www.w3.org/2002/07/owl#> "
			+ "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> "
			+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "
			+ "PREFIX icl2: <http://www.miningminds.re.kr/icl/context/context-v2-5.owl#> "
			+ "SELECT ?hlc " //count(?hlc) As ?cnt "//?hlc "
			+ "WHERE { "
			+ "?hlc rdf:type icl2:PhysicalActivityContext. " //PhysicalActivityContext NutritionContext
			+ "} ";
//			+ "Group by ?hlc";
		
		
	public static void main(String[] args) {
	
		Dataset dataset = TDBFactory.createDataset(directory);
		dataset.begin(ReadWrite.READ);

		Model model = dataset.getDefaultModel();
		List<String> out = Lists.newArrayList();
		
		QueryExecution qe = QueryExecutionFactory.create(sparqlQueryHlc, dataset)  ;             //("select * {?s ?p ?o}",dataset);
		ResultSet rs = qe.execSelect();
		
		while (rs.hasNext()) {
			System.out.println("in the While");
			QuerySolution qs = rs.next();
			System.out.println(qs);
			String subject = qs.get("s").asNode().toString();
			
			System.out.println(subject);
		}
		System.out.println("End");
		dataset.end();
		dataset.close();
		

		
}
	}		
		
		
		
		
		
		

/*		ContextOntologyManager mng = new ContextOntologyManager(directory);
		
		if(mng.correctInitialization()) {
			Iterator<Context> it = ContextHandler.retrieveContextInstancesMatchingSparqlQuery(sparqlQueryHlc).iterator();
			while(it.hasNext()) {
				//your code that maeks async errors
				    try{
				    	System.out.println("------------------------");
				
				    	Context inst = it.next();
				    	inst.getCtxModel().write(System.out, "RDF/XML");
//						inst.getCtxModel().write(System.out, "Turtle");
				    	Thread.sleep(1);      ///////////////////////////// if want to add delay for visibility 5000
				    
				}
			catch(InterruptedException e){}
			}
		}
		else  {
			System.out.println("No HLC because there are no LLC _________");
		}*/
		
		
		
		
		
		
		
		
		


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/ContextOntologyManager/ContextHandler.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.ContextOntologyManager;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;

import mm.icl.hlc.OntologyTools.Context;
import mm.icl.hlc.OntologyTools.ContextOntology;
import mm.icl.hlc.OntologyTools.HLCA;
import mm.icl.hlc.OntologyTools.LowLevelContext;
import mm.icl.hlc.OntologyTools.NutritionContext;
import mm.icl.hlc.OntologyTools.PhysicalActivityContext;
import mm.icl.hlc.OntologyTools.ClinicalContext;

import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ReadWrite;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.tdb.TDB;
import com.hp.hpl.jena.tdb.TDBFactory;
/**
 * Context Handler: Subcomponent of the Context Ontology Manager which deals
 * with the retrieval and storage of Context instances from/in the Context
 * Ontology Storage.
 * 
 * @author <NAME> and <NAME>
 * @version 2.5
 * @since 2015-10-28
 */
public class ContextHandler extends AbstractHandler{
	
	private static Logger logger = Logger.getLogger(ContextHandler.class);
	
	
	/**
	 * Collection of Context Instances and Context Ontology stored in the
	 * Context Ontology Storage.
	 */
	private static ContextHandler contextHandler = null;
	private ContextHandler(){};
	protected ContextQueryGenerator contextQueryGenerator = ContextQueryGenerator.getContextQueryGenerator();   
	
	private static Dataset dataset;
	/**
	 * Context Ontology which represents the Mining Minds Context Model.
	 */
	
	
	private static ContextOntology ont;
	
	public ContextQueryGenerator getContextQueryGenerator() {
		return contextQueryGenerator;
	}
	public void setContextQueryGenerator(ContextQueryGenerator contextQueryGenerator) {
		this.contextQueryGenerator = contextQueryGenerator;
	}
	/**
	 * Method to initialize the Context Handler.
	 * 
	 * @param directory
	 *            Path to the directory where the Context Ontology Storage is
	 *            deployed.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 */
	public  void initialize(String directory, ContextOntology ont) {
	try {
		ContextHandler.dataset = TDBFactory.createDataset(directory);
		TDB.getContext().set(TDB.symUnionDefaultGraph, true);
		ContextHandler.ont = ont;} 
	catch (Exception e)
		{
			logger.error("Error while Initializing ContextHandler.  Message: " + e.getMessage());
			e.printStackTrace();
		}
	}
	/**
	 * Method to retrieve the previous instance of PhysicalActivity Context which is
	 * persisted in the Context Ontology Storage and to save the newly inferred
	 * PhysicalActivity Context instance.
	 * 
	 * @param newHlc
	 *            Instance of PhysicalActivity Context which has been newly inferred.
	 * @return PhysicalActivity Context instance which is previous to newHlc.
	 */
	public PhysicalActivityContext retrievePreviousHlcAndStoreNew(PhysicalActivityContext newHlc) { 
		
		
		dataset.begin(ReadWrite.WRITE);
		Query sparqlQuery = contextQueryGenerator.generateQueryForPreviousValidAndUnfinishedHlc(newHlc, ont); 
		QueryExecution qExec = QueryExecutionFactory.create(sparqlQuery, dataset);
		ResultSet rs = qExec.execSelect();
		PhysicalActivityContext previousHlc = null;
		
	try {
		if (rs.hasNext()) {
			Model inst = dataset.getNamedModel(rs.next().getResource(HLCA.hlcSparqlVar).getURI());
			OntModel previousHlcModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, inst);
			previousHlc = new PhysicalActivityContext(previousHlcModel, ont);
			previousHlc.setDataPropertyValue(ont.getEndTimeProp(), newHlc.getDataPropertyValue(ont.getStartTimeProp()));
		}
		else {
			sparqlQuery = contextQueryGenerator.generateQueryForPreviousValidAndFinishedHlc(newHlc, ont);
			qExec = QueryExecutionFactory.create(sparqlQuery, dataset);
			rs = qExec.execSelect();
			if (rs.hasNext()) {
				Model inst = dataset.getNamedModel(rs.next().getResource(HLCA.hlcSparqlVar).getURI());
				OntModel previousHlcModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, inst);
				previousHlc = new PhysicalActivityContext(previousHlcModel, ont);
				newHlc.setDataPropertyValue(ont.getEndTimeProp(),
						previousHlc.getDataPropertyValue(ont.getEndTimeProp()));
				previousHlc.setDataPropertyValue(ont.getEndTimeProp(),
						newHlc.getDataPropertyValue(ont.getStartTimeProp()));
			}
			else {
				sparqlQuery = contextQueryGenerator.generateQueryForStartTimeOfNextHlc(newHlc, ont); 
				qExec = QueryExecutionFactory.create(sparqlQuery, dataset);
				rs = qExec.execSelect();
				if (rs.hasNext()) {
					QuerySolution soln = rs.next();
					Iterator<String> it = soln.varNames();
					if (it.hasNext())
						newHlc.setDataPropertyValue(ont.getEndTimeProp(), soln.getLiteral(it.next()));
				}
			}
		}
		}

		catch (Exception e) {
								logger.error("Error while Processing PhysicalActivityHLCContext.  Message: " + e.getMessage());
								e.printStackTrace();
							}
		dataset.addNamedModel(newHlc.getCtxInstanceName(), newHlc.getCtxModel());
		dataset.commit();
		dataset.end();
		return previousHlc;
	}
	/**
	 * Method to retrieve the previous instance of Nutrition Context which is
	 * persisted in the Context Ontology Storage and to save the newly inferred
	 * Nutrition Context instance.
	 * 
	 * @param newHlc
	 *            Instance of Nutrition Context which has been newly inferred.
	 * @return Nutrition Context instance which is previous to newHlc.
	 */
	public NutritionContext retrievePreviousHlcAndStoreNew(NutritionContext newHlc) {     
		dataset.begin(ReadWrite.WRITE);
		Query sparqlQuery = contextQueryGenerator.generateQueryForPreviousValidAndUnfinishedHlc(newHlc, ont);
		QueryExecution qExec = QueryExecutionFactory.create(sparqlQuery, dataset);
		ResultSet rs = qExec.execSelect();
		NutritionContext previousHlc = null;
	try{	
		if (rs.hasNext()) {
			Model inst = dataset.getNamedModel(rs.next().getResource(HLCA.hlcSparqlVar).getURI());
			OntModel previousHlcModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, inst);
			previousHlc = new NutritionContext(previousHlcModel, ont);
			previousHlc.setDataPropertyValue(ont.getEndTimeProp(), newHlc.getDataPropertyValue(ont.getStartTimeProp()));
		}
		else {
			sparqlQuery = contextQueryGenerator.generateQueryForPreviousValidAndFinishedHlc(newHlc, ont);
			qExec = QueryExecutionFactory.create(sparqlQuery, dataset);
			rs = qExec.execSelect();
			if (rs.hasNext()) {
				Model inst = dataset.getNamedModel(rs.next().getResource(HLCA.hlcSparqlVar).getURI());
				OntModel previousHlcModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, inst);
				previousHlc = new NutritionContext(previousHlcModel, ont);
				newHlc.setDataPropertyValue(ont.getEndTimeProp(),
						previousHlc.getDataPropertyValue(ont.getEndTimeProp()));
				previousHlc.setDataPropertyValue(ont.getEndTimeProp(),
						newHlc.getDataPropertyValue(ont.getStartTimeProp()));
			}
			else {
				sparqlQuery = contextQueryGenerator.generateQueryForStartTimeOfNextHlc(newHlc, ont);
				qExec = QueryExecutionFactory.create(sparqlQuery, dataset);
				rs = qExec.execSelect();
				if (rs.hasNext()) {
					QuerySolution soln = rs.next();
					Iterator<String> it = soln.varNames();
					if (it.hasNext())
						newHlc.setDataPropertyValue(ont.getEndTimeProp(), soln.getLiteral(it.next()));
				}
			}
		}
	}
	
	catch (Exception e) {
		logger.error("Error while Processing retrievePreviousHlcAndStoreNew Nutrition Context.  Message: " + e.getMessage());
		e.printStackTrace();
	}
		dataset.addNamedModel(newHlc.getCtxInstanceName(), newHlc.getCtxModel());
		dataset.commit();
		dataset.end();
		return previousHlc;
	}
	/**
	 * Method to retrieve the previous instance of PhysicalActivity Context which is
	 * persisted in the Context Ontology Storage and to save the newly inferred
	 * PhysicalActivity Context instance.
	 * 
	 * @param newHlc
	 *            Instance of PhysicalActivity Context which has been newly inferred.
	 * @return PhysicalActivity Context instance which is previous to newHlc.
	 */
	public ClinicalContext retrievePreviousHlcAndStoreNew(ClinicalContext newHlc) { 
			
		dataset.begin(ReadWrite.WRITE);
		Query sparqlQuery = contextQueryGenerator.generateQueryForPreviousValidAndUnfinishedHlc(newHlc, ont); 
		QueryExecution qExec = QueryExecutionFactory.create(sparqlQuery, dataset);
		ResultSet rs = qExec.execSelect();
		ClinicalContext previousHlc = null;
		
	try {
		if (rs.hasNext()) {
			Model inst = dataset.getNamedModel(rs.next().getResource(HLCA.hlcSparqlVar).getURI());
			OntModel previousHlcModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, inst);
			previousHlc = new ClinicalContext(previousHlcModel, ont);
			previousHlc.setDataPropertyValue(ont.getEndTimeProp(), newHlc.getDataPropertyValue(ont.getStartTimeProp()));
		}
		else {
			sparqlQuery = contextQueryGenerator.generateQueryForPreviousValidAndFinishedHlc(newHlc, ont);
			qExec = QueryExecutionFactory.create(sparqlQuery, dataset);
			rs = qExec.execSelect();
			if (rs.hasNext()) {
				Model inst = dataset.getNamedModel(rs.next().getResource(HLCA.hlcSparqlVar).getURI());
				OntModel previousHlcModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, inst);
				previousHlc = new ClinicalContext(previousHlcModel, ont);
				newHlc.setDataPropertyValue(ont.getEndTimeProp(),
						previousHlc.getDataPropertyValue(ont.getEndTimeProp()));
				previousHlc.setDataPropertyValue(ont.getEndTimeProp(),
						newHlc.getDataPropertyValue(ont.getStartTimeProp()));
			}
			else {
				sparqlQuery = contextQueryGenerator.generateQueryForStartTimeOfNextHlc(newHlc, ont); 
				qExec = QueryExecutionFactory.create(sparqlQuery, dataset);
				rs = qExec.execSelect();
				if (rs.hasNext()) {
					QuerySolution soln = rs.next();
					Iterator<String> it = soln.varNames();
					if (it.hasNext())
						newHlc.setDataPropertyValue(ont.getEndTimeProp(), soln.getLiteral(it.next()));
				}
			}
		}
		}

		catch (Exception e) {
								logger.error("Error while Processing ClinicalHLCContext.  Message: " + e.getMessage());
								e.printStackTrace();
							}
		dataset.addNamedModel(newHlc.getCtxInstanceName(), newHlc.getCtxModel());
		dataset.commit();
		dataset.end();
		return previousHlc;
	}
	/**
	 * Method to store the newly mapped Low Level Context instance into the
	 * Context Ontology Storage.
	 * 
	 * @param newLlc
	 *            Instance of Low Level Context which has been newly mapped and
	 *            has to be stored.
	 */
	public  void storeNewLlc(LowLevelContext newLlc) {
		dataset.begin(ReadWrite.WRITE);
		Query sparqlQuery = contextQueryGenerator.generateQueryForPreviousValidAndUnfinishedLlc(newLlc, ont);
		QueryExecution qExec = QueryExecutionFactory.create(sparqlQuery, dataset);
		ResultSet rs = qExec.execSelect();
	try{	
		if (rs.hasNext()) {
			Model inst = dataset.getNamedModel(rs.next().getResource(HLCA.llcSparqlVar).getURI()); 
			OntModel previousLlcModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, inst);
			LowLevelContext previousLlc = new LowLevelContext(previousLlcModel, ont);
			previousLlc.setDataPropertyValue(ont.getEndTimeProp(), newLlc.getDataPropertyValue(ont.getStartTimeProp()));
		}
		else {
			sparqlQuery = contextQueryGenerator.generateQueryForPreviousValidAndFinishedLlc(newLlc, ont);
			qExec = QueryExecutionFactory.create(sparqlQuery, dataset);
			rs = qExec.execSelect();
			if (rs.hasNext()) {
				Model inst = dataset.getNamedModel(rs.next().getResource(HLCA.llcSparqlVar).getURI());
				OntModel previousLlcModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, inst);
				LowLevelContext previousLlc = new LowLevelContext(previousLlcModel, ont);
				newLlc.setDataPropertyValue(ont.getEndTimeProp(),
						previousLlc.getDataPropertyValue(ont.getEndTimeProp()));
				previousLlc.setDataPropertyValue(ont.getEndTimeProp(),
						newLlc.getDataPropertyValue(ont.getStartTimeProp()));
			}
			else {
				sparqlQuery = contextQueryGenerator.generateQueryForStartTimeOfNextLlc(newLlc, ont);
				qExec = QueryExecutionFactory.create(sparqlQuery, dataset);
				rs = qExec.execSelect();
				if (rs.hasNext()) {
					QuerySolution soln = rs.next();
					Iterator<String> it = soln.varNames();
					if (it.hasNext())
						newLlc.setDataPropertyValue(ont.getEndTimeProp(), soln.getLiteral(it.next()));
				}
			}
		}
	}
	catch (Exception e) {
		logger.error("Error while Storing New LLC.  Message: " + e.getMessage());
		e.printStackTrace();
	}
		dataset.addNamedModel(newLlc.getCtxInstanceName(), newLlc.getCtxModel());
		dataset.commit();
		dataset.end(); 
	}
	/**
	 * Method to finalize, i.e., to set the end time of, the previous Low Level
	 * Context instance stored in the Context Ontology Storage.
	 * 
	 * @param category
	 *            Ontology class defining the category (e.g., location, emotion,
	 *            food or location) of the LLC which should be finalized.
	 * @param user
	 *            Ontology individual representing the user for which the LLC
	 *            should be finalized.
	 * @param time
	 *            Literal describing the end time that should be set to the
	 *            stored LLC.
	 */
	public void finalizePreviousLlc(OntClass category, Resource user, Literal time) {
		dataset.begin(ReadWrite.WRITE);
		Query sparqlQuery = contextQueryGenerator.generateQueryForPreviousValidAndUnfinishedLlc(category, user, time,
				ont);
		QueryExecution qExec = QueryExecutionFactory.create(sparqlQuery, dataset);
		ResultSet rs = qExec.execSelect();
	try {	
		if (rs.hasNext()) {
			Model inst = dataset.getNamedModel(rs.next().getResource(HLCA.llcSparqlVar).getURI());
			OntModel previousLlcModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, inst);
			LowLevelContext previousLlc = new LowLevelContext(previousLlcModel, ont);
			previousLlc.setDataPropertyValue(ont.getEndTimeProp(), time);
		}
		else {
			sparqlQuery = contextQueryGenerator.generateQueryForPreviousValidAndFinishedLlc(category, user, time, ont);
			qExec = QueryExecutionFactory.create(sparqlQuery, dataset);
			rs = qExec.execSelect();
			if (rs.hasNext()) {
				Model inst = dataset.getNamedModel(rs.next().getResource(HLCA.llcSparqlVar).getURI());
				OntModel previousLlcModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, inst);
				LowLevelContext previousLlc = new LowLevelContext(previousLlcModel, ont);
				previousLlc.setDataPropertyValue(ont.getEndTimeProp(), time);
			}
		}
		
	}
	catch (Exception e) {
		logger.error("Error while finalizing Previous LLC.  Message: " + e.getMessage());
		e.printStackTrace();
	}

		dataset.commit();
		dataset.end();
	}
	/**
	 * Method to retrieve from the Context Ontology Storage the Low Level
	 * Context instances which are concurrent at the start time of a Low Level
	 * Context instance.
	 * 
	 * @param llc
	 *            Instance of Low Level Context.
	 * @return List of Low Level Context Instances which are concurrent at the
	 *         start time of llc.
	 */
	public  List<LowLevelContext> retrieveConcurrentLlcAtStartTime(LowLevelContext llc) {
		Query sparqlQuery = contextQueryGenerator.generateQueryForConcurrentAtStartTimeUnfinishedLlc(llc, ont);
		ResultSet results = executeSparqlQuery(sparqlQuery);
		List<LowLevelContext> llcList = (List<LowLevelContext>) (List<?>) getContextForSparqlResults(results);
		sparqlQuery = contextQueryGenerator.generateQueryForConcurrentAtStartTimeFinishedLlc(llc, ont);
		results = executeSparqlQuery(sparqlQuery);
		llcList.addAll((List<LowLevelContext>) (List<?>) getContextForSparqlResults(results));
		return llcList;
	}
	/**
	 * Method to retrieve from the Context Ontology Storage the Low Level
	 * Context instances which are concurrent at the end time of a Low Level
	 * Context instance.
	 * 
	 * @param llc
	 *            Instance of Low Level Context.
	 * @return List of Low Level Context Instances which are concurrent at the
	 *         end time of llc.
	 */
	public List<LowLevelContext> retrieveConcurrentLlcAtEndTime(LowLevelContext llc) {
		Query sparqlQuery = contextQueryGenerator.generateQueryForConcurrentAtEndTimeUnfinishedLlc(llc, ont);
		ResultSet results = executeSparqlQuery(sparqlQuery);
		List<LowLevelContext> llcList = (List<LowLevelContext>) (List<?>) getContextForSparqlResults(results);
		sparqlQuery = contextQueryGenerator.generateQueryForConcurrentAtEndTimeFinishedLlc(llc, ont);
		results = executeSparqlQuery(sparqlQuery);
		llcList.addAll((List<LowLevelContext>) (List<?>) getContextForSparqlResults(results));
		return llcList;
	}
	/**
	 * Method to retrieve from the Context Ontology Storage all the Low Level
	 * Context instances which have their start time within a time window.
	 * 
	 * @param windowStart
	 *            xsd:dateTime typed Literal representing the start time of the
	 *            window.
	 * @param windowEnd
	 *            xsd:dateTime typed Literal representing the end time of the
	 *            window.
	 * @return List of Low Level Context instances which have their start time
	 *         within the time window
	 */
	public List<LowLevelContext> retrieveLlcStartingWithinWindow(Literal windowStart, Literal windowEnd) {
		Query sparqlQuery = contextQueryGenerator.generateQueryForLlcWithStartTimeInWindow(windowStart, windowEnd, ont);
		ResultSet results = executeSparqlQuery(sparqlQuery);
		List<LowLevelContext> llcList = (List<LowLevelContext>) (List<?>) getContextForSparqlResults(results);
		return llcList;
	}
	/**
	 * Method to retrieve from the Context Ontology Storage all the Low Level
	 * Context instances which have their end time within a time window and
	 * which do not have a contiguous Low Level Context instance.
	 * 
	 * @param windowStart
	 *            xsd:dateTime typed Literal representing the start time of the
	 *            window.
	 * @param windowEnd
	 *            xsd:dateTime typed Literal representing the end time of the
	 *            window.
	 * @return List of Low Level Context instances which have their end time
	 *         within the time window
	 */
	public List<LowLevelContext> retrieveLlcEndingWithinWindow(Literal windowStart, Literal windowEnd) {
		Query sparqlQuery = contextQueryGenerator.generateQueryForLlcWithEndTimeInWindowAndNoContiguousLlc(windowStart,
				windowEnd, ont);
		ResultSet results = executeSparqlQuery(sparqlQuery);
		return (List<LowLevelContext>) (List<?>) getContextForSparqlResults(results);
	}
	/**
	 * Method to retrieve the Context instances stored in the Context Ontology
	 * Storage which match a SPARQL query.
	 * 
	 * @param sparqlQuery
	 *            SPARQL query which defines the constraints that the Context
	 *            needs to meet.
	 * @return List of Context instances that match the sparqlQuery.
	 */
	public static List<Context> retrieveContextInstancesMatchingSparqlQuery(Query sparqlQuery) {
		ResultSet rs = executeSparqlQuery(sparqlQuery);
		return getContextForSparqlResults(rs);
	}
	/**
	 * Method to retrieve the Context instances stored in the Context Ontology
	 * Storage which match a SPARQL query.
	 * 
	 * @param sparqlQueryString
	 *            String encoding of the SPARQL query which defines the
	 *            constraints that the Context needs to meet.
	 * @return List of Context instances that match the sparqlQueryString.
	 */
	public static List<Context> retrieveContextInstancesMatchingSparqlQuery(String sparqlQueryString) {
		ResultSet rs = executeSparqlQuery(sparqlQueryString);
		return getContextForSparqlResults(rs);
	}
	/**
	 * Method to execute a SPARQL query on the Context instances stored in the
	 * Context Ontology Storage.
	 * 
	 * @param sparqlQuery
	 *            SPARQL query which defines the constraints that the Context
	 *            needs to meet.
	 * @return Set of results that match the sparqlQuery, presented in a
	 *         table-like manner.
	 */
	private static ResultSet executeSparqlQuery(Query sparqlQuery) {
		dataset.begin(ReadWrite.WRITE);
		QueryExecution qExec = QueryExecutionFactory.create(sparqlQuery, dataset);
		ResultSet rs = qExec.execSelect();
		dataset.commit();
		dataset.end();
		return rs;
	}
	/**
	 * Method to execute a SPARQL query on the Context instances stored in the
	 * Context Ontology Storage.
	 * 
	 * @param sparqlQueryString
	 *            String encoding of the SPARQL query which defines the
	 *            constraints that the Context needs to meet.
	 * @return Set of results that match the sparqlQueryString, presented in a
	 *         table-like manner.
	 */
	private static ResultSet executeSparqlQuery(String sparqlQueryString) {
		dataset.begin(ReadWrite.WRITE);
		QueryExecution qExec = QueryExecutionFactory.create(sparqlQueryString, dataset);
		ResultSet rs = qExec.execSelect();
		dataset.commit();
		dataset.end();
		return rs;
	}
	/**
	 * Method to get from the Context Ontology Storage the list of Context
	 * instances which are part of the result set of a SPARQL query.
	 * 
	 * @param rs
	 *            Set of results of a SPARQL query, presented in a table-like
	 *            manner.
	 * @return List of Context instances that match the sparqlQuery.
	 */
	private static List<Context> getContextForSparqlResults(ResultSet rs) {
		List<Context> results = new ArrayList<Context>();
		if (rs.getResultVars().contains(HLCA.hlcSparqlVar) && !rs.getResultVars().contains(HLCA.llcSparqlVar)) {
			while (rs.hasNext()) {
				OntModel hlcModel = getContextOntModel(rs.next(), HLCA.hlcSparqlVar);
				if (hlcModel != null)
					results.add(new PhysicalActivityContext(hlcModel, ont));
			}
		}
		else if (!rs.getResultVars().contains(HLCA.hlcSparqlVar) && rs.getResultVars().contains(HLCA.llcSparqlVar)) {
			while (rs.hasNext()) {
				OntModel llcModel = getContextOntModel(rs.next(), HLCA.llcSparqlVar);
				if (llcModel != null)
					results.add(new LowLevelContext(llcModel, ont));
			}
		}
		return results;
	}
	/**
	 * Method to get from the Context Ontology Storage the OntModel associated
	 * to the Context instance which is a solution of the SPARQL query.
	 * 
	 * @param sol
	 *            Solution which is part of the set of results of a SPARQL
	 *            query.
	 * @param varName
	 *            Name of the variable which is part of the results of a SPARQL
	 *            query.
	 * @return OntModel associated to the Context which is a solution of the
	 *         SPARQL query.
	 */
	private static OntModel getContextOntModel(QuerySolution sol, String varName) {
		return getContextOntModel(sol.getResource(varName).getURI());
	}
	/**
	 * Method to get from the Context Ontology Storage the OntModel associated
	 * to the Context instance by its name.
	 * 
	 * @param modelName
	 *            Name of the Context instance.
	 * @return OntModel associated to the Context instance which name is
	 *         modelName.
	 */
	private static OntModel getContextOntModel(String modelName) {
		dataset.begin(ReadWrite.READ);
		Model inst = dataset.getNamedModel(modelName);
		dataset.end();
		if (inst.isEmpty())
			return null;
		return ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, inst);
	}
	/**
	 * Method to add to the Context Ontology Storage the OntModel associated to
	 * a Context instance.
	 * 
	 * @param modelName
	 *            Name of the Context instance.
	 * @param model
	 *            OntModel representation of the Context instance.
	 */
	private static void addContextOntModel(String modelName, OntModel model) {
		dataset.begin(ReadWrite.WRITE);
		dataset.addNamedModel(modelName, model);
		dataset.commit();
		dataset.end();
	}
	/**
	 * Method to update in the Context Ontology Storage the OntModel associated
	 * to a Context instance.
	 * 
	 * @param modelName
	 *            Name of the Context instance.
	 * @param model
	 *            OntModel representation of the Context instance.
	 */
	private static void updateContextOntModel(String modelName, OntModel model) {
		addContextOntModel(modelName, model);
	}
	
	public static ContextHandler getContextHandler(){
		if(contextHandler == null){
			contextHandler = new ContextHandler();
		}
		return contextHandler;
	}
	}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/framework/RecInterpreter/PARecInterpretations.java<|end_filename|>
/* Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.scl.framework.RecInterpreter;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.uclab.scl.communication.CommunicationManager;
import org.uclab.scl.interpreterdatamodel.Conclusion;
import org.uclab.scl.interpreterdatamodel.CurrentContext;
import org.uclab.scl.interpreterdatamodel.CurrentLocation;
import org.uclab.scl.interpreterdatamodel.FiredRule;
import org.uclab.scl.interpreterdatamodel.InterpretationIngredients;
import org.uclab.scl.framework.AbstractInterpreterPacket;
import org.uclab.scl.framework.RecInterpreter.Explanation.AbstractRecExplanation;
import org.uclab.scl.framework.RecInterpreter.PARecommender.ContextSelector;
import org.uclab.scl.framework.RecInterpreter.PARecommender.MultipleRecEvaluator;
import org.uclab.scl.framework.RecInterpreter.PARecommender.SingleRecEvaluator;
import org.uclab.scl.outputModel.InterpretationModel.InterpretedRecommendations;

public class PARecInterpretations {
	private static Logger LOG = LogManager.getLogger(PARecInterpretations.class);
	public static String description = "";
	public static String durationValue = "";
	private CurrentContext currentContext = new CurrentContext();
    CommunicationManager commManager = CommunicationManager.getCommunicationManager();
	private AbstractRecExplanation recExplanation;

	/**
	 * Receives control flow for Physical Recommendation and evaluates its
	 * contextually. If required generates an alternative recommendation. This
	 * function serves as a control unit for Recommendation Interpreter
	 * 
	 * @param interpreterPacket
	 */
	public void buildPARecInterpretations(AbstractInterpreterPacket interpreterPacket) {
		LOG.debug("Interpreting...");
		InterpretationIngredients interpretationIngredients = (InterpretationIngredients) interpreterPacket.getRecommendationInput();
		List<FiredRule> firedrule = interpretationIngredients.getFiredRule();
		String userID = interpretationIngredients.getUserID();
		String receivedContext = null;
		String recList = "";
		String key = "";
		String value = "";
		String operator = "";
		
		LOG.debug("Looping through rules...");
		for (FiredRule f : firedrule) {
			description = f.getRuleConclusion() + ",";
			LOG.debug("Received Description:", description);
			List<Conclusion> fireConclusionList = f.getConclusionList();
			for (Conclusion c : fireConclusionList) {
				key = c.getConclusionKey();
				LOG.debug("key: " + key);
				//. if (key.equalsIgnoreCase("Current Activity")) {
				if (key.equalsIgnoreCase("Recommended Activity")) {
					value = c.getConclusionValue() + ",";
					operator = c.getConclusionOperator() + ",";
					recList += value;
				} else if(key.equalsIgnoreCase("Activity Duration")){
					durationValue = c.getConclusionValue();
					LOG.debug("Activity Duration", durationValue);
				}
				else{
					//..Nothing
				}
			}
		}

		String lastCh = recList.substring(recList.length() - 1);
		if (lastCh.contains(","))
			recList = recList.substring(0, recList.length() - 1);
		LOG.debug("Received Recommendation:  {}", recList);
		CurrentContext currentContexts = new CurrentContext();
		//commManager.getCurrentContext(Long.parseLong(userID));
		if (!(currentContexts.getCurrentLocation().isEmpty())) {
			currentContext.setCurrentLocation(currentContexts.getCurrentLocation());
			for (CurrentLocation cl : currentContext.getCurrentLocation()) {
				receivedContext = cl.getLocationLabel();
				break;
			}
		} else {
			receivedContext = "UnidentifiedLocation";
			if (!(currentContexts.getCurrentHLC().isEmpty())) {
				currentContext.setCurrentHLC(currentContexts.getCurrentHLC());
				receivedContext += "," + currentContext.getCurrentHLC().get(0).gethLCLabel();
			} else {
				receivedContext += "," + "UnidentifiedHLC";
			}
			if (!(currentContexts.getCurrentWeather().isEmpty())) {
				currentContext.setCurrentWeather(currentContexts.getCurrentWeather());
				receivedContext += "," + currentContext.getCurrentWeather().get(0).getWeatherLabel();
			} else {
				receivedContext += "," + "UnidentifiedWeather";
			}
			if (!(currentContexts.getCurrentEmotion().isEmpty())) {
				currentContext.setCurrentEmotion(currentContexts.getCurrentEmotion());
				receivedContext += "," + currentContext.getCurrentEmotion().get(0).getEmotionLabel();
			} else {
				receivedContext += "," + "UnidentifiedEmotion";
			}
			receivedContext += ",No";
			
			LOG.debug("Current Context:"+ receivedContext);

			List<InterpretedRecommendations> interpretedRecs = new ArrayList<InterpretedRecommendations>();
			InterpretedRecommendations interpretedRec = new InterpretedRecommendations();
			LOG.debug("Before context selector");
			ContextSelector contextSelector = new ContextSelector();
			boolean userInterrupt = contextSelector.selectContext(receivedContext);
			if (!userInterrupt) {
				LOG.debug("User can't be Interrupted Now");
				interpretedRec.setCurrentContext(receivedContext);
			} else {
				LOG.debug("Recommendation Forwarded for Content Evaluation");
				AbstractRecEvaluator evaluator = getEvaluator(recList);
				int[] validRec = evaluator.evaluate(recList, userID, receivedContext);

				int[] tempRecVec = new int[validRec.length];
				System.arraycopy(validRec, 0, tempRecVec, 0, validRec.length);

				for (int i = 0; i < tempRecVec.length; i++) {
					if (validRec[i] == 1) {
						tempRecVec[i] = 1;
						try {
							interpretedRec = recExplanation.handleExplanation(tempRecVec, PARecInterpretations.durationValue, receivedContext, description);
						} catch (Exception e) {
							e.printStackTrace();
						}
						String ActType = null;						
						String url = null;
						try {
							ActType = recExplanation.parseAggregateVec(tempRecVec);						    
						    LOG.debug("URL Builder");
							url = recExplanation.buildUrl(ActType);
						} catch (Exception e) {
							e.printStackTrace();
						}

						interpretedRec.setRecURL(url);
						tempRecVec[i] = 0;
						interpretedRecs.add(interpretedRec);
					}
				}
			}
			interpreterPacket.setRecommendationOutput(interpretedRecs);
		} //. comment out
	}

	public AbstractRecExplanation getRecExpalanation() {
		return recExplanation;
	}

	public void setRecExpalanation(AbstractRecExplanation recExpalanation) {
		this.recExplanation = recExpalanation;
	}

	public AbstractRecEvaluator getEvaluator(String rec) {
		int contentLength = rec.split(",").length;
		AbstractRecEvaluator evaluator = null;

		switch (contentLength) {
		case 1:
			evaluator = new SingleRecEvaluator();
			break;
		default:
			evaluator = new MultipleRecEvaluator();
		}

		return evaluator;
	}

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/test/java/org/uclab/mm/datamodel/dc/dataadapter/testcases/PhysiologicalFactorsAdapterTest.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.dc.dataadapter.testcases;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.junit.Test;
import org.uclab.mm.datamodel.AbstractDataBridge;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.DatabaseStorage;
import org.uclab.mm.datamodel.dc.PhysiologicalFactors;
import org.uclab.mm.datamodel.dc.Users;
import org.uclab.mm.datamodel.dc.dataadapter.PhysiologicalFactorsAdapter;
import org.uclab.mm.datamodel.dc.dataadapter.UserDataAdapter;

/**
 * This is a class for testing the insertion, fetching, and update of PhysiologicalFactorsAdapter 
 * @author <NAME>
 *
 */

public class PhysiologicalFactorsAdapterTest {

	/**
	 * This is function for testing the insertion, fetching, and update of PhysiologicalFactorsAdapter 
	 */
	@Test
	public void testCRUDPhysiologicalFactors() {
				
		/* Preparing input object for insertion*/
		PhysiologicalFactors objOuterPhysiologicalFactors = new PhysiologicalFactors();
		PhysiologicalFactors objInnerPhysiologicalFactors = new PhysiologicalFactors();
		List<PhysiologicalFactors> objListPhysiologicalFactors = new  ArrayList<PhysiologicalFactors>();
		
		objOuterPhysiologicalFactors.setUserId(2L);
		objOuterPhysiologicalFactors.setWeight((float) 65.3);
		objOuterPhysiologicalFactors.setHeight((float) 6.1);
		objOuterPhysiologicalFactors.setDate("2014 05 02 00:00:00");
		objOuterPhysiologicalFactors.setIdealWeight((float) 60.5);
		objOuterPhysiologicalFactors.setTargetWeight((float) 61.9);
		
		/* Testing of insertion function*/
		 DataAccessInterface objDAInterface = new PhysiologicalFactorsAdapter();
         AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
         List<String> lstResponse = objADBridge.SavePhysiologicalFactors(objOuterPhysiologicalFactors);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerPhysiologicalFactors.setUserId(2L);
        	 DataAccessInterface objDAInterfaceRetrieval = new PhysiologicalFactorsAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListPhysiologicalFactors = objADBridgeRetrieval.RetrivePhysiologicalFactors(objInnerPhysiologicalFactors);
        	 objInnerPhysiologicalFactors = objListPhysiologicalFactors.get(0);
         }
         
         assertEquals(0, Double.compare(objOuterPhysiologicalFactors.getWeight(), objInnerPhysiologicalFactors.getWeight()));
         
         /* Testing of Update function*/
         objInnerPhysiologicalFactors.setWeight((float) 64.8);
         DataAccessInterface objDAInterfaceUpdate = new PhysiologicalFactorsAdapter();
         AbstractDataBridge objADBridgeUpdate = new DatabaseStorage(objDAInterfaceUpdate);
         lstResponse = objADBridgeUpdate.UpdatePhysiologicalFactors(objInnerPhysiologicalFactors);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerPhysiologicalFactors.setUserId(2L);
        	 DataAccessInterface objDAInterfaceRetrieval = new PhysiologicalFactorsAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListPhysiologicalFactors = objADBridgeRetrieval.RetrivePhysiologicalFactors(objInnerPhysiologicalFactors);
        	 objInnerPhysiologicalFactors = objListPhysiologicalFactors.get(0);
         }
         
         assertEquals(0, Double.compare(objInnerPhysiologicalFactors.getWeight(), (float) 64.8));
		
	}

}


<|start_filename|>supporting-layer/uiux-authoring-tool/JavaDoc/org/uclab/mm/sl/uiux/analytics/CustomVariables.html<|end_filename|>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_76-release) on Fri Dec 23 12:27:00 KST 2016 -->
<title>CustomVariables</title>
<meta name="date" content="2016-12-23">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
    try {
        if (location.href.indexOf('is-external=true') == -1) {
            parent.document.title="CustomVariables";
        }
    }
    catch(err) {
    }
//-->
var methods = {"i0":10,"i1":10,"i2":10};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!--   -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!--   -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/CustomVariables.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/BuildConfig.html" title="class in org.uclab.mm.sl.uiux.analytics"><span class="typeNameLink">Prev&nbsp;Class</span></a></li>
<li><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics"><span class="typeNameLink">Next&nbsp;Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/uclab/mm/sl/uiux/analytics/CustomVariables.html" target="_top">Frames</a></li>
<li><a href="CustomVariables.html" target="_top">No&nbsp;Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
  allClassesLink = document.getElementById("allclasses_navbar_top");
  if(window==top) {
    allClassesLink.style.display = "block";
  }
  else {
    allClassesLink.style.display = "none";
  }
  //-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary:&nbsp;</li>
<li>Nested&nbsp;|&nbsp;</li>
<li>Field&nbsp;|&nbsp;</li>
<li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail:&nbsp;</li>
<li>Field&nbsp;|&nbsp;</li>
<li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!--   -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.uclab.mm.sl.uiux.analytics</div>
<h2 title="Class CustomVariables" class="title">Class CustomVariables</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.uclab.mm.sl.uiux.analytics.CustomVariables</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="typeNameLabel">CustomVariables</span>
extends java.lang.Object</pre>
<div class="block">You can track up to 5 custom variables for each user to your app,
 and up to 5 custom variables for each screen view.
 <p/>
 Desired json output:
 {
 "1":["OS","iphone 5.0"],
 "2":["UIUXAnalytics Mobile Version","1.6.2"],
 "3":["Locale","en::en"],
 "4":["Num Accounts","2"],
 "5":["Level","over9k"]
 }</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!--   -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/CustomVariables.html#CustomVariables--">CustomVariables</a></span>()</code>
<div class="block">Instantiates a new Custom variables.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/CustomVariables.html#CustomVariables-org.uclab.mm.sl.uiux.analytics.CustomVariables-">CustomVariables</a></span>(<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/CustomVariables.html" title="class in org.uclab.mm.sl.uiux.analytics">CustomVariables</a>&nbsp;variables)</code>
<div class="block">Instantiates a new Custom variables.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!--   -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>org.json.JSONArray</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/CustomVariables.html#put-int-java.lang.String-java.lang.String-">put</a></span>(int&nbsp;index,
   java.lang.String&nbsp;name,
   java.lang.String&nbsp;value)</code>
<div class="block">Custom variable names and values are limited to 200 characters in length each.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>org.json.JSONArray</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/CustomVariables.html#put-java.lang.String-org.json.JSONArray-">put</a></span>(java.lang.String&nbsp;index,
   org.json.JSONArray&nbsp;values)</code>
<div class="block">Put json array.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/CustomVariables.html#toString--">toString</a></span>()</code>&nbsp;</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!--   -->
</a>
<h3>Methods inherited from class&nbsp;java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!--   -->
</a>
<h3>Constructor Detail</h3>
<a name="CustomVariables--">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>CustomVariables</h4>
<pre>public&nbsp;CustomVariables()</pre>
<div class="block">Instantiates a new Custom variables.</div>
</li>
</ul>
<a name="CustomVariables-org.uclab.mm.sl.uiux.analytics.CustomVariables-">
<!--   -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>CustomVariables</h4>
<pre>public&nbsp;CustomVariables(<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/CustomVariables.html" title="class in org.uclab.mm.sl.uiux.analytics">CustomVariables</a>&nbsp;variables)</pre>
<div class="block">Instantiates a new Custom variables.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>variables</code> - the variables</dd>
</dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!--   -->
</a>
<h3>Method Detail</h3>
<a name="put-int-java.lang.String-java.lang.String-">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>put</h4>
<pre>public&nbsp;org.json.JSONArray&nbsp;put(int&nbsp;index,
                              java.lang.String&nbsp;name,
                              java.lang.String&nbsp;value)</pre>
<div class="block">Custom variable names and values are limited to 200 characters in length each.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>index</code> - this Integer accepts values from 1 to 5.              A given custom variable name must always be stored in the same "index" per session.              For example, if you choose to store the variable name = "Gender" in index = 1              and you record another custom variable in index = 1, then the "Gender" variable              will be deleted and replaced with the new custom variable stored in index 1.              You may configure UIUXAnalytics to track more custom variables than 5.</dd>
<dd><code>name</code> - of a specific Custom Variable such as "User type".</dd>
<dd><code>value</code> - of a specific Custom Variable such as "Customer".</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>super.put result if index in right range and name/value pair aren't null</dd>
</dl>
</li>
</ul>
<a name="put-java.lang.String-org.json.JSONArray-">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>put</h4>
<pre>public&nbsp;org.json.JSONArray&nbsp;put(java.lang.String&nbsp;index,
                              org.json.JSONArray&nbsp;values)</pre>
<div class="block">Put json array.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>index</code> - index accepts values from 1 to 5.</dd>
<dd><code>values</code> - packed key/value pair</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>super.put result or null if key is null or value length is not equals 2</dd>
</dl>
</li>
</ul>
<a name="toString--">
<!--   -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>toString</h4>
<pre>public&nbsp;java.lang.String&nbsp;toString()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code>toString</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!--   -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!--   -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/CustomVariables.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/BuildConfig.html" title="class in org.uclab.mm.sl.uiux.analytics"><span class="typeNameLink">Prev&nbsp;Class</span></a></li>
<li><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics"><span class="typeNameLink">Next&nbsp;Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/uclab/mm/sl/uiux/analytics/CustomVariables.html" target="_top">Frames</a></li>
<li><a href="CustomVariables.html" target="_top">No&nbsp;Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
  allClassesLink = document.getElementById("allclasses_navbar_bottom");
  if(window==top) {
    allClassesLink.style.display = "block";
  }
  else {
    allClassesLink.style.display = "none";
  }
  //-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary:&nbsp;</li>
<li>Nested&nbsp;|&nbsp;</li>
<li>Field&nbsp;|&nbsp;</li>
<li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail:&nbsp;</li>
<li>Field&nbsp;|&nbsp;</li>
<li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!--   -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>


<|start_filename|>supporting-layer/uiux-authoring-tool/accounts/templates/accounts/login.html<|end_filename|>
{% extends "base_login.html" %}


{% block content %}

<div class="login_wrapper">
        <div class="animate form login_form">
          <section class="login_content">

              <h1>Login Form</h1>
               {% include "accounts/form.html" with form=form %}
              <div class="clearfix"></div>

              <div class="separator">
                <p class="change_link">New to site?
                  <a href="/accounts/register/" class="to_register"> Create Account </a>
                </p>

                <div class="clearfix"></div>
                <br />

                <div>

                  <p>©2016 All Rights Reserved.UI/UX Authoring Tool</p>
                </div>
              </div>

          </section>
        </div>


      </div>

{% endblock %}

<|start_filename|>data-curation-layer/active-data-reader/src/main/java/org/uclab/mm/dcl/adr/model/SLDataModel.java<|end_filename|>
/*
 * Copyright (C) 2016 <NAME>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Data Model of the Detected Location table. 
 *
 * @author <NAME>
 */
package org.uclab.mm.dcl.adr.model;

import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
 * Here you define the default table schema. based on the data schema we have
 * define the data id, name, attributes and values.
 */

public class SLDataModel {

	private final String data_id;
	private final String data_name;
	private final ArrayList<Object> data_attributes;
	private final LinkedHashMap<String, String> data_values;

	/**
	 * Constructs an empty list with an initial capacity of ten.
	 *
	 * @param data_id the data id
	 * @param data_name the data name
	 * @param data_attributes the data attributes
	 * @param data_values the data values
	 */
	public SLDataModel(String data_id, String data_name, ArrayList<Object> data_attributes,
			LinkedHashMap<String, String> data_values) {
		this.data_id = data_id;
		this.data_name = data_name;
		this.data_attributes = data_attributes;
		this.data_values = data_values;
	}

	/**
	 * Gets the data id.
	 *
	 * @return the data_id of the table stored in Aapche Hive
	 */
	public final String getData_id() {
		return data_id;
	}

	/**
	 * @return the data_name
	 */
	public final String getData_name() {
		return data_name;
	}

	/**
	 * @return the data_attributes
	 */
	public final ArrayList<Object> getData_attributes() {
		return data_attributes;
	}

	/**
	 * @return the data_values
	 */
	public final LinkedHashMap<String, String> getData_values() {
		return data_values;
	}

	

}

<|start_filename|>knowledge-curation-layer/i-kat/src/main/java/org/uclab/mm/kcl/edkat/dao/SituationDAOImpl.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.kcl.edkat.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.uclab.mm.kcl.edkat.datamodel.Condition;
import org.uclab.mm.kcl.edkat.datamodel.Rule;
import org.uclab.mm.kcl.edkat.datamodel.Situations;


/**
* This is interface for the situation this interface provides 
* create, update, retrieve of situations of some specific rule
 * @author  <NAME>
 * @version 1.0
 * @since   2015-08-16
 * */
@Repository
public class SituationDAOImpl implements SituationDAO {

	/**
	 * This creation of static object of logger for Situation 
	*/
	private static final Logger logger = LoggerFactory.getLogger(RuleDAOImpl.class);
	
	/**
	 * This creation of Session for factory  
	*/
	 private SessionFactory sessionFactory;
    
   public void setSessionFactory(SessionFactory sf){
       this.sessionFactory = sf;
   }
   /**
	 * This function is the implementation for add new situation
	 * @param objSituation
	 * @return object of Situations
	*/
	public Situations addSituation(Situations objSituation) {
		try
		{
			Situations objNewSituation = new Situations();
			Session session = this.sessionFactory.openSession();
	        Transaction tx = session.beginTransaction();
	        objNewSituation = (Situations) session.merge(objSituation);
	        tx.commit();
	        session.close();
	        logger.info("Situation saved successfully, Situation Details="+objSituation);
	        return objNewSituation;
		}
		catch(Exception ex)
		{
			logger.info("Error occured in saving new situation, Error Details="+ex.getMessage());
			return objSituation;
		}
		
	}

	/**
	 * This function is the implementation for update existing situation
	 * @param objSituation
	 * @return object of Situations
	*/
	public Situations updateSituation(Situations objSituation) {
		try
		{
			Session session = this.sessionFactory.openSession();
	        Transaction tx = session.beginTransaction();
	        session.update(objSituation); // Replaced with updated rule
	        tx.commit();
	        session.close();
	        logger.info("Situation updated successfully, Situation Details="+objSituation);
	        return objSituation;
		}
		catch(Exception ex)
		{
			logger.info("Error occured in updating existing situation, Error Details="+ex.getMessage());
			return objSituation;
		}
		
	}

	/**
	 * This function is the implementation for retrieving all situations in form of list
	 * @return List of Situations
	*/
	@SuppressWarnings("unchecked")
	public List<Situations> listSituations() {
		try
		{
			Session session = this.sessionFactory.openSession();
	        @SuppressWarnings("unchecked")
	        List<Situations> situationsList = session.createQuery("from Situations").list();
	        for(Situations objSituations : situationsList){
	            logger.info("Situations List::"+objSituations);
	        }
	        session.close();
	        return situationsList;
		}
		catch(Exception ex)
		{
			logger.info("Error occured in retrieving list of situation, Error Details="+ex.getMessage());
			return null;
		}
		
	}

	/**
	 * This function is the implementation for retrieving a single situation by id
	 * @param id
	 * @return Object of Situations
	*/
	public Situations getSituationById(int id) {
		try
		{
			Session session = this.sessionFactory.openSession();      
			Situations objSituations = (Situations) session.load(Situations.class, new Integer(id));
	        logger.info("Situations loaded successfully, Situations details="+objSituations);
	        session.close();
	        return objSituations;
		}
		catch(Exception ex)
		{
			logger.info("Error occured in retrieving single situation, Error Details="+ex.getMessage());
			return null;
		}
	}

	/**
	 * This function is the implementation for deleting existing selected situation
	 * @param id
	*/
	public void removeSituation(int id) {
		try
		{
			Session session = this.sessionFactory.openSession();
			Situations objSituations = (Situations) session.load(Situations.class, new Integer(id));
		        if(null != objSituations){
		            session.delete(objSituations);
		        }
		        logger.info("Situations deleted successfully, Situations details="+objSituations);
		        session.close();
		}
		catch(Exception ex)
		{
			logger.info("Error occured in deleting single situation, Error Details="+ex.getMessage());
		}
	
	}

	/**
	 * This function is the implementation for retrieving  situation to its check existence 
	 * @param objSituation
	 * @return object of Situations
	*/
	public Situations getExistingSituation(Situations objSituation) {
		try
		{
			Session session = this.sessionFactory.openSession();  
			Situations objSendingSituation = objSituation;
			List<Situations> objExistingSituations = session.createQuery("from Situations s left join fetch s.situationConditionList sc where sc.conditionKey='" + objSituation.getSituationConditionList().get(0).getConditionKey() + "' and sc.conditionValue='" + objSituation.getSituationConditionList().get(0).getConditionValue() + "' and sc.conditionValueOperator='" + objSituation.getSituationConditionList().get(0).getConditionValueOperator() + "'").list();
			if(objExistingSituations.size() > 0)
			{
				
				for(Situations objDBSituation : objExistingSituations)
				{
					Session session2 = this.sessionFactory.openSession();
					Situations objFullDBSituation = (Situations) session2.createQuery("from Situations where SituationID = " + objDBSituation.getSituationID()).uniqueResult();
					objDBSituation = objFullDBSituation;
					if(objSituation.getSituationConditionList().size() == objDBSituation.getSituationConditionList().size())
					{
						int countEqual = 0;
						for(Condition objCommingCondition : objSituation.getSituationConditionList())
						{
							for(Condition objDBCondition : objDBSituation.getSituationConditionList())
							{
								if(objCommingCondition.getConditionKey().equals(objDBCondition.getConditionKey()) && objCommingCondition.getConditionValue().equals(objDBCondition.getConditionValue()) && objCommingCondition.getConditionValueOperator().equals(objDBCondition.getConditionValueOperator()))
								{
									countEqual = countEqual + 1;
								}
							}
						}
						
				        if(objSituation.getSituationConditionList().size() == countEqual)
				        {
				        	objSendingSituation = objDBSituation;
				        }
					}
					session2.close();
				}
			}
			session.close();

	        return objSendingSituation;
		}
		catch(Exception ex)
		{
			logger.info("Error occured in deleting single situation, Error Details="+ex.getMessage());
			return objSituation;
		}
		
		
	}

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/dataadapter/UserRewardsAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.dc.Users;
import org.uclab.mm.datamodel.sc.UserRewards;

/**
 * This is UserRewardsAdapter class which implements the Data Access Interface for CRUD operations
 * @author dcadmin
 */
public class UserRewardsAdapter implements DataAccessInterface {

    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(UserRewardsAdapter.class);
    public UserRewardsAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving UserRewards. 
     * @param objUserRewards
     * @return List of String
     */
    @Override
    public List<String> Save(Object objUserRewards) {
        
        UserRewards objInnerUserRewards = new UserRewards();
        objInnerUserRewards =  (UserRewards) objUserRewards;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_UserRewards(?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserID", objInnerUserRewards.getUserID());
            objCallableStatement.setInt("RewardPoints", objInnerUserRewards.getRewardPoints());
            objCallableStatement.setString("RewardDescription", objInnerUserRewards.getRewardDescription());
                       
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
             Date dtUserRewards = sdf.parse(objInnerUserRewards.getRewardDate());
            Timestamp tsUserRewards = new Timestamp(dtUserRewards.getYear(),dtUserRewards.getMonth(), dtUserRewards.getDate(), dtUserRewards.getHours(), dtUserRewards.getMinutes(), dtUserRewards.getSeconds(), 00);
            objCallableStatement.setTimestamp("RewardDate", tsUserRewards);
            
            objCallableStatement.setInt("RewardTypeID", objInnerUserRewards.getRewardTypeID());
            
            objCallableStatement.registerOutParameter("UserRewardID", Types.BIGINT);
            objCallableStatement.execute();
            
            int intUserRewardID = objCallableStatement.getInt("UserRewardID");
            objDbResponse.add(String.valueOf(intUserRewardID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("User Rewards saved successfully, User Rewards Details="+objUserRewards);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding User Rewards");
        	objDbResponse.add("Error in adding User Rewards");
        }   
        return objDbResponse;
    }

    /**
     * This is implementation function for updating UserRewards.
     * @param objUserRewards
     * @return List of String 
     */
    @Override
    public List<String> Update(Object objUserRewards) {
        
        UserRewards objInnerUserRewards = new UserRewards();
        objInnerUserRewards =  (UserRewards) objUserRewards;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_UserRewards(?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserRewardID", objInnerUserRewards.getUserRewardID());
            objCallableStatement.setLong("UserID", objInnerUserRewards.getUserID());
            objCallableStatement.setInt("RewardPoints", objInnerUserRewards.getRewardPoints());
            objCallableStatement.setString("RewardDescription", objInnerUserRewards.getRewardDescription());
                       
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
             Date dtUserRewards = sdf.parse(objInnerUserRewards.getRewardDate());
            Timestamp tsUserRewards = new Timestamp(dtUserRewards.getYear(),dtUserRewards.getMonth(), dtUserRewards.getDate(), dtUserRewards.getHours(), dtUserRewards.getMinutes(), dtUserRewards.getSeconds(), 00);
            objCallableStatement.setTimestamp("RewardDate", tsUserRewards);
            objCallableStatement.setInt("RewardTypeID", objInnerUserRewards.getRewardTypeID());
            
            objCallableStatement.execute();
            
            objDbResponse.add(String.valueOf(objInnerUserRewards.getUserRewardID()));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("User Rewards updated successfully, User Rewards Details="+objUserRewards);
        }
        catch (Exception e)
        {
        	logger.info("Error in updating User Rewards");
        	objDbResponse.add("Error in updating User Rewards");
        }   
        return objDbResponse;
        
    }

    /**
     * This is implementation function for retrieving UserRewards. 
     * @param objUserRewards
     * @return List of UserRewards
     */
    @Override
    public List<UserRewards> RetriveData(Object objUserRewards) {
        UserRewards objOuterUserRewards = new UserRewards();
        List<UserRewards> objListInnerUserRewards = new ArrayList<UserRewards>();
        objOuterUserRewards =  (UserRewards) objUserRewards;
        
        try
        {
            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UserRewardsByUserID(?)}");
            objCallableStatement.setLong("UserID", objOuterUserRewards.getUserID());
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                UserRewards objInnerUserRewards = new UserRewards();
                
                objInnerUserRewards.setUserRewardID(objResultSet.getLong("UserRewardID"));
                objInnerUserRewards.setUserID(objResultSet.getLong("UserID"));
                objInnerUserRewards.setRewardPoints(objResultSet.getInt("RewardPoints"));
                objInnerUserRewards.setRewardDescription(objResultSet.getString("RewardDescription"));
                Timestamp tsRewardDate = objResultSet.getTimestamp("RewardDate");
                objInnerUserRewards.setRewardDate(tsRewardDate.toString());
                objInnerUserRewards.setRewardTypeID(objResultSet.getInt("RewardTypeID"));
                objInnerUserRewards.setRewardTypeDescription(objResultSet.getString("RewardTypeDescription"));
                
                objListInnerUserRewards.add(objInnerUserRewards);
            }
            objConn.close();
            logger.info("User Rewards loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading User Rewards");
        }   
        return objListInnerUserRewards;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>supporting-layer/uiux-authoring-tool/JavaDoc/index-files/index-7.html<|end_filename|>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_76-release) on Fri Dec 23 12:27:02 KST 2016 -->
<title>G-Index</title>
<meta name="date" content="2016-12-23">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
<script type="text/javascript" src="../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
    try {
        if (location.href.indexOf('is-external=true') == -1) {
            parent.document.title="G-Index";
        }
    }
    catch(err) {
    }
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!--   -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!--   -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-6.html">Prev Letter</a></li>
<li><a href="index-8.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-files/index-7.html" target="_top">Frames</a></li>
<li><a href="index-7.html" target="_top">No&nbsp;Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
  allClassesLink = document.getElementById("allclasses_navbar_top");
  if(window==top) {
    allClassesLink.style.display = "block";
  }
  else {
    allClassesLink.style.display = "none";
  }
  //-->
</script>
</div>
<a name="skip.navbar.top">
<!--   -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="contentContainer"><a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">J</a>&nbsp;<a href="index-11.html">L</a>&nbsp;<a href="index-12.html">M</a>&nbsp;<a href="index-13.html">N</a>&nbsp;<a href="index-14.html">O</a>&nbsp;<a href="index-15.html">P</a>&nbsp;<a href="index-16.html">Q</a>&nbsp;<a href="index-17.html">R</a>&nbsp;<a href="index-18.html">S</a>&nbsp;<a href="index-19.html">T</a>&nbsp;<a href="index-20.html">U</a>&nbsp;<a href="index-21.html">V</a>&nbsp;<a href="index-22.html">W</a>&nbsp;<a name="I:G">
<!--   -->
</a>
<h2 class="title">G</h2>
<dl>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/R.attr.html#gapBetweenBars">gapBetweenBars</a></span> - Static variable in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/R.attr.html" title="class in org.uclab.mm.sl.uiux.analytics">R.attr</a></dt>
<dd>
<div class="block">Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/TrackMe.html#get-org.uclab.mm.sl.uiux.analytics.QueryParams-">get(QueryParams)</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/TrackMe.html" title="class in org.uclab.mm.sl.uiux.analytics">TrackMe</a></dt>
<dd>
<div class="block">Get string.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/dispatcher/TrackerBulkURLWrapper.html#getApiUrl--">getApiUrl()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.dispatcher.<a href="../org/uclab/mm/sl/uiux/analytics/dispatcher/TrackerBulkURLWrapper.html" title="class in org.uclab.mm.sl.uiux.analytics.dispatcher">TrackerBulkURLWrapper</a></dt>
<dd>
<div class="block">Gets api url.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html#getAPIUrl--">getAPIUrl()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html" title="class in org.uclab.mm.sl.uiux.analytics">Tracker</a></dt>
<dd>
<div class="block">Gets api url.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html#getApplicationDomain--">getApplicationDomain()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html" title="class in org.uclab.mm.sl.uiux.analytics">UIUXAnalytics</a></dt>
<dd>
<div class="block">Gets application domain.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html#getAuthToken--">getAuthToken()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html" title="class in org.uclab.mm.sl.uiux.analytics">Tracker</a></dt>
<dd>
<div class="block">Gets auth token.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/tools/ActivityHelper.html#getBreadcrumbs-android.app.Activity-">getBreadcrumbs(Activity)</a></span> - Static method in class org.uclab.mm.sl.uiux.analytics.tools.<a href="../org/uclab/mm/sl/uiux/analytics/tools/ActivityHelper.html" title="class in org.uclab.mm.sl.uiux.analytics.tools">ActivityHelper</a></dt>
<dd>
<div class="block">Gets breadcrumbs.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/dispatcher/Dispatcher.html#getConnectionTimeOut--">getConnectionTimeOut()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.dispatcher.<a href="../org/uclab/mm/sl/uiux/analytics/dispatcher/Dispatcher.html" title="class in org.uclab.mm.sl.uiux.analytics.dispatcher">Dispatcher</a></dt>
<dd>
<div class="block">Connection timeout in milliseconds</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/UIUXExceptionHandler.html#getDefaultExceptionHandler--">getDefaultExceptionHandler()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/UIUXExceptionHandler.html" title="class in org.uclab.mm.sl.uiux.analytics">UIUXExceptionHandler</a></dt>
<dd>
<div class="block">This will give you the previous exception handler that is now wrapped.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html#getDefaultTrackMe--">getDefaultTrackMe()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html" title="class in org.uclab.mm.sl.uiux.analytics">Tracker</a></dt>
<dd>
<div class="block">UIUXAnalytics will use the content of this object to fill in missing values before any transmission.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html#getDispatcher--">getDispatcher()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html" title="class in org.uclab.mm.sl.uiux.analytics">Tracker</a></dt>
<dd>
<div class="block">Gets dispatcher.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/dispatcher/Dispatcher.html#getDispatchInterval--">getDispatchInterval()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.dispatcher.<a href="../org/uclab/mm/sl/uiux/analytics/dispatcher/Dispatcher.html" title="class in org.uclab.mm.sl.uiux.analytics.dispatcher">Dispatcher</a></dt>
<dd>
<div class="block">Gets dispatch interval.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html#getDispatchInterval--">getDispatchInterval()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html" title="class in org.uclab.mm.sl.uiux.analytics">Tracker</a></dt>
<dd>
<div class="block">Gets dispatch interval.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html#getDispatchTimeout--">getDispatchTimeout()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html" title="class in org.uclab.mm.sl.uiux.analytics">Tracker</a></dt>
<dd>
<div class="block"><a href="../org/uclab/mm/sl/uiux/analytics/dispatcher/Dispatcher.html#getConnectionTimeOut--"><code>Dispatcher.getConnectionTimeOut()</code></a></div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/dispatcher/TrackerBulkURLWrapper.html#getEvents-org.uclab.mm.sl.uiux.analytics.dispatcher.TrackerBulkURLWrapper.Page-">getEvents(TrackerBulkURLWrapper.Page)</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.dispatcher.<a href="../org/uclab/mm/sl/uiux/analytics/dispatcher/TrackerBulkURLWrapper.html" title="class in org.uclab.mm.sl.uiux.analytics.dispatcher">TrackerBulkURLWrapper</a></dt>
<dd>
<div class="block">{
 "requests": ["?idsite=1&url=http://example.org&action_name=Test bulk log Pageview&rec=1",
 "?idsite=1&url=http://example.net/test.htm&action_name=Another bul k page view&rec=1"],
 "token_auth": "<KEY>"
 }</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/dispatcher/TrackerBulkURLWrapper.html#getEventUrl-org.uclab.mm.sl.uiux.analytics.dispatcher.TrackerBulkURLWrapper.Page-">getEventUrl(TrackerBulkURLWrapper.Page)</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.dispatcher.<a href="../org/uclab/mm/sl/uiux/analytics/dispatcher/TrackerBulkURLWrapper.html" title="class in org.uclab.mm.sl.uiux.analytics.dispatcher">TrackerBulkURLWrapper</a></dt>
<dd>
<div class="block">Gets event url.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html#getInstance-android.content.Context-">getInstance(Context)</a></span> - Static method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html" title="class in org.uclab.mm.sl.uiux.analytics">UIUXAnalytics</a></dt>
<dd>
<div class="block">Gets instance.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html#getLastEvent--">getLastEvent()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html" title="class in org.uclab.mm.sl.uiux.analytics">Tracker</a></dt>
<dd>
<div class="block">For testing purposes</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html#getPiwik--">getPiwik()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html" title="class in org.uclab.mm.sl.uiux.analytics">Tracker</a></dt>
<dd>
<div class="block">Gets piwik.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/UIUXApplication.html#getPiwik--">getPiwik()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/UIUXApplication.html" title="class in org.uclab.mm.sl.uiux.analytics">UIUXApplication</a></dt>
<dd>
<div class="block">Gets piwik.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/tools/DeviceHelper.html#getResolution-android.content.Context-">getResolution(Context)</a></span> - Static method in class org.uclab.mm.sl.uiux.analytics.tools.<a href="../org/uclab/mm/sl/uiux/analytics/tools/DeviceHelper.html" title="class in org.uclab.mm.sl.uiux.analytics.tools">DeviceHelper</a></dt>
<dd>
<div class="block">Tries to get the most accurate device resolution.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html#getSessionTimeout--">getSessionTimeout()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html" title="class in org.uclab.mm.sl.uiux.analytics">Tracker</a></dt>
<dd>
<div class="block">Default is 30min (30*60*1000).</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html#getSharedPreferences--">getSharedPreferences()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html" title="class in org.uclab.mm.sl.uiux.analytics">Tracker</a></dt>
<dd>
<div class="block">Gets shared preferences.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html#getSharedPreferences--">getSharedPreferences()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html" title="class in org.uclab.mm.sl.uiux.analytics">UIUXAnalytics</a></dt>
<dd>
<div class="block">Returns the shared preferences used by UIUXAnalytics that are stored under <a href="../org/uclab/mm/sl/uiux/analytics/UIUXAnalytics.html#PREFERENCE_FILE_NAME"><code>UIUXAnalytics.PREFERENCE_FILE_NAME</code></a></div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/UIUXApplication.html#getSiteId--">getSiteId()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/UIUXApplication.html" title="class in org.uclab.mm.sl.uiux.analytics">UIUXApplication</a></dt>
<dd>
<div class="block">The siteID you specified for this application in Piwik.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/UIUXApplication.html#getTracker--">getTracker()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/UIUXApplication.html" title="class in org.uclab.mm.sl.uiux.analytics">UIUXApplication</a></dt>
<dd>
<div class="block">Gives you an all purpose thread-safe persisted Tracker object.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/UIUXExceptionHandler.html#getTracker--">getTracker()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/UIUXExceptionHandler.html" title="class in org.uclab.mm.sl.uiux.analytics">UIUXExceptionHandler</a></dt>
<dd>
<div class="block">Gets tracker.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/UIUXApplication.html#getTrackerUrl--">getTrackerUrl()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/UIUXApplication.html" title="class in org.uclab.mm.sl.uiux.analytics">UIUXApplication</a></dt>
<dd>
<div class="block">The URL of your remote Piwik server.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/tools/DeviceHelper.html#getUserAgent--">getUserAgent()</a></span> - Static method in class org.uclab.mm.sl.uiux.analytics.tools.<a href="../org/uclab/mm/sl/uiux/analytics/tools/DeviceHelper.html" title="class in org.uclab.mm.sl.uiux.analytics.tools">DeviceHelper</a></dt>
<dd>
<div class="block">Returns android system user agent</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/tools/DeviceHelper.html#getUserCountry--">getUserCountry()</a></span> - Static method in class org.uclab.mm.sl.uiux.analytics.tools.<a href="../org/uclab/mm/sl/uiux/analytics/tools/DeviceHelper.html" title="class in org.uclab.mm.sl.uiux.analytics.tools">DeviceHelper</a></dt>
<dd>
<div class="block">Returns user country</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html#getUserId--">getUserId()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html" title="class in org.uclab.mm.sl.uiux.analytics">Tracker</a></dt>
<dd>
<div class="block">Gets user id.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/tools/DeviceHelper.html#getUserLanguage--">getUserLanguage()</a></span> - Static method in class org.uclab.mm.sl.uiux.analytics.tools.<a href="../org/uclab/mm/sl/uiux/analytics/tools/DeviceHelper.html" title="class in org.uclab.mm.sl.uiux.analytics.tools">DeviceHelper</a></dt>
<dd>
<div class="block">Returns user language</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html#getVisitorId--">getVisitorId()</a></span> - Method in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/Tracker.html" title="class in org.uclab.mm.sl.uiux.analytics">Tracker</a></dt>
<dd>
<div class="block">Gets visitor id.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/uclab/mm/sl/uiux/analytics/R.attr.html#goIcon">goIcon</a></span> - Static variable in class org.uclab.mm.sl.uiux.analytics.<a href="../org/uclab/mm/sl/uiux/analytics/R.attr.html" title="class in org.uclab.mm.sl.uiux.analytics">R.attr</a></dt>
<dd>
<div class="block">Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".</div>
</dd>
</dl>
<a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">J</a>&nbsp;<a href="index-11.html">L</a>&nbsp;<a href="index-12.html">M</a>&nbsp;<a href="index-13.html">N</a>&nbsp;<a href="index-14.html">O</a>&nbsp;<a href="index-15.html">P</a>&nbsp;<a href="index-16.html">Q</a>&nbsp;<a href="index-17.html">R</a>&nbsp;<a href="index-18.html">S</a>&nbsp;<a href="index-19.html">T</a>&nbsp;<a href="index-20.html">U</a>&nbsp;<a href="index-21.html">V</a>&nbsp;<a href="index-22.html">W</a>&nbsp;</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!--   -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!--   -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-6.html">Prev Letter</a></li>
<li><a href="index-8.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-files/index-7.html" target="_top">Frames</a></li>
<li><a href="index-7.html" target="_top">No&nbsp;Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
  allClassesLink = document.getElementById("allclasses_navbar_bottom");
  if(window==top) {
    allClassesLink.style.display = "block";
  }
  else {
    allClassesLink.style.display = "none";
  }
  //-->
</script>
</div>
<a name="skip.navbar.bottom">
<!--   -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/ic/UserDevice.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.ic;

import java.io.Serializable;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author Taqdir
 */
@Entity
public class UserDevice implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private Long userDeviceID;
    private Long userID;
    private Long deviceID;
    private int SubscriptionStatusID;
    //private GregorianCalendar registerDate; updated
    private String registerDate;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof UserDevice)) {
            return false;
        }
        UserDevice other = (UserDevice) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.ic.UserDevice[ id=" + id + " ]";
    }

    /**
     * @return the userDeviceID
     */
    public Long getUserDeviceID() {
        return userDeviceID;
    }

    /**
     * @param userDeviceID the userDeviceID to set
     */
    public void setUserDeviceID(Long userDeviceID) {
        this.userDeviceID = userDeviceID;
    }

    /**
     * @return the userID
     */
    public Long getUserID() {
        return userID;
    }

    /**
     * @param userID the userID to set
     */
    public void setUserID(Long userID) {
        this.userID = userID;
    }

    /**
     * @return the deviceID
     */
    public Long getDeviceID() {
        return deviceID;
    }

    /**
     * @param deviceID the deviceID to set
     */
    public void setDeviceID(Long deviceID) {
        this.deviceID = deviceID;
    }

    /**
     * @return the SubscriptionStatusID
     */
    public int getSubscriptionStatusID() {
        return SubscriptionStatusID;
    }

    /**
     * @param SubscriptionStatusID the SubscriptionStatusID to set
     */
    public void setSubscriptionStatusID(int SubscriptionStatusID) {
        this.SubscriptionStatusID = SubscriptionStatusID;
    }

    /**
     * @return the registerDate
     */
    public String getRegisterDate() {
        return registerDate;
    }

    /**
     * @param registerDate the registerDate to set
     */
    public void setRegisterDate(String registerDate) {
        this.registerDate = registerDate;
    }
    
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/AER/jh/AERSegmentation.java<|end_filename|>
/*
Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.AER.jh;

import javax.sound.sampled.AudioInputStream;

import org.uclab.mm.icl.llc.MachineLearningTools.Segmentation;
import org.uclab.mm.icl.llc.MachineLearningTools.WindowBasedSegmentation;

public class AERSegmentation extends
		Segmentation<AudioInputStream, AudioInputStream> {
	WindowBasedSegmentation wbs ;

	public AERSegmentation(int sec, int samplerate) {
		wbs = new WindowBasedSegmentation(sec, samplerate);
	}

	@Override
	public AudioInputStream segmentation(AudioInputStream input) {
		// TODO Auto-generated method stub
		AudioInputStream ais = null;
		ais = wbs.segmentation(input);
		return ais;
	}

	
}


<|start_filename|>data-curation-layer/data-acquisition-and-synchronization/rev_server2.js<|end_filename|>
/************************************************************************************************
Author: <NAME>
Affiliation: UC Lab
Project: Mining Mind
Created date: 2016-03-23
Revised date: 2016-10-27
Functionality: receiving server 2.
************************************************************************************************/

/*Required libraries***********************************************************************************************/
var express		=require('express');
var bodyParser  =require('body-parser');
var requestify  =require('requestify');
var util = require('util');
var nodeProcess = require('process');

/*Server initialization***********************************************************************************************/
var app	=express();
	app.use(bodyParser.json());
var urlencodedParser = bodyParser.urlencoded({ extended: true })
/*Server initialization***********************************************************************************************/

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

//following is the processing code for the HTTP POST restful, the route /newData is the entry point for all of data source
app.post('/saveData', urlencodedParser,  function (req,res){	
		console.log("userID:"+req.body.userID);		
		console.log("============");
		res.json({response:0});
});

app.listen('8083', function (){
	console.log('Receiving server 2 is listening at port 8083.');
});

<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/llm/SCLResponse.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.llm;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
import org.codehaus.jackson.annotate.JsonProperty;
//import org.codehaus.jackson.annotate.JsonTypeInfo;
//import org.codehaus.jackson.annotate.JsonTypeInfo.As;
//import org.codehaus.jackson.annotate.JsonTypeInfo.Id;

/**
 *
 * @author User
 */
//@JsonTypeInfo(use=Id.NAME, include=As.WRAPPER_OBJECT)
@XmlRootElement
public class SCLResponse implements Serializable {
    
    @JsonProperty("result")
    List<String> result;

    public SCLResponse() {
        this.result = new ArrayList<>();
    }

    @JsonProperty("result")
    public List<String> getResult() {
        return result;
    }

    @JsonProperty("result")
    public void setResult(List<String> result) {
        this.result = result;
    }
    
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/llm/FoodItemList.java<|end_filename|>
/*
 Copyright [2016] [Taqdir Ali]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.llm;

/**
 *
 * @author Rizvi
 */

import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.uclab.mm.datamodel.llm.dataadapter.DBConnection;


public class FoodItemList implements Serializable {
     private List<FoodItem> listFood = new ArrayList<FoodItem>();
     public List<FoodItem> getFoods() {
        Connection conn = null;
        Statement sta = null;
        try {
            conn = DBConnection.getDBConnection().getConnection();
            sta = conn.createStatement();
            ResultSet rs = sta.executeQuery("select FoodID, FoodCategory, FoodNutrientName, FoodItem from tblFoodItems");
            if (rs != null) {
                // String[] result = new String[7];
                while (rs.next()) {
                    String FoodID = rs.getString("FoodID");
                    String FoodCategory = rs.getString("FoodCategory");
                    String FoodNutrientName = rs.getString("FoodNutrientName");
                    String FoodName = rs.getString("FoodItem");
                    //String LogID = rs.getString("Log_Id");
                    FoodItem objFoodItem = new FoodItem();
                    objFoodItem.setFoodID(FoodID);
                    objFoodItem.setFoodCategory(FoodCategory);
                    objFoodItem.setFoodNutrientName(FoodNutrientName);
                    objFoodItem.setFoodName(FoodName);
                    //objViolations.setUserID(UserID);
                    listFood.add(objFoodItem);
                }
            }
        } catch (Exception e) {
            StringWriter errors = new StringWriter();
            e.printStackTrace(new PrintWriter(errors));
        }
        return listFood;
    }
    
    
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/LLCManager/MajorityVoting.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Kang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.mm.icl.llc.LLCManager;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.log4j.Logger;
import org.uclab.mm.icl.llc.config.ContextType;
import org.uclab.mm.icl.llc.config.RecognizerType;
import org.uclab.mm.icl.utils.TimeUtil;


/**
 * Low level context unifier which runs the unifying process
 * @author Nailbrainz
 */
public class MajorityVoting extends LLCUnifier{
	private final static Logger logger = Logger.getLogger(MajorityVoting.class);
	AtomicInteger index = new AtomicInteger(0);
	final int maxIndex = 100;
	
	TimeUtil util = new TimeUtil();
	
	ArrayList< ArrayList<ContextLabel> > Tables = new ArrayList< ArrayList<ContextLabel> >();
	ArrayList<byte[]> images = new ArrayList<byte[]>();
    
    
	/**
	 * Unique constructor of MajorityVoting class
	 * @param userID corresponding user ID
	 */
	public MajorityVoting(long userID, ArrayList<AtomicReference<String> > curLabels){
		super(userID, curLabels);
		
		for(int i =  0; i<RecognizerType.values().length; i++){
			Tables.add(new ArrayList<ContextLabel>());
		}
	}
	
	
    /**
     * This function clear the image data
     */
    public void clear(){
		images.clear();
    }
    
    
    /**
     * Push the llc context into unifier
     * @param obj object(llcContext) to push
     * @param rec corresponding recognizer type
     */
	public void push(Object obj, RecognizerType rec){
		Tables.get(rec.getValue()).add((ContextLabel) obj);
		
		if(rec.equals(RecognizerType.SER) || rec.equals(RecognizerType.ER)){
			System.err.println(rec.toString());
			System.err.println(((ContextLabel)obj).getLabel());
			System.err.println(((ContextLabel)obj).getTimeStamp());
			
			logger.info("****** " + rec.toString() + " At unifier : " + ((ContextLabel)obj).getLabel() + "  " + ((ContextLabel)obj).getTimeStamp() + "   ******");
		}
	}
	
	
	/**
	 * boolean function for printing console
	 * @param rec recognizer type
	 * @return 
	 */
	private boolean cond(ContextType ct){
		//return false;
		return (ct.equals(ContextType.Activity));
	}
	
	/**
	 * 
	 * @param rec Target recognizer to get minimum time of the labels
	 * @return get minimum time from the data of target recognizer
	 * @throws NullPointerException The 
	 */
	public Calendar getMinTime(RecognizerType rec) throws NullPointerException{
		ArrayList<ContextLabel> values = Tables.get(rec.getValue());
		if(values.size() == 0)return null;
		
		Calendar cal = Calendar.getInstance();
		for(int i = 0; i<values.size(); i++){
			Calendar comp = util.parseString((values.get(i).getTimeStamp()));
			if(cal.compareTo(comp) > 0){
				cal.setTime(comp.getTime());
			}
		}
		return cal;
	}
	
	



	/**
	 * This function implements unification process with majority voting
	 */
	@Override
	ContextLabel unify(String startTime, ContextType ct) {
		// TODO Auto-generated method stub

		HashMap<String, Double> map = new HashMap<String, Double>();
		String[] labels = ct.getLabels();
		String def = labels[labels.length-1];
		for(String label : labels){
			map.put(label, (double) 0);
		}
		
		//if(cond(rec))System.err.println("Labels of " + rec.toString() + "-------------------- until time " + startTime + " with " + map.size());
		
		ArrayList<ContextLabel> values = new ArrayList<ContextLabel>();
		for(RecognizerType rec: RecognizerType.values()){
			if(rec.getContext().equals(ct)){ //if the recognizer recognizes the parameter context, we collect the data for majority vote
				ArrayList<ContextLabel> prev = Tables.get(rec.getValue());
				for(int i = 0; i<prev.size(); i++){
					ContextLabel item = prev.get(i);
					values.add(item);
				}
				ArrayList<ContextLabel> left = new ArrayList<ContextLabel>();
				Tables.set(rec.getValue(), left);
			}
		}
		
		double sz = values.size();
		for(int i = 0; i<values.size(); i++){
			ContextLabel item = values.get(i);
			if(cond(ct))System.err.println(item.getLabel() + " " + item.getTimeStamp());
			try{
				double val = map.get(item.getLabel());
				map.put(item.getLabel(), val+1/(sz));
			}catch(Exception e){
				if(item == null){
					System.err.println("item null");
				}else{
					if(item.getLabel() == null){
						System.err.println("label null");
					}
				}
				logger.error("Label err is " + item.getLabel());
				for(int j = 0; j<labels.length; j++){
					logger.error("with " + labels[j]);
				}
				logger.error(e);
			}
		}
		
		String maxI = null;
		Double maxV = (double) -1;
		
		boolean found = false;
		for(int i = 0; i<values.size(); i++){
			Calendar cal = util.parseString((values.get(i).getTimeStamp()));
			ContextLabel item = values.get(i); 
			if(map.containsKey(item.getLabel())){
				double val = map.get(item.getLabel());
				if(val != 0)found = true;
				map.put(item.getLabel(), val+1/sz);
			}
		}
		String emptyL = null;
		ContextLabel ret = null;
		/*need to be removed to return null*/
		ret = ct.getBasicLabel(userID, startTime);
		
		if(cond(ct))logger.info("Output-------------");
		
		for( String key : ct.getLabels() ){
			if(cond(ct))
				logger.info("act = " + key + " val = " + map.get(key));
			if(!key.equals(def) && map.get(key) != 0 && map.get(key) > maxV){
            	maxV = map.get(key);
            	maxI = key;
            }
        }
		if(maxI != null){
			ret = ct.getContext(userID, maxI, startTime);
		}
		
		if(cond(ct))logger.info("Final result = " + ret.getUserID() + " "+ ret.getLabel() + "  " + ret.getTimeStamp());
		if(cond(ct)){
			try {
				PrintWriter pw = new PrintWriter(new FileOutputStream(new File("D:/KinectFace/activity.txt"),true));
				pw.append(ret.getLabel() + "\t" + ret.getTimeStamp() + "\r\n");
				pw.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		curLabels.set(ct.getValue(), new AtomicReference<String>(ret.getLabel()));
		return ret;
	}



}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/dc/dataadapter/PhysiologicalFactorsAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.dc.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.dc.PhysiologicalFactors;

/**
 * This is PhysiologicalFactorsAdapter class which implements the Data Access Interface for CRUD operations
 * @author Taqdir
 */
public class PhysiologicalFactorsAdapter implements DataAccessInterface {

    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(PhysiologicalFactorsAdapter.class);
    public PhysiologicalFactorsAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving PhysiologicalFactors. 
     * @param objPhysiologicalFactors
     * @return List of String
     */
    
   @Override
    public List<String> Save(Object objPhysiologicalFactors) {
        PhysiologicalFactors objInnerPhysiologicalFactors = new PhysiologicalFactors();
        objInnerPhysiologicalFactors =  (PhysiologicalFactors) objPhysiologicalFactors;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_PhysiologicalFactors(?, ?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserID", objInnerPhysiologicalFactors.getUserId());
            objCallableStatement.setFloat("Weight", objInnerPhysiologicalFactors.getWeight());
            objCallableStatement.setFloat("height", objInnerPhysiologicalFactors.getHeight());
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
            Date dtDate = sdf.parse(objInnerPhysiologicalFactors.getDate());
            Timestamp tsDate = new Timestamp(dtDate.getYear(),dtDate.getMonth(), dtDate.getDate(), 00, 00, 00, 00);
            objCallableStatement.setTimestamp("Date", tsDate);
            objCallableStatement.setFloat("IdealWeight", objInnerPhysiologicalFactors.getIdealWeight());
            objCallableStatement.setFloat("TargetWeight", objInnerPhysiologicalFactors.getTargetWeight());
            objCallableStatement.registerOutParameter("PhysiologicalFactorID", Types.BIGINT);
            objCallableStatement.execute();
            
            int intPhysiologicalFactorID = objCallableStatement.getInt("PhysiologicalFactorID");
            objDbResponse.add(String.valueOf(intPhysiologicalFactorID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Physiological factor saved successfully, User Details="+objPhysiologicalFactors);
        }
        catch (Exception e)
        {
             e.printStackTrace();
             objDbResponse.add("rror in adding Physiological factors");
             logger.info("Error in adding Physiological factors");
        } 
        return objDbResponse;
    }

   /**
    * This is implementation function for updating PhysiologicalFactors. 
    * @param objPhysiologicalFactors
    * @return List of String
    */
    @Override
    public List<String> Update(Object objPhysiologicalFactors) {
        PhysiologicalFactors objInnerPhysiologicalFactors = new PhysiologicalFactors();
        objInnerPhysiologicalFactors =  (PhysiologicalFactors) objPhysiologicalFactors;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_PhysiologicalFactors(?, ?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("PhysiologicalFactorID", objInnerPhysiologicalFactors.getPhysiologicalFactorId());
            objCallableStatement.setLong("UserID", objInnerPhysiologicalFactors.getUserId());
            objCallableStatement.setFloat("Weight", objInnerPhysiologicalFactors.getWeight());
            objCallableStatement.setFloat("height", objInnerPhysiologicalFactors.getHeight());

             SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
             Date dtDate =sdf.parse( objInnerPhysiologicalFactors.getDate());
            Timestamp tsDate = new Timestamp(dtDate.getYear(),dtDate.getMonth(), dtDate.getDate(), 00, 00, 00, 00);
            objCallableStatement.setTimestamp("Date", tsDate);
            objCallableStatement.setFloat("IdealWeight", objInnerPhysiologicalFactors.getIdealWeight());
            objCallableStatement.setFloat("TargetWeight", objInnerPhysiologicalFactors.getTargetWeight());
            
            objCallableStatement.execute();
            
            objDbResponse.add(String.valueOf(objInnerPhysiologicalFactors.getPhysiologicalFactorId()));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Physiological factor updated successfully, User Details="+objPhysiologicalFactors);
        }
        catch (Exception e)
        {
        	logger.info("Error in updated Physiological factors");
        	objDbResponse.add("Error in updated Physiological factors");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for retrieving PhysiologicalFactors.
     * @param objPhysiologicalFactors
     * @return List of PhysiologicalFactors 
     */
    @Override
    public List<PhysiologicalFactors> RetriveData(Object objPhysiologicalFactors) {
        PhysiologicalFactors objOuterPhysiologicalFactors = new PhysiologicalFactors();
        List<PhysiologicalFactors> objListInnerPhysiologicalFactors = new ArrayList<PhysiologicalFactors>();
        objOuterPhysiologicalFactors =  (PhysiologicalFactors) objPhysiologicalFactors;
        
        try
        {
            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_PhysiologicalFactorsByUserID(?)}");
            objCallableStatement.setLong("UserID", objOuterPhysiologicalFactors.getUserId());
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                PhysiologicalFactors objInnerPhysiologicalFactors = new PhysiologicalFactors();
                objInnerPhysiologicalFactors.setPhysiologicalFactorId(objResultSet.getLong("PhysiologicalFactorID"));
                objInnerPhysiologicalFactors.setUserId(objResultSet.getLong("UserID"));
                objInnerPhysiologicalFactors.setWeight(objResultSet.getFloat("Weight"));
                objInnerPhysiologicalFactors.setHeight(objResultSet.getFloat("height"));
                
                Timestamp tsDate = objResultSet.getTimestamp("Date");
                objInnerPhysiologicalFactors.setDate(tsDate.toString());
                
                objInnerPhysiologicalFactors.setIdealWeight(objResultSet.getFloat("IdealWeight"));
                objInnerPhysiologicalFactors.setTargetWeight(objResultSet.getFloat("TargetWeight"));
                
                objListInnerPhysiologicalFactors.add(objInnerPhysiologicalFactors);
            }
            objConn.close();
            logger.info("Physiological is loaded successfully");
            
        }
        catch (Exception e)
        {
             logger.info("Error in Loading Physiological factors");
        }   
        return objListInnerPhysiologicalFactors;
    }

    /**
     * This is implementation function for retrieving PhysiologicalFactors.
     * Not implemented
     */
    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>knowledge-curation-layer/i-kat/src/main/java/org/uclab/mm/kcl/edkat/dao/RuleDAO.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.kcl.edkat.dao;

import java.util.List;

import org.uclab.mm.kcl.edkat.datamodel.Rule;


/**
* This is Data Access Object class for the rule this DAO provides interfaces to
* create, update, retrieve of rules, conditions, conclusions, and situation
 * @author  <NAME>
 * @version 1.0
 * @since   2015-08-16
 * */

public interface RuleDAO {

	/**
	 * This interface function is for add new rule with conditions, conclusions, and situations
	 * @param objRule
	 * @return Object of Rule
	*/
	public Rule addRule(Rule objRule);
	
	/**
	 *  This interface function is for update the existing rule with conditions, conclusions, and situations
	 * @param objRule
	 * @return Object of Rule
	*/
	public Rule updateRule(Rule objRule);
	
	/**
	 * This function get all rules with conditions, conclusions, and situations
	 * @return List of Rules
	*/
	public List<Rule> listRule();
	
	/**
	 * This function get a specific rule by rule id (primary key)
	 * @param id
	 * @return Object of Rule
	*/
	public Rule getRuleById(int id);
	
	/**
	 * This function delete a specific rule by rule id (primary key)
	 * @param id
	*/
    public void removeRule(int id);
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/hlca/RemoveContext.java<|end_filename|>
package mm.hlca;
import mm.icl.hlc.ContextOntologyManager.ContextRemovalManager;

public class RemoveContext {

	public static void main(String[] args) {
		
		try{
			ContextRemovalManager jdh = new ContextRemovalManager();
			jdh.ClearModel();
			System.out.println("All Instance Removed.");

		}
		catch(Exception e)
		{
			
		}
		
		
	}
}



<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/dataaccess/SituationEventDAOImp.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */
package org.uclab.mm.dcl.llm.dataaccess;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import org.apache.log4j.BasicConfigurator;
import org.uclab.mm.dcl.llm.objectmodel.SituationConditions;
import org.uclab.mm.dcl.llm.objectmodel.SituationEvent;
import org.uclab.mm.dcl.llm.objectmodel.SituationEvents;
import org.apache.log4j.Logger;

/**
 *The class is used to provide the functionality for managing the monitoring 
 * conditions and the related constraints shared by experts.
 * @author Rizvi
 */
public class SituationEventDAOImp implements SituationEventDAO{

  static org.apache.log4j.Logger log = Logger.getLogger(SituationEventDAOImp.class.getName());
  /**
   * This method is used to differentiate between monitor-able event and
   * constraints. After dividing the situation event into two parts it stores
   * persistently the monitoring and constraints information in configuration
   * data for the guidance of monitoring process..
   *
   * @param objSituationEvents
   */
  @Override
  public void persistentSituation(SituationEvents objSituationEvents)
  {
    BasicConfigurator.configure();
    String mapperid = null;
    String Activity = null;
    String ActivityOperator = null;
    String ActivityValue = null;
    String ActivityDataType = null;
    String MeasuringMetric = null;
    String MeasuringOperator = null;
    String MeasuringTargetValue = null;
    String MeasuringDataType = null;
    String sitID = null;
    Connection conn = null;
    Statement sta = null;
    try{

      conn = DBConnection.getDBConnection().getConnection();

      sta = conn.createStatement();
      Iterator<SituationEvent> itSituationEvent = objSituationEvents.getListSEvents().iterator();
      int counter = 0;
      while (itSituationEvent.hasNext()){
        SituationEvent objSituationEvent = itSituationEvent.next();
        counter = 0;
        Iterator<SituationConditions> itSituationConditions = objSituationEvent.getListSConditions().iterator();
        while (itSituationConditions.hasNext()){
          SituationConditions objSituationCondition = itSituationConditions.next();

          if (objSituationCondition.getConditionKey().equals("Current Activity"))
          {
            mapperid = objSituationEvent.getSituationID();
            Activity = objSituationCondition.getConditionKey();
            ActivityOperator = objSituationCondition.getConditionValueOperator();
            ActivityValue = objSituationCondition.getConditionValue();
            ActivityDataType = objSituationCondition.getConditionType();
            counter++;
          } else if (objSituationCondition.getConditionKey().equals("Activity Duration") || objSituationCondition.getConditionKey().equals("Consumed Fat"))
          {
            MeasuringMetric = objSituationCondition.getConditionKey();
            MeasuringOperator = objSituationCondition.getConditionValueOperator();
            MeasuringTargetValue = objSituationCondition.getConditionValue();
            MeasuringDataType = objSituationCondition.getConditionType();
            counter++;
          } else 
          {            
            /**
             * Insert the information of constraints of Situation in table
             * SItuation Constraints where it is persisted as key value pair.
             * Stored procedure "usp_SituationConstraintsInsertion" is called.
             */
              java.sql.CallableStatement cstmt = conn.prepareCall("{call usp_SituationConstraintsInsertion('" + objSituationEvent.getSituationID() + "','" + objSituationCondition.getConditionKey() + "','" + objSituationCondition.getConditionValueOperator() + "','" + objSituationCondition.getConditionValue() + "','" + objSituationCondition.getConditionType() + "','" + objSituationEvent.getSituationID() + "')}");
              cstmt.execute();
          }
          if (counter == 2)
          {
            /**
             * Insert the information of Monitoring Situation in table
             * monitoring Events where it is persisted as key value pair. Stored
             * procedure "usp_MonitoringSituationInsertion" is called.
             */
            java.sql.CallableStatement cstmt = conn.prepareCall("{call usp_MonitoringSituationInsertion('" + mapperid + "','" + Activity + "','" + ActivityOperator + "','" + ActivityValue + "','" + ActivityDataType + "','" + MeasuringMetric + "','" + MeasuringOperator + "','" + timeCal(MeasuringTargetValue) + "','" + MeasuringDataType + "')}");
            cstmt.execute();
            counter = 0;
          }
         }//. inner while loop
            
        log.info("********** New Situation Event Received From KCL **********");
        log.info("\tSituation Event Details:");
        log.info("\t Current Activity: " + ActivityValue);
        log.info("\t Activity Duration: " + MeasuringTargetValue);
        log.info("********** New Situation Saved Successfully **********");
        
      } //. main while loop
    }catch(SQLException sqlException){
      sqlException.printStackTrace();
    } 
    catch (Exception e){
      StringWriter errors = new StringWriter();
      e.printStackTrace(new PrintWriter(errors));
      sitID = errors.toString();
      sitID = sitID.replaceAll("\\s", "");
    }    
  }

  /**
   * 
   * @return 
   */
  @Override
  public SituationEvents retriveSituationEvents(){
    return null;
  }

  /**
   * This method is used to Convert time into minutes for physical activity monitoring also manage amount 
   * having no unit for handling fats in nutrition.
   * @param measuringParameter
   * @return 
   */
  public String timeCal(String measuringParameter){
    String[] tokens = measuringParameter.split(":");
    int hrmin = 0;
    int minmin = 0;
    int grams = 0;
    String total1 = "";
    int total = 0;
    for (String t : tokens)
    {
      if ((t.charAt(t.length() - 1)) == ('h'))
      {
        String hr = removeLastChar(t);
        hrmin = Integer.parseInt(hr);
        hrmin = 60 * hrmin;
      }
      if ((t.charAt(t.length() - 1)) == ('m'))
      {
        String hr = removeLastChar(t);
        minmin = Integer.parseInt(hr);
      }
      if ((t.charAt(t.length() - 1)) != 'h' && (t.charAt(t.length() - 1)) != 'm')
      {
        String gm = t;
        grams = Integer.parseInt(gm);
      }
      System.out.println(t);
    }
    total = hrmin + minmin + grams;
    total1 = total + "";
    return total1;
  }
  
  private String removeLastChar(String str){
    return str.substring(0, str.length() - 1);
  }
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/ic/UserRecognizedEmotion.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.ic;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
//import net.sourceforge.jtds.jdbc.DateTime;
/**
 *
 * @author Taqdir
 */
public class UserRecognizedEmotion implements Serializable {
    
     private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private Long userRecognizedEmotionId;
    private Long userId;
    private String emotionLabel;
    private String startTime;
    private String endTime;
    private Long duration;
    
    private String requestType;

    /**
     * @return the userRecognizedEmotionId
     */
    public Long getUserRecognizedEmotionId() {
        return userRecognizedEmotionId;
    }

    /**
     * @param userRecognizedEmotionId the userRecognizedEmotionId to set
     */
    public void setUserRecognizedEmotionId(Long userRecognizedEmotionId) {
        this.userRecognizedEmotionId = userRecognizedEmotionId;
    }

    /**
     * @return the userId
     */
    public Long getUserId() {
        return userId;
    }

    /**
     * @param userId the userId to set
     */
    public void setUserId(Long userId) {
        this.userId = userId;
    }

     /**
     * @return the startTime
     */
    public String getStartTime() {
        return startTime;
    }

    /**
     * @param startTime the startTime to set
     */
    public void setStartTime(String startTime) {
        this.startTime = startTime;
    }

    /**
     * @return the endTime
     */
    public String getEndTime() {
        return endTime;
    }

    /**
     * @param endTime the endTime to set
     */
    public void setEndTime(String endTime) {
        this.endTime = endTime;
    }

    /**
     * @return the duration
     */
    public Long getDuration() {
        return duration;
    }

    /**
     * @param duration the duration to set
     */
    public void setDuration(Long duration) {
        this.duration = duration;
    }

    /**
     * @return the emotionLabel
     */
    public String getEmotionLabel() {
        return emotionLabel;
    }

    /**
     * @param emotionLabel the emotionLabel to set
     */
    public void setEmotionLabel(String emotionLabel) {
        this.emotionLabel = emotionLabel;
    }

    /**
     * @return the requestType
     */
    public String getRequestType() {
        return requestType;
    }

    /**
     * @param requestType the requestType to set
     */
    public void setRequestType(String requestType) {
        this.requestType = requestType;
    }
    
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/hlca/ContextCSVReader.java<|end_filename|>
package mm.hlca;
import mm.icl.hlc.HLC.TimeUtil;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Calendar;


public class ContextCSVReader 
{
//	static final String userId = "9735";
//	static final String llcLabel = "Sitting";     
//	TimeUtil util = new TimeUtil();			 
//	Calendar cal1 = util.parseString("2016 04 18 10:11:25");

	
	//Delimiters used in the CSV file
    private static final String COMMA_DELIMITER = ",";
    
   public static void main(String args[])
//    public void bilalTest()
    
    {
		TimeUtil util = new TimeUtil();		
		BufferedReader br = null;
        try
        {
            //Reading the csv file
            br = new BufferedReader(new FileReader("E:/ICL_LOG/TDB/Activity.csv"));//ContextCSV
            
            //Create List for holding Employee objects
            List<ContextCSV> contextList = new ArrayList<ContextCSV>();
            
            String line = "";
            //Read to skip the header
            br.readLine();
            //Reading from the second line
            while ((line = br.readLine()) != null) 
            {
                String[] ContextCSVDetails = line.split(COMMA_DELIMITER);
                
                if(ContextCSVDetails.length > 0 )
                {
                	ContextCSV context_llc = new ContextCSV(ContextCSVDetails[0], ContextCSVDetails[1],ContextCSVDetails[2]);
                	contextList.add(context_llc);
                }
            }
            
            //Lets print the Employee List
            for(ContextCSV c : contextList)
            { 
            	
                System.out.println(c.getllcLabel()+" "+ c.getuserId()+" "+ util.parseString(c.getcal()));
//                System.out.println(util.parseString(c.getcal())); //                System.out.println(c.getcal()); //                System.out.println(c.getuserId()); //                System.out.println(c.getllcLabel());
            }
        }
        catch(Exception ee)
        {
            ee.printStackTrace();
        }
        finally
        {
            try
            {
                br.close();
            }
            catch(IOException ie)
            {
                System.out.println("Error occured while closing the BufferedReader");
                ie.printStackTrace();
            }
        }
    }
}

<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/MachineLearningTools/EventBasedSegmentation.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Bang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.MachineLearningTools;

import java.io.IOException;
import java.util.Vector;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;

import org.uclab.mm.icl.llc.AER.jh.ConvertAudioData;

import mm.icl.llc.MachineLearningTools.Segmentation;


/**
 * This class segments the audio data, based on the event (when there is no voice, this class filters that void period)
 * @author <NAME>
 *
 */
public class EventBasedSegmentation extends
		Segmentation<AudioInputStream, AudioInputStream[]> {

	AudioFormat audioFM;
	ConvertAudioData cad = new ConvertAudioData();
	int nonSpeechTime = 0;
	int speechTime = 0;
	boolean segFlag = false;
	Vector<Integer> speechIndex = new Vector<Integer>();
	int segmentNumber = 0;
	double segmentSec = 0.4;
	Vector<Vector<byte[]>> segment;
	int remainedNumber =0;

	@Override
	public AudioInputStream[] segmentation(AudioInputStream origin_input) {
		// TODO Auto-generated method stub

		audioFM = origin_input.getFormat();
		segment = segmentData(origin_input);
		AudioInputStream[] ais = new AudioInputStream[segment.size()];
		if (segment.size() > 0) {
			for (int i = 0; i < segment.size(); i++) {
				byte[] buffer = cad.convertByteBuffer(segment.get(i));
				ais[i] = cad.convertAudioInputStream(buffer, audioFM);
			}
			segFlag = true;
		}
		segFlag =false;

		return ais;
	}

	public void setSpeechIndex(Vector<Integer> speechIndex) {
		this.speechIndex = speechIndex;
	}

	public void setSegmentOption(double sec) {
		segmentSec = sec;
	}
	
	
/**
 * Segmenting the data
 * @param input input audio stream data to segment
 * @return segmented audio data
 */
	public Vector<Vector<byte[]>> segmentData(AudioInputStream input) {
		Vector<byte[]> buffer = new Vector<byte[]>();
		Vector<Vector<byte[]>> returnValue = new Vector<Vector<byte[]>>();
		byte[] temp = new byte[1024];

		try {
			for (int i = 0; i < speechIndex.size(); i++) {
				if (speechIndex.get(i) == 0) {
					input.read(temp);
					nonSpeechTime++;
				} else {
					input.read(temp);
					buffer.add(temp);
					speechTime++;
					nonSpeechTime = 0;
				}
				if (speechTime > 34 && nonSpeechTime == 43) {
					Vector<byte[]> temp_vector = new Vector<byte[]>();
					for (int l = 0; l < buffer.size(); l++) {
						temp_vector.add(buffer.get(l));
					}
					buffer.removeAllElements();
					returnValue.add(temp_vector);
					speechTime = 0;
					nonSpeechTime = 0;
					remainedNumber = i;
										
				} else if (nonSpeechTime > 43) {
					buffer.removeAllElements();
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return returnValue;
	}

	

	/**
	 * return remained data
	 * 
	 * @param input
	 * @return AudioInputStream
	 */

	public AudioInputStream returnRemainedData(AudioInputStream input) {
		if (segFlag) {
			byte[] remained = new byte[(speechIndex.size()-remainedNumber)*1024];
			AudioInputStream ais = null;
			try {
				input.read(remained);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ais = cad.convertAudioInputStream(remained, audioFM);
			segFlag = false;
			return ais;
		}
		return input;
	}

}


<|start_filename|>service-curation-layer/recommendation-builder/src/test/java/org/uclab/scl/framework/recbuilder/PatternMatcherTest.java<|end_filename|>
package org.uclab.scl.framework.recbuilder;

import static org.junit.Assert.assertEquals;

import java.util.List;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.uclab.scl.datamodel.FiredRule;

public class PatternMatcherTest {
  private static Map<String, List<Map<String, Object>>> rules;
  private static PatternMatcher patternMatcher;

  @BeforeClass
  public static void setup() {
    ObjectMapper mapper = new ObjectMapper();
    try {
      rules = mapper.readValue(TestHelper.loadStringRules(), new TypeReference<Map<String, List<Map<String, Object>>>>() {});
      patternMatcher = new PatternMatcher();

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

  }

  @AfterClass
  public static void afterClass() {
    // . TODO afterClass stuff
  }

  @Test
  public void rulesLoaded() {
    int expected = 19;
    int actual = (rules.get("rules")).size();
    assertEquals(expected, actual);
  }
  public void fireRuleTest1() {
    String jsonFact = "{\"Current Activity\":\"LyingDown\",\"Activity Duration\":\"1h\",\"Activity Environment\":\"BedRest\",\"Activity Status\":\"Non-continuous\"}";
    Map<String, Object> fact = TestHelper.buildFact(jsonFact);
    int expected = 2;
    try{
      List<FiredRule> firedRules = patternMatcher.fireRule(fact, rules.get("rules"));
      assertEquals(expected, firedRules.size());
    }catch(UnsupportedTypeException e){e.printStackTrace();}
  }

  @Test
  public void fireRuleTest2() {
    String jsonFact = "{\"Current Activity\":\"LyingDown\",\"Activity Duration\":\"1h\"}";
    Map<String, Object> fact = TestHelper.buildFact(jsonFact);
    
    String expected = "19";
    
    try{
      List<FiredRule> firedRules = patternMatcher.fireRule(fact, rules.get("rules"));
      assertEquals(expected, firedRules.get(0).getRuleId());
    }catch(UnsupportedTypeException e){} 
  }
  
  @Test
  public void fireRuleTest3() {
    String jsonFact = "{\"Current Activity\":\"LyingDown\",\"Activity Duration\":\"1h\"}";
    Map<String, Object> fact = TestHelper.buildFact(jsonFact);
    
    int expected = 0;
    fact.put("Current Activity", "Nothing");
    try{
      List<FiredRule> firedRules = patternMatcher.fireRule(fact, rules.get("rules"));
      assertEquals(expected, firedRules.size());
    }catch(UnsupportedTypeException e){}
  }

}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/AR/var/KinectARClassification.java<|end_filename|>
/*
Copyright [2016] [Thien]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.AR.var;

import weka.classifiers.trees.J48;
import weka.core.Attribute;
import weka.core.FastVector;
import weka.core.Instance;
import weka.core.Instances;

public class KinectARClassification {
	String[] labelString = new String[] {"Stretching","LyingDown","Sweeping","Sitting","Eating","Standing"};
	
	private J48 smo;
	Instances dummyDataset;
	
	/**
	 * 
	 */
	public KinectARClassification(String modelFile) {
		smo = null;
		loadModel(modelFile);
	}
	
	/**
	 * @param filename
	 * @return
	 */
	public boolean loadModel(String filename) {
		try {
			smo = (J48) weka.core.SerializationHelper.read(filename);
			dummyDataset = createDummyDataset(281);
			return true;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return false;
	}
	
	/**
	 * @param features
	 * @return
	 */
	protected Instance createInstance(double[] features) {
		int numAttributes = features.length;
		Instance instance = new Instance(numAttributes + 1);
		for (int i = 0; i < numAttributes; i++)
			instance.setValue(i, features[i]);
		return instance;
	}
	
	/**
	 * @param numAttributes
	 * @return
	 */
	protected Instances createDummyDataset(int numAttributes) {
		// Create attribute set
		FastVector fvWekaAttributes = new FastVector(numAttributes);
		
		// Create numeric attributes
		for (int i = 0; i < numAttributes - 1; i++) {
			Attribute attribute = new Attribute("f" + i);
			fvWekaAttributes.addElement(attribute);
		}
		
		// Create class attribute
		FastVector fvClassVal = new FastVector(6);
		fvClassVal.addElement("c1");
		fvClassVal.addElement("c2");
		fvClassVal.addElement("c3");
		fvClassVal.addElement("c4");
		fvClassVal.addElement("c5");
		fvClassVal.addElement("c6");
		Attribute classAttribute = new Attribute("class", fvClassVal);
		fvWekaAttributes.addElement(classAttribute);
		
		// Create an empty training set
		Instances dataset = new Instances("Rel", fvWekaAttributes, 1);
		// Set class index
		dataset.setClassIndex(numAttributes - 1);
		
		return dataset;
	}

	public String Classify(double[] data) {
		try {
			if (smo == null)
				return "MODELISNULL";
			
			// Convert features to an instance
			Instance instance = createInstance(data);
			instance.setDataset(dummyDataset);
			
			// Classify
			int labelIndex = Double.valueOf(smo.classifyInstance(instance)).intValue();
			
			return labelString[labelIndex];
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/AbstractDataBridge.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */


package org.uclab.mm.datamodel;

import java.util.List;
import org.uclab.mm.datamodel.dc.PhysiologicalFactors;
import org.uclab.mm.datamodel.dc.UserDisabilities;
import org.uclab.mm.datamodel.dc.UserFacilities;
import org.uclab.mm.datamodel.dc.UserRiskFactors;
import org.uclab.mm.datamodel.dc.UserSchedule;
import org.uclab.mm.datamodel.dc.Users;
import org.uclab.mm.datamodel.ic.Device;
import org.uclab.mm.datamodel.ic.FoodLog;
import org.uclab.mm.datamodel.ic.UserAccelerometerData;
import org.uclab.mm.datamodel.ic.UserDetectedLocation;
import org.uclab.mm.datamodel.ic.UserDevice;
import org.uclab.mm.datamodel.ic.UserGPSData;
import org.uclab.mm.datamodel.ic.UserPreferredLocation;
import org.uclab.mm.datamodel.ic.UserRecognizedActivity;
import org.uclab.mm.datamodel.ic.UserRecognizedActivityAccumulate;
import org.uclab.mm.datamodel.ic.UserRecognizedActivityLog;
import org.uclab.mm.datamodel.ic.UserRecognizedEmotion;
import org.uclab.mm.datamodel.ic.UserRecognizedHLC;
import org.uclab.mm.datamodel.llm.LifelogMonitorActivity;
import org.uclab.mm.datamodel.sc.Achievements;
import org.uclab.mm.datamodel.sc.ActivityPlan;
import org.uclab.mm.datamodel.sc.ActivityRecommendation;
import org.uclab.mm.datamodel.sc.ActivityRecommendationLog;
import org.uclab.mm.datamodel.sc.Facts;
import org.uclab.mm.datamodel.sc.ProfileData;
import org.uclab.mm.datamodel.sc.Recommendation;
import org.uclab.mm.datamodel.sc.RecommendationException;
import org.uclab.mm.datamodel.sc.RecommendationExplanation;
import org.uclab.mm.datamodel.sc.Situation;
import org.uclab.mm.datamodel.sc.UserGoal;
import org.uclab.mm.datamodel.sc.UserPreferredActivities;
import org.uclab.mm.datamodel.sc.UserRewards;
import org.uclab.mm.datamodel.sl.ActiveSession;
import org.uclab.mm.datamodel.sl.ActivityFeedback;
import org.uclab.mm.datamodel.sl.ExpertReview;
import org.uclab.mm.datamodel.sl.FactsFeedback;
import org.uclab.mm.datamodel.sl.RecommendationFeedback;
import org.uclab.mm.datamodel.sl.UserAccelerometerDataVisulization;
import org.uclab.mm.datamodel.sl.UserGPSDataVisulization;


/**
 * This abstract class is bridge between for the CRUD operations between Database and all corresponding implementation classes.
 * @author <NAME>
 */
public abstract class AbstractDataBridge {
    
    protected DataAccessInterface objDAInterface;
    public AbstractDataBridge(DataAccessInterface objDAInterface)
    {
        this.objDAInterface = objDAInterface;
    }
    
    /**
     * This constructor of the abstract class
     */
    public AbstractDataBridge()
    {
        
    }
    
    /**
     * This is abstract function for saving User.
     * @param objUser
     * @return List of String 
     */
    public abstract List<String> SaveUser(Users objUser);
    /**
     * This is abstract function for updating User.
     * @param objUser
     * @return List of string
     *  
     */
    public abstract List<String> UpdateUser(Users objUser);
    /**
     * This is abstract function for retrieving User. 
     * @param objUser
     * @return List of Users
     */
    public abstract List<Users> RetriveUser(Users objUser);
    /**
     * This is abstract function for deleting User.
     * @param objUser
     * @return List of String 
     */
    public abstract List<String> DeleteUser(Users objUser);
    
    /**
     * This is abstract function for saving Device. 
     * @param objDevice
     * @return List of String
     */
    public abstract List<String> SaveDevice(Device objDevice);
    /**
     * This is abstract function for updating Device. 
     * @param objDevice
     * @return List of String
     */
    public abstract List<String> UpdateDevice(Device objDevice);
    /**
     * This is abstract function for retrieving Device. 
     * @param objDevice
     * @return List of String
     */
    public abstract List<Device> RetriveDevice(Device objDevice);
    
    /**
     * This is abstract function for saving UserDevice. 
     * @param objUserDevice
     * @return List of String
     */
    public abstract List<String> SaveUserDevice(UserDevice objUserDevice);
    /**
     * This is abstract function for updating UserDevice. 
     * @param objUserDevice
     * @return List of String
     */
    public abstract List<String> UpdateUserDevice(UserDevice objUserDevice);
    /**
     * This is abstract function for retrieving UserDevice. 
     * @param objUserDevice
     * @return List of UserDevice
     */
    
    public abstract List<UserDevice> RetriveUserDevice(UserDevice objUserDevice);
    
    /**
     * This is abstract function for saving UserRiskFactors. 
     * @param objUserRiskFactors
     * @return List of String
     */
    public abstract List<String> SaveUserRiskFactors(UserRiskFactors objUserRiskFactors);
    /**
     * This is abstract function for updating UserRiskFactors. 
     * @param objUserRiskFactors
     * @return List of String
     */
    public abstract List<String> UpdateUserRiskFactors(UserRiskFactors objUserRiskFactors);
    /**
     * This is abstract function for retrieving UserRiskFactors.
     * @param objUserRiskFactors
     * @return List of UserRiskFactors 
     */
    public abstract List<UserRiskFactors> RetriveUserRiskFactors(UserRiskFactors objUserRiskFactors);
    
    /**
     * This is abstract function for saving PhysiologicalFactors. 
     * @param objPhysiologicalFactors
     * @return List of String
     */
    public abstract List<String> SavePhysiologicalFactors(PhysiologicalFactors objPhysiologicalFactors);
    /**
     * This is abstract function for updating PhysiologicalFactors. 
     * @param objPhysiologicalFactors
     * @return List of String
     */
    public abstract List<String> UpdatePhysiologicalFactors(PhysiologicalFactors objPhysiologicalFactors);
    /**
     * This is abstract function for retrieving PhysiologicalFactors.
     * @param objPhysiologicalFactors
     * @return List of PhysiologicalFactors 
     */
    public abstract List<PhysiologicalFactors> RetrivePhysiologicalFactors(PhysiologicalFactors objPhysiologicalFactors);
    
    /**
     * This is abstract function for saving UserFacilities. 
     * @param objUserFacilities
     * @return List of String
     */
    public abstract List<String> SaveUserFacilities(UserFacilities objUserFacilities);
    /**
     * This is abstract function for updating UserFacilities. 
     * @param objUserFacilities
     * @return List of String
     */
    public abstract List<String> UpdateUserFacilities(UserFacilities objUserFacilities);
    /**
     * This is abstract function for retrieving UserFacilities.
     * @param objUserFacilities
     * @return List of UserFacilities
     */
    public abstract List<UserFacilities> RetriveUserFacilities(UserFacilities objUserFacilities);
    
    /**
     * This is abstract function for saving UserPreferredActivities.
     * @param objUserPreferredActivities
     * @return List of String
     */
    public abstract List<String> SaveUserPreferredActivities(UserPreferredActivities objUserPreferredActivities);
    /**
     * This is abstract function for updating User. 
     * @param objUserPreferredActivities
     * @return List of String
     */
    public abstract List<String> UpdateUserPreferredActivities(UserPreferredActivities objUserPreferredActivities);
    /**
     * This is abstract function for retrieving UserPreferredActivities. 
     * @param objUserPreferredActivities
     * @return List of UserPreferredActivities
     */
    public abstract List<UserPreferredActivities> RetriveUserPreferredActivities(UserPreferredActivities objUserPreferredActivities);
    
    /**
     * This is abstract function for saving UserGPSData. 
     * @param objUserGPSData
     * @return List of String
     */
    public abstract List<String> SaveUserGPSData(UserGPSData objUserGPSData);
    /**
     * This is abstract function for retrieving UserGPSData. 
     * @param objUserGPSData
     * @return List of UserGPSData
     */
    public abstract List<UserGPSData> RetriveUserGPSData(UserGPSData objUserGPSData);
    
    /**
     * This is abstract function for saving UserAccelerometerData. 
     * @param objUserAccelerometerData
     * @return List of String
     */
    public abstract List<String> SaveUserAccelerometerData(UserAccelerometerData objUserAccelerometerData);
    /**
     * This is abstract function for retrieving UserAccelerometerData. 
     * @param objUserAccelerometerData
     * @return List of UserAccelerometerData
     */
    public abstract List<UserAccelerometerData> RetriveUserAccelerometerData(UserAccelerometerData objUserAccelerometerData);
    
    /**
     * This is abstract function for saving UserRecognizedActivity.
     * @param objUserRecognizedActivity
     * @return List of String 
     */
    public abstract List<String> SaveUserRecognizedActivity(UserRecognizedActivity objUserRecognizedActivity);
    /**
     * This is abstract function for retrieving UserRecognizedActivity.
     * @param objUserRecognizedActivity
     * @return List of UserRecognizedActivity 
     */
    public abstract List<UserRecognizedActivity> RetriveUserRecognizedActivity(UserRecognizedActivity objUserRecognizedActivity);
    
    /**
     * This is abstract function for saving UserDetectedLocation. 
     * @param objUserDetectedLocation
     * @return List of String
     */
    public abstract List<String> SaveUserDetectedLocation(UserDetectedLocation objUserDetectedLocation);
    /**
     * This is abstract function for retrieving UserDetectedLocation.
     * @param objUserDetectedLocation
     * @return List of UserDetectedLocation 
     */
    public abstract List<UserDetectedLocation> RetriveUserDetectedLocation(UserDetectedLocation objUserDetectedLocation);
    
    /**
     * This is abstract function for saving UserGoal. 
     * @param objUserGoal
     * @return List of String
     */
    public abstract List<String> SaveUserGoal(UserGoal objUserGoal);
    /**
     * This is abstract function for retrieving UserGoal.
     * @param objUserGoal
     * @return List of UserGoal 
     */
    public abstract List<UserGoal> RetriveUserGoal(UserGoal objUserGoal);
    
    /**
     * This is abstract function for saving ActivityPlan. 
     * @param objActivityPlan
     * @return List of String
     */
    public abstract List<String> SaveActivityPlan(ActivityPlan objActivityPlan);
    /**
     * This is abstract function for retrieving ActivityPlan. 
     * @param objActivityPlan
     * @return List of ActivityPlan
     * 
     */
   public abstract List<ActivityPlan> RetriveActivityPlan(ActivityPlan objActivityPlan);
    
    /**
     * This is abstract function for saving ActivityRecommendation. 
     * @param objActivityRecommendation
     * @return List of String
     */
    public abstract List<String> SaveActivityRecommendation(ActivityRecommendation objActivityRecommendation);
    /**
     * This is abstract function for retrieving ActivityRecommendation. 
     * @param objActivityRecommendation
     * @return List of ActivityRecommendation
     */
    public abstract List<ActivityRecommendation> RetriveActivityRecommendation(ActivityRecommendation objActivityRecommendation);
    
    /**
     * This is abstract function for saving ActivityRecommendationLog. 
     * @param objActivityRecommendationLog
     * @return List of String
     */
    public abstract List<String> SaveActivityRecommendationLog(ActivityRecommendationLog objActivityRecommendationLog);
    /**
     * This is abstract function for retrieving ActivityRecommendationLog. 
     * @param objActivityRecommendationLog
     * @return List of ActivityRecommendationLog
     */
    public abstract List<ActivityRecommendationLog> RetriveActivityRecommendationLog(ActivityRecommendationLog objActivityRecommendationLog);
    
    
    /**
     * This is abstract function for validating Users. 
     * @param objUsers
     * @return List of String
     */
    public abstract List<String> IsUserValid(Users objUsers);
    
    /**
     * This is abstract function for saving ActiveSession. 
     * @param objActiveSession
     * @return List of String
     */
    public abstract List<String> SaveActiveSession(ActiveSession objActiveSession);
    
    /**
     * This is abstract function setter of DataAccessInterface. 
     * @param DAInterface
     *
     */
    public abstract void setDataAdapter(DataAccessInterface DAInterface);
    
    /**
     * This is abstract function for retrieving ProfileData. 
     * @param objProfileData
     * @return List of ProfileData
     */
     public abstract List<ProfileData> RetriveProfileData(ProfileData objProfileData);
     
     /**
      * This is abstract function for saving UserGPSDataVisulization. 
      * @param objUserGPSData
     * @return List of UserGPSDataVisulization
      */
     public abstract List<UserGPSDataVisulization> RetriveUserGPSDataVisulization(UserGPSDataVisulization objUserGPSData);
     /**
      * This is abstract function for retrieving UserAccelerometerDataVisulization. 
      * @param objUserAccelerometerData
     * @return List of UserAccelerometerDataVisulization
      */
     public abstract List<UserAccelerometerDataVisulization> RetriveUserAccelerometerDataVisulization(UserAccelerometerDataVisulization objUserAccelerometerData);
     
     /**
      * This is abstract function for retrieving UserRewards. 
      * @param objUserRewards
     * @return List of UserRewards
      */
      public abstract List<UserRewards> RetriveUserRewards(UserRewards objUserRewards);
      /**
       * This is abstract function for saving UserRewards. 
       * @param objUserRewards
     * @return List of String
       */
      public abstract List<String> SaveUserRewards(UserRewards objUserRewards);
      /**
       * This is abstract function for updating UserRewards.
       * @param objUserRewards
     * @return List of String 
       */
      public abstract List<String> UpdateUserRewards(UserRewards objUserRewards);
      
      /**
       * This is abstract function for saving UserRecognizedActivityLog. 
       * @param objUserRecognizedActivityLog
     * @return List of String
       */
    public abstract List<String> SaveUserRecognizedActivityLog(UserRecognizedActivityLog objUserRecognizedActivityLog);
    /**
     * This is abstract function for retrieving UserRecognizedActivityLog. 
     * @param objUserRecognizedActivityLog
     * @return List of UserRecognizedActivityLog
     */
    public abstract List<UserRecognizedActivityLog> RetriveUserRecognizedActivityLog(UserRecognizedActivityLog objUserRecognizedActivityLog);
    
    /**
     * This is abstract function for saving Situation. 
     * @param objSituation
     * @return List of String
     */
    public abstract List<String> SaveSituation(Situation objSituation);
    /**
     * This is abstract function for retrieving Situation.
     * @param objSituation
     * @return List of Situation 
     */
    public abstract List<Situation> RetriveSituation(Situation objSituation);
    /**
     * This is abstract function for updating Situation. 
     * @param objSituation
     * @return List of String
     */
    public abstract List<String> UpdateSituation(Situation objSituation);
    
    /**
     * This is abstract function for saving Recommendation. 
     * @param objRecommendation
     * @return List of String
     */
    public abstract List<String> SaveRecommendation(Recommendation objRecommendation);
    /**
     * This is abstract function for retrieving Recommendation. 
     * @param objRecommendation
     * @return List of Recommendation
     */
    public abstract List<Recommendation> RetriveRecommendation(Recommendation objRecommendation);
    /**
     * This is abstract function for updating Recommendation. 
     * @param objRecommendation
     * @return List of String
     */
    public abstract List<String> UpdateRecommendation(Recommendation objRecommendation);
    
    /**
     * This is abstract function for saving RecommendationException.
     * @param objRecommendationException
     * @return List of String 
     */
    public abstract List<String> SaveRecommendationException(RecommendationException objRecommendationException);
    /**
     * This is abstract function for retrieving RecommendationException.
     * @param objRecommendationException
     * @return List of RecommendationException 
     */
    public abstract List<RecommendationException> RetriveRecommendationException(RecommendationException objRecommendationException);
    /**
     * This is abstract function for updating RecommendationException.
     * @param objRecommendationException
     * @return List of RecommendationException 
     */
    public abstract List<String> UpdateRecommendationException(RecommendationException objRecommendationException);
    
    /**
     * This is abstract function for saving RecommendationExplanation. 
     * @param objRecommendationExplanation
     * @return List of String
     */
    public abstract List<String> SaveRecommendationExplanation(RecommendationExplanation objRecommendationExplanation);
    /**
     * This is abstract function for retrieving RecommendationExplanation. 
     * @param objRecommendationExplanation
     * @return List of RecommendationExplanation
     */
    public abstract List<RecommendationExplanation> RetriveRecommendationExplanation(RecommendationExplanation objRecommendationExplanation);
    /**
     * This is abstract function for updating RecommendationExplanation. 
     * @param objRecommendationExplanation
     * @return List of String
     */
    public abstract List<String> UpdateRecommendationExplanation(RecommendationExplanation objRecommendationExplanation);
      
    /**
     * This is abstract function for saving RecommendationFeedback. 
     * @param objRecommendationFeedback
     * @return List of String
     */
    public abstract List<String> SaveRecommendationFeedback(RecommendationFeedback objRecommendationFeedback);
    /**
     * This is abstract function for retrieving RecommendationFeedback. 
     * @param objRecommendationFeedback
     * @return List of RecommendationFeedback
     */
    public abstract List<RecommendationFeedback> RetriveRecommendationFeedback(RecommendationFeedback objRecommendationFeedback);
    /**
     * This is abstract function for updating RecommendationFeedback. 
     * @param objRecommendationFeedback
     * @return List of String
     */
    public abstract List<String> UpdateRecommendationFeedback(RecommendationFeedback objRecommendationFeedback);
     
    /**
     * This is abstract function for saving ActivityFeedback. 
     * @param objActivityFeedback
     * @return List of String
     */
    public abstract List<String> SaveActivityFeedback(ActivityFeedback objActivityFeedback);
    /**
     * This is abstract function for retrieving ActivityFeedback. 
     * @param objActivityFeedback
     * @return List of ActivityFeedback
     */
    public abstract List<ActivityFeedback> RetriveActivityFeedback(ActivityFeedback objActivityFeedback);
    /**
     * This is abstract function for updating ActivityFeedback. 
     * @param objActivityFeedback
     * @return List of String
     */
    public abstract List<String> UpdateActivityFeedback(ActivityFeedback objActivityFeedback);
     
    /**
     * This is abstract function for saving ExpertReview. 
     * @param objExpertReview
     * @return List of String
     */
    public abstract List<String> SaveExpertReview(ExpertReview objExpertReview);
    /**
     * This is abstract function for retrieving ExpertReview. 
     * @param objExpertReview
     * @return List of ExpertReview
     */
    public abstract List<ExpertReview> RetriveExpertReview(ExpertReview objExpertReview);
    /**
     * This is abstract function for updating ExpertReview. 
     * @param objExpertReview
     * @return List of String
     */
    public abstract List<String> UpdateExpertReview(ExpertReview objExpertReview);
     
    /**
     * This is abstract function for saving UserDisabilities. 
     * @param objUserDisabilities
     * @return List of String
     */
    public abstract List<String> SaveUserDisabilities(UserDisabilities objUserDisabilities);
    /**
     * This is abstract function for updating UserDisabilities. 
     * @param objUserDisabilities
     * @return List of String
     */
    public abstract List<String> UpdateUserDisabilities(UserDisabilities objUserDisabilities);
    /**
     * This is abstract function for retrieving UserDisabilities. 
     * @param objUserDisabilities
     * @return List of UserDisabilities
     */
    public abstract List<UserDisabilities> RetriveUserDisabilities(UserDisabilities objUserDisabilities);
    
    /**
     * This is abstract function for saving UserSchedule. 
     * @param objUserSchedule
     * @return List of String
     */
    public abstract List<String> SaveUserSchedule(UserSchedule objUserSchedule);
    /**
     * This is abstract function for updating UserSchedule. 
     * @param objUserSchedule
     * @return List of String
     */
    public abstract List<String> UpdateUserSchedule(UserSchedule objUserSchedule);
    /**
     * This is abstract function for retrieving UserSchedule.
     * @param objUserSchedule
     * @return List of UserSchedule 
     */
    public abstract List<UserSchedule> RetriveUserSchedule(UserSchedule objUserSchedule);

    /**
     * This is abstract function for saving LifelogMonitorActivity. 
     * @param objLifelogMonitorActivity
     * @return List of LifelogMonitorActivity
     */   
    public abstract List<LifelogMonitorActivity> RetriveLifelogMonitorActivity(LifelogMonitorActivity objLifelogMonitorActivity);
     
    /**
     * This is abstract function for saving Facts. 
     * @param objFacts
     * @return List of String
     */
    public abstract List<String> SaveFacts(Facts objFacts);
    /**
     * This is abstract function for retrieving Facts. 
     * @param objFacts
     * @return List of Facts
     */
    public abstract List<Facts> RetriveFacts(Facts objFacts);
    /**
     * This is abstract function for updating Facts. 
     * @param objFacts
     * @return List of String
     */
    public abstract List<String> UpdateFacts(Facts objFacts);
    
    /**
     * This is abstract function for saving FactsFeedback. 
     * @param objFactsFeedback
     * @return List of String
     */
    public abstract List<String> SaveFactsFeedback(FactsFeedback objFactsFeedback);
    /**
     * This is abstract function for retrieving FactsFeedback.
     * @param objFactsFeedback
     * @return List of FactsFeedback 
     */
    public abstract List<FactsFeedback> RetriveFactsFeedback(FactsFeedback objFactsFeedback);
    /**
     * This is abstract function for updating FactsFeedback. 
     * @param objFactsFeedback
     * @return List of String
     */
    public abstract List<String> UpdateFactsFeedback(FactsFeedback objFactsFeedback);
    
    /**
     * This is abstract function for saving UserRecognizedActivityAccumulate. 
     * @param objUserRecognizedActivityAccumulate
     * @return List of String
     */
    public abstract List<String> SaveUserRecognizedActivityAccumulate(UserRecognizedActivityAccumulate objUserRecognizedActivityAccumulate);
    /**
     * This is abstract function for retrieving UserRecognizedActivityAccumulate. 
     * @param objUserRecognizedActivityAccumulate
     * @return List of RetriveUserRecognizedActivityAccumulate
     */
    public abstract List<UserRecognizedActivityAccumulate> RetriveUserRecognizedActivityAccumulate(UserRecognizedActivityAccumulate objUserRecognizedActivityAccumulate);
    /**
     * This is abstract function for updating UserRecognizedActivityAccumulate.
     * @param objUserRecognizedActivityAccumulate
     * @return List of String 
     */
    public abstract List<String> UpdateUserRecognizedActivityAccumulate(UserRecognizedActivityAccumulate objUserRecognizedActivityAccumulate);
    
    /**
     * This is abstract function for saving Achievements. 
     * @param objAchievements
     * @return List of String
     */
    public abstract List<String> SaveAchievements(Achievements objAchievements);
    /**
     * This is abstract function for retrieving Achievements. 
     * @param objAchievements
     * @return List of Achievements
     */
    public abstract List<Achievements> RetriveAchievements(Achievements objAchievements);
    /**
     * This is abstract function for updating Achievements. 
     * @param objAchievements
     * @return List of String
     */
    public abstract List<String> UpdateAchievements(Achievements objAchievements);
    
    /**
     * This is abstract function for saving UserRecognizedEmotion. 
     * @param objUserRecognizedEmotion
     * @return List of String
     */
    public abstract List<String> SaveUserRecognizedEmotion(UserRecognizedEmotion objUserRecognizedEmotion);
    /**
     * This is abstract function for retrieving UserRecognizedEmotion.
     * @param objUserRecognizedEmotion
     * @return List of RetriveUserRecognizedEmotion 
     */
    public abstract List<UserRecognizedEmotion> RetriveUserRecognizedEmotion(UserRecognizedEmotion objUserRecognizedEmotion);
    
    /**
     * This is abstract function for saving UserRecognizedHLC. 
     * @param objUserRecognizedHLC
     * @return List of String
     */
    public abstract List<String> SaveUserRecognizedHLC(UserRecognizedHLC objUserRecognizedHLC);
    /**
     * This is abstract function for retrieving UserRecognizedHLC.
     * @param objUserRecognizedHLC
     * @return List of UserRecognizedHLC 
     */
    public abstract List<UserRecognizedHLC> RetriveUserRecognizedHLC(UserRecognizedHLC objUserRecognizedHLC);
    
    /**
     * This is abstract function for saving UserPreferredLocation. 
     * @param objUserPreferredLocation
     * @return List of String
     */
    public abstract List<String> SaveUserPreferredLocation(UserPreferredLocation objUserPreferredLocation);
    /**
     * This is abstract function for retrieving UserPreferredLocation. 
     * @param objUserPreferredLocation
     * @return List of UserPreferredLocation
     */
    public abstract List<UserPreferredLocation> RetriveUserPreferredLocation(UserPreferredLocation objUserPreferredLocation);
    /**
     * This is abstract function for updating UserPreferredLocation. 
     * @param objUserPreferredLocation
     * @return List of String
     */
    public abstract List<String> UpdateUserPreferredLocation(UserPreferredLocation objUserPreferredLocation);
    
    /**
     * This is abstract function for saving FoodLog. 
     * @param objFoodLog
     * @return List of String
     */
    public abstract List<String> SaveFoodLog(FoodLog objFoodLog);
    /**
     * This is abstract function for retrieving FoodLog.
     * @param objFoodLog
     * @return List of FoodLog 
     */
    public abstract List<FoodLog> RetriveFoodLog(FoodLog objFoodLog);
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/AR/iar/AR_DecisionFusion.java<|end_filename|>
/**
Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */

package org.uclab.mm.icl.llc.AR.iar;

/**
 * This class is to fuse the decision among smartphone, smartwatch and integrated AR model
 * 
 * @author <NAME>
 *
 */

public class AR_DecisionFusion {
	int[][] table;  // Contains the list of activity

	/**
	 * This function returns the activity label
	 * @param input activity integer label
	 * @return string activity label
	 */
	public static String getActivity(int input) {
		if (input == 0) {
			return "Eating";
		} else if (input == 1) {
			return "Running";
		} else if (input == 2) {
			return "Sitting";
		} else if (input == 3) {
			return "Standing";
		} else if (input == 4) {
			return "Walking";
		} else if (input == 5) {
			return "Stretching";
		} else if (input == 6) {
			return "Sweeping";
		} else if (input == 7) {
			return "LyingDown";
		} else
			return "UnidentifiedActivity";
	}

/**
 * Converts the string activity into integer
 * @param arg String activity to convert
 * @return converted integer label
 */
	public static int getActivityNum(String arg) {
		arg = arg.toLowerCase();
		if (arg.equals("eating")) {
			return 0;
		} else if (arg.equals("running")) {
			return 1;
		} else if (arg.equals("sitting")) {
			return 2;
		} else if (arg.equals("standing")) {
			return 3;
		} else if (arg.equals("walking")) {
			return 4;
		} else if (arg.equals("stretching")) {
			return 5;
		} else if (arg.equals("sweeping")) {
			return 6;
		} else if (arg.equals("lyingdown")) {
			return 7;
		}
		return 10;
	}

	/**
	 * This function finds the activity with the most weight
	 * @param arg activity to find the biggest weight
	 * @return activity with the biggest weight
	 */
	public int findBiggestActivity(int arg[]) {

		int big_point = -1;
		double big_num = -1;

		for (int j = 0; j < arg.length; j++) {
			if (arg[j] > big_num) {
				big_num = arg[j];
				big_point = j;
			}
		}

		return big_point;
	}

	/**
	 * This function returns the final concluded activity based on the weight
	 * @param in
	 * @param sm
	 * @param wm
	 * @return
	 */
	public String getFinalActivity(String in, String sm, String wm) {

		int[][] result_table = new int[4][8];
		
		for(int j = 0 ; j < 4 ; j++) {
			for(int k = 0 ; k < 8; k++) {
				result_table[j][k] = 0;
			}
		}

		result_table[0][getActivityNum(in)] = table[0][getActivityNum(in)]; // integrated
		result_table[1][getActivityNum(sm)] = table[1][getActivityNum(sm)]; // sm
		result_table[2][getActivityNum(wm)] = table[2][getActivityNum(wm)]; // wm

		for (int l = 0; l < 8; l++) {
			result_table[3][l] = result_table[2][l] + result_table[1][l] + result_table[0][l];
		}

		int act = findBiggestActivity(result_table[3]);
		return getActivity(act);
	}

	/**
	 * This function allocates weight to each AR model's activity
	 */
	public AR_DecisionFusion() {

	      table = new int[3][8];

	      // integrated    
	      table[0][0] = 2;
	      table[0][1] = 1;
	      table[0][2] = 1;
	      table[0][3] = 1;
	      table[0][4] = 2;
	      table[0][5] = 2;
	      table[0][6] = 3;
	      table[0][7] = 2;
	      
	      // smartphone
	      table[1][0] = 0;
	      table[1][1] = 1;
	      table[1][2] = 2;
	      table[1][3] = 2;
	      table[1][4] = 2;
	      table[1][5] = 1;
	      table[1][6] = 0;
	      table[1][7] = 2;
	     
	      // wearable
	      table[2][0] = 0;
	      table[2][1] = 3;
	      table[2][2] = 2;
	      table[2][3] = 2;
	      table[2][4] = 1;
	      table[2][5] = 1;
	      table[2][6] = 1;
	      table[2][7] = 2;
	}
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/test/HLCAMapperTest.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.test;

import static org.junit.Assert.*;

import org.junit.Test;

public class HLCAMapperTest {

    private java.util.List emptyList;
	@Test
	public void test() {
		fail("Check HLCAMapper");
		}
	  public void testForException() { 
          try { 
               Object o = emptyList.get(0); 
               fail("Should raise an IndexOutOfBoundsException");
          } 
          catch (IndexOutOfBoundsException success) {
          } 
}
}



<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/objectmodel/SituationLog.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */
package org.uclab.mm.dcl.llm.objectmodel;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

/**
 *
 * @author Rizvi
 */
public class SituationLog{

  private String UserID;
  private String SituationCategoryID;
  private String SituationDescription;
  private String SituationDate;

  /**
   * @return the UserID
   */
  public String getUserID(){
    return UserID;
  }

  /**
   * @param UserID the UserID to set
   */
  public void setUserID(String UserID){
    this.UserID = UserID;
  }

  /**
   * @return the SituationCategoryID
   */
  public String getSituationCategoryID(){
    return SituationCategoryID;
  }

  /**
   * @param SituationCategoryID the SituationCategoryID to set
   */
  public void setSituationCategoryID(String SituationCategoryID){
    this.SituationCategoryID = SituationCategoryID;
  }

  /**
   * @return the SituationDescription
   */
  public String getSituationDescription(){
    return SituationDescription;
  }

  /**
   * @param SituationDescription the SituationDescription to set
   */
  public void setSituationDescription(String SituationDescription){
    this.SituationDescription = SituationDescription;
  }

  /**
   * @return the SituationDate
   */
  public String getSituationDate(){
    return SituationDate;
  }

  /**
   * @param SituationDate the SituationDate to set
   */
  public void setSituationDate(String SituationDate){
    this.SituationDate = SituationDate;
  }

  public void setSituationDate(){
    this.SituationDate = getCurrentDate();
  }

  private String getCurrentDate(){
    String recGenerationDate = null;
    Date today = new Date();
    DateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
    //Converting date to XMLGregorianCalendar in Java
    XMLGregorianCalendar startTime = toXMLGregorianCalendar(today);

    GregorianCalendar gc = startTime.toGregorianCalendar();
    recGenerationDate = (String) sdf.format(gc.getTime());
    return recGenerationDate;
  }

  private XMLGregorianCalendar toXMLGregorianCalendar(Date date){

    GregorianCalendar gCalendar = new GregorianCalendar();

    gCalendar.setTime(date);

    XMLGregorianCalendar xmlCalendar = null;

    try{
      xmlCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(gCalendar);
    } catch (DatatypeConfigurationException ex){
      ex.printStackTrace();
    }

    return xmlCalendar;

  }

}


<|start_filename|>knowledge-curation-layer/i-kat/src/test/java/org/uclab/mm/kcl/edkat/service/testcases/RuleServiceImplTest.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.kcl.edkat.service.testcases;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.uclab.mm.kcl.edkat.dao.ConditionDAO;
import org.uclab.mm.kcl.edkat.dao.RuleDAO;
import org.uclab.mm.kcl.edkat.dao.SituationDAO;
import org.uclab.mm.kcl.edkat.datamodel.Conclusion;
import org.uclab.mm.kcl.edkat.datamodel.Condition;
import org.uclab.mm.kcl.edkat.datamodel.Rule;
import org.uclab.mm.kcl.edkat.datamodel.Situations;

/**
 * This is a class for testing the insertion, fetching, and update of Rule with combination of Condition, Conclusion, and Situation 
 * @author <NAME>
 *
 */
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class RuleServiceImplTest {

	@Autowired
	private ConditionDAO conditionDAO;
	
	@Autowired
	private SituationDAO situationDAO;
	
	@Autowired
	private RuleDAO ruleDAO;
	/**
	 * This is function for testing the insertion, fetching, and update of Rule with combination of Condition, Conclusion, and Situation  
	 */
	@Test
	@Transactional
	@Rollback(true)
	public void test() {
		
		Condition objOuterCondition = new Condition();
		Condition objOuterCondition2 = new Condition();
		Condition objOuterCondition3 = new Condition();
		List<Condition> objListOuterCondition = new ArrayList<Condition>();
		
		/* Setting the Condition Object*/
		objOuterCondition.setConditionKey("unit test 6");
		objOuterCondition.setConditionValue("unit Test Value 6");
		objOuterCondition.setConditionType("int");
		objOuterCondition.setConditionValueOperator("=");
		
		/* Setting the Condition Object*/
		objOuterCondition2.setConditionKey("unit test 7");
		objOuterCondition2.setConditionValue("unit Test Value 7");
		objOuterCondition2.setConditionType("int");
		objOuterCondition2.setConditionValueOperator("=");
		
		/* Setting the Condition Object*/
		objOuterCondition3.setConditionKey("unit test 8");
		objOuterCondition3.setConditionValue("unit Test Value 8");
		objOuterCondition3.setConditionType("int");
		objOuterCondition3.setConditionValueOperator("=");
		
		//objListOuterCondition.add(objOuterCondition);
		//objListOuterCondition.add(objOuterCondition2);
		objListOuterCondition.add(objOuterCondition3);
		
		/* Setting the Situation Object*/
		
		Situations objSituations = new Situations();
		Situations objAddedSituations = new Situations();
		Situations objInnerSituations = new Situations();
		
		objSituations.setSituationDescription("First unit test situation");
		objSituations.setSituationConditionList(objListOuterCondition);
		/* Testing of Situation Insertion*/
		objAddedSituations = situationDAO.addSituation(objSituations);
		
		/* Testing of Situation fetching*/
		objInnerSituations = situationDAO.getSituationById(objAddedSituations.getSituationID());
		
		assertEquals(objAddedSituations.getSituationDescription(), objInnerSituations.getSituationDescription());
		
		
		/* Setting the Rule Object*/
		Rule objRule = new Rule();
		Rule objInnerRule = new Rule();
		
		objRule.setRuleTitle("UnitTitle");
		objRule.setInstitution("UnitInstitution");
		objRule.setRuleDescription("UnitRuleDescription");
		objRule.setRuleConclusion("UnitConclusion");
		Date today = Calendar.getInstance().getTime();
		objRule.setRuleCreatedDate(today);
		objRule.setRuleCreatedBy(4);
		objRule.setSpecialistName("UnitSpecialist");
		objRule.setRuleTypeID(1);
		objRule.setSituationID(objAddedSituations.getSituationID());
		
		/* Setting Rule Condition List */
		objListOuterCondition.clear();
		objListOuterCondition.add(objOuterCondition);
		objListOuterCondition.add(objOuterCondition2);
		objListOuterCondition.add(objOuterCondition3);
				
		objRule.setConditionList(objListOuterCondition);
		
		/* Setting Rule Conclusion List */
		Conclusion objConclusion = new Conclusion();
		List<Conclusion> objListConclusion = new ArrayList<Conclusion>();
		
		objConclusion.setConclusionKey("unit testing conclution");
		objConclusion.setConclusionOperator("=");
		objConclusion.setConclusionValue("unit testing value");
		
		objListConclusion.add(objConclusion);
		
		objRule.setConclusionList(objListConclusion);
		
		/* Testing of Rule Insertion*/
		objInnerRule = ruleDAO.addRule(objRule);
		
		/* Testing of Rule fetching*/
		objInnerRule = ruleDAO.getRuleById(objInnerRule.getRuleID());
		
		assertEquals(objRule.getRuleTitle(), objInnerRule.getRuleTitle());
		
		
	}

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/dataadapter/ProfileDataAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.sc.ProfileData;

/**
 * This is ProfileDataAdapter class which implements the Data Access Interface for CRUD operations
 * @author Taqdir
 */
public class ProfileDataAdapter implements DataAccessInterface {

     private Connection objConn;
     private static final Logger logger = LoggerFactory.getLogger(ProfileDataAdapter.class);
    public ProfileDataAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving ProfileData. 
     * Not Implemented
     */
    @Override
    public <T> List<String> Save(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for update ProfileData. 
     * Not Implemented
     */
    @Override
    public <T> List<String> Update(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet."); 
    }

    /**
     * This is implementation function for retrieving ProfileData. 
     * @param objProfileData
     * @return List of ProfileData
     */
     @Override
    public List<ProfileData> RetriveData(Object objProfileData) {
        ProfileData objOuterProfileData = new ProfileData();
        List<ProfileData> objListInnerProfileData = new ArrayList<ProfileData>();
        objOuterProfileData =  (ProfileData) objProfileData;
        
        try
        {
            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_ProfileDataByUserID(?)}");
            objCallableStatement.setLong("UserID", objOuterProfileData.getUserID());
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                ProfileData objInnerProfileData = new ProfileData();
                objInnerProfileData.setGenderId(objResultSet.getInt("GenderID"));
                objInnerProfileData.setGenderDescription(objResultSet.getString("GenderDescription"));
                
                 Timestamp tsDateOfBirth = objResultSet.getTimestamp("DateOfBirth"); //updated
                objInnerProfileData.setDateOfBirth(tsDateOfBirth.toString());
                
                objInnerProfileData.setActivityLevelId(objResultSet.getInt("ActivityLevelID"));
                objInnerProfileData.setActivityLevelDescription(objResultSet.getString("ActivityLevelDescription"));
                objInnerProfileData.setHeight(objResultSet.getFloat("Height"));
                objInnerProfileData.setWeight(objResultSet.getFloat("Weight"));
                objListInnerProfileData.add(objInnerProfileData);
            }
            objConn.close();
            logger.info("Profile Data loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading Profile Data");
        }   
        return objListInnerProfileData;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
    
    
}


<|start_filename|>knowledge-curation-layer/i-kat/src/test/java/org/uclab/mm/kcl/edkat/controller/testcases/RulesControllerTest.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.kcl.edkat.controller.testcases;

import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;

import org.aspectj.lang.annotation.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.*;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.View;
import static org.hamcrest.Matchers.hasEntry;
import org.uclab.mm.kcl.edkat.controller.RulesController;
import org.uclab.mm.kcl.edkat.datamodel.Rule;
import org.uclab.mm.kcl.edkat.service.RuleService;

public class RulesControllerTest {

	@InjectMocks
    RulesController controller;
	
	@Mock
	RuleService mockRuleService;
	
	@Mock
    View mockView;
    MockMvc mockMvc;

	
	@Before(value = "")
	public void setUp() throws Exception {
		MockitoAnnotations.initMocks(this);
	}
	
	@Test
	public void test() {
		//List<Rule> expectedRules = new ArrayList<Rule>();
       // Mockito.when(mockRuleService.listRules()).thenReturn(expectedRules);
        //Model modelMap;
        //String viewName = controller.listRules(modelMap);
        //assertEquals("RulesDashboard", viewName);
        //assertThat(modelMap, hasEntry("RulesDashboard", (Object) expectedRules));
	}

}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/HLCReasoner/HLCReasoner.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.HLCReasoner;
import java.util.Iterator;

import mm.icl.hlc.OntologyTools.Context;
import mm.icl.hlc.OntologyTools.InferredContextOntology;
import mm.icl.hlc.OntologyTools.NutritionContext;
import mm.icl.hlc.OntologyTools.ClinicalContext;
import mm.icl.hlc.OntologyTools.PhysicalActivityContext;
import mm.icl.utils.FileUtil;
import org.apache.log4j.Logger;
import com.hp.hpl.jena.reasoner.ValidityReport;
import com.hp.hpl.jena.reasoner.ValidityReport.Report;
/**
 * HLC Reasoner: Component of HLCA which performs a consistency check on the
 * unclassified PhysicalActivity and Nutrition Context instance and classifies it in order to
 * identify the context type to which the instance belongs.
 * 
 * @author <NAME> and <NAME>
 * @version 2.5
 * @since 2015-10-28
 */
public class HLCReasoner extends AbstractReasoner{
	
	private static Logger logger = Logger.getLogger(HLCReasoner.class);
	/**
	 * Context Classifier which is a subcomponent of the HLC Reasoner.
	 */
	private ContextClassifier cc;
	/**
	 * Context Classifier which is a subcomponent of the HLC Reasoner.
	 */
	private ContextVerifier cv;
	/**
	 * Constructor of a new HLC Reasoner.
	 * 
	 * @param ont
	 *            Inferred version of the Context Ontology which represents the
	 *            Mining Minds Context Model.
	 */
	
	private Context context;
	public HLCReasoner(InferredContextOntology ont) {
		this.cc = new ContextClassifier(ont);
		this.cv = new ContextVerifier(ont);
	}
	/**
	 * Method to infer PhysicalActivity Context, i.e., to perform a consistency check
	 * on the unclassified PhysicalActivity Context instance and in case it is valid,
	 * to identify the context type to which the instance belongs.
	 * 
	 * @param unclassified
	 *            Unclassified PhysicalActivity Context instance.
	 * @return Classified PhysicalActivity Context instance.
	 */
	public PhysicalActivityContext inferHlc(PhysicalActivityContext unclassified) {
		if (cv.isValid(unclassified))
			return cc.classify(unclassified);
		return unclassified;
	}
	/**
	 * Method to infer Nutrition Context, i.e., to perform a consistency check
	 * on the unclassified Nutrition Context instance and in case it is valid,
	 * to identify the context type to which the instance belongs.
	 * 
	 * @param unclassified
	 *            Unclassified Nutrition Context instance.
	 * @return Classified Nutrition Context instance.
	 */
	public NutritionContext inferHlc(NutritionContext unclassified) {
		if (cv.isValid(unclassified))
			return cc.classify(unclassified);
		return unclassified;
	}
	/**
	 * Method to infer Nutrition Context, i.e., to perform a consistency check
	 * on the unclassified Nutrition Context instance and in case it is valid,
	 * to identify the context type to which the instance belongs.
	 * 
	 * @param unclassified
	 *            Unclassified Nutrition Context instance.
	 * @return Classified Nutrition Context instance.
	 */
	public ClinicalContext inferHlc(ClinicalContext unclassified) {
		if (cv.isValid(unclassified))
			return cc.classify(unclassified);
		return unclassified;
	}
	/**
	 * Test method that applies the same business logic than inferHlc but prints
	 * messages through the standard output stream.
	 * 
	 * @param unclassified
	 *            Unclassified PhysicalActivity Context instance.
	 * @return Classified PhysicalActivity Context instance.
	 */
	public PhysicalActivityContext inferTest(PhysicalActivityContext unclassified) {
		ValidityReport report = cv.validate(unclassified);
		if (report.isValid()) {
			PhysicalActivityContext classified = cc.classify(unclassified);
			logger.info("[HLC Reasoner: PhysicalActivityContext: ] " + classified.getCtxInstanceLocalName() + " classified as " 
					+ classified.getCtxTypeLocalName());
			return classified;
		} else {
			logger.info("[HLC Reasoner: PhysicalActivityContext: ] The HLC is not valid."); 
			Iterator<Report> i = report.getReports();
			while (i.hasNext())
				logger.info(i.next());
			return unclassified;
		}
	}
	/**
	 * Test method that applies the same business logic than inferHlc but prints
	 * messages through the standard output stream.
	 * 
	 * @param unclassified
	 *            Unclassified Nutrition Context instance.
	 * @return Classified Nutrition Context instance.
	 */
	public NutritionContext inferTest(NutritionContext unclassified) {
		ValidityReport report = cv.validate(unclassified);
		if (report.isValid()) {
			NutritionContext classified = cc.classify(unclassified);
			logger.info("[HLC Reasoner: NutritionContext: ] " + classified.getCtxInstanceLocalName() + " classified as " 
					+ classified.getCtxTypeLocalName());
			return classified;
		} else {
			logger.info("[HLC Reasoner: NutritionContext: ] The NutritionContext HLC is not valid.");  
			Iterator<Report> i = report.getReports();
			while (i.hasNext())
				logger.info(i.next());
			return unclassified;
		}
	}
	/**
	 * Test method that applies the same business logic than inferHlc but prints
	 * messages through the standard output stream.
	 * 
	 * @param unclassified
	 *            Unclassified Nutrition Context instance.
	 * @return Classified Nutrition Context instance.
	 */
	public ClinicalContext inferTest(ClinicalContext unclassified) {
		ValidityReport report = cv.validate(unclassified);
		if (report.isValid()) {
			ClinicalContext classified = cc.classify(unclassified);
			logger.info("[HLC Reasoner: ClinicalContext: ] " + classified.getCtxInstanceLocalName() + " classified as " 
					+ classified.getCtxTypeLocalName());
			return classified;
		} else {
			logger.info("[HLC Reasoner: ClinicalContext: ] The ClinicalContext HLC is not valid.");  
			Iterator<Report> i = report.getReports();
			while (i.hasNext())
				logger.info(i.next());
			return unclassified;
		}
	}
	/**
	 * Test method that applies the same business logic than inferHlc but
	 * calculates the elapsed time and prints messages through the standard
	 * output stream.
	 * 
	 * @param unclassified
	 *            Unclassified PhysicalActivity Context instance.
	 * @return Classified PhysicalActivity Context instance.
	 */
	public PhysicalActivityContext inferTestElapsedTime(PhysicalActivityContext unclassified) {
		long s1 = System.currentTimeMillis();
		ValidityReport report = cv.validate(unclassified);
		long e1 = System.currentTimeMillis();
		logger.info("[HLC Reasoner: PhysicalActivityContext: ] " + unclassified.getCtxInstanceLocalName() + " validation lasted "
				+ (e1 - s1) + " ms.");
		logger.info("[HLC Reasoner: PhysicalActivityContext: ] " + unclassified.getCtxInstanceLocalName() + " validation lasted "
				+ (e1 - s1) + " ms.");  //FileUtil.WriteHLCLog
		if (report.isValid()) {
			long s2 = System.currentTimeMillis();
			PhysicalActivityContext classified = cc.classify(unclassified);
			long e2 = System.currentTimeMillis();
			logger.info("[HLC Reasoner: PhysicalActivityContext: ] " + classified.getCtxInstanceLocalName() + " classification lasted "
					+ (e2 - s2) + " ms.");
			logger.info("[HLC Reasoner: PhysicalActivityContext: ] " + classified.getCtxInstanceLocalName() + " classification lasted "
					+ (e2 - s2) + " ms.");//FileUtil.WriteHLCLog
			logger.info("[HLC Reasoner: PhysicalActivityContext: ] " + classified.getCtxInstanceLocalName()
					+ " HLC Reasoner overall process lasted " + (e2 - s1) + " ms.");
			logger.info("[HLC Reasoner: PhysicalActivityContext: ] " + classified.getCtxInstanceLocalName()
			+ " HLC Reasoner overall process lasted " + (e2 - s1) + " ms.");
			logger.info("[HLC Reasoner: PhysicalActivityContext: ] " + classified.getCtxInstanceLocalName() + " classified as "
					+ classified.getCtxTypeLocalName());
			logger.info("[HLC Reasoner: PhysicalActivityContext: ] " + classified.getCtxInstanceLocalName() + " classified as "
					+ classified.getCtxTypeLocalName());
			return classified;
		} else {
			logger.info("[HLC Reasoner: PhysicalActivityContext: ] The HLC is not valid.");
			logger.info("[HLC Reasoner: PhysicalActivityContext: ] The HLC is not valid.");
			Iterator<Report> i = report.getReports();
			while (i.hasNext()){
				logger.info(i.next());
				logger.info(i.next().toString());  
			}
			return unclassified;
		}
	}
	/**
	 * Test method that applies the same business logic than inferHlc but
	 * calculates the elapsed time and prints messages through the standard
	 * output stream.
	 * 
	 * @param unclassified
	 *            Unclassified Nutrition Context instance.
	 * @return Classified Nutrition Context instance.
	 */
	public NutritionContext inferTestElapsedTime(NutritionContext unclassified) {
		long s1 = System.currentTimeMillis();
		ValidityReport report = cv.validate(unclassified);
		long e1 = System.currentTimeMillis();
		logger.info("[HLC Reasoner: NutritionContext: ] " + unclassified.getCtxInstanceLocalName() + " validation lasted "
				+ (e1 - s1) + " ms.");
		logger.info("[HLC Reasoner: NutritionContext: ] " + unclassified.getCtxInstanceLocalName() + " validation lasted "
				+ (e1 - s1) + " ms.");
		if (report.isValid()) {
			long s2 = System.currentTimeMillis();
			NutritionContext classified = cc.classify(unclassified);
			long e2 = System.currentTimeMillis();
			logger.info("[HLC Reasoner: NutritionContext: ] " + classified.getCtxInstanceLocalName() + " classification lasted "
					+ (e2 - s2) + " ms.");
			logger.info("[HLC Reasoner: NutritionContext: ] " + classified.getCtxInstanceLocalName() + " classification lasted "
					+ (e2 - s2) + " ms.");
			logger.info("[HLC Reasoner: NutritionContext: ] " + classified.getCtxInstanceLocalName()
					+ " HLC Reasoner overall process lasted " + (e2 - s1) + " ms.");
			logger.info("[HLC Reasoner: NutritionContext: ] " + classified.getCtxInstanceLocalName()
			+ " HLC Reasoner overall process lasted " + (e2 - s1) + " ms.");
			logger.info("[HLC Reasoner: NutritionContext: ] " + classified.getCtxInstanceLocalName() + " classified as "
					+ classified.getCtxTypeLocalName());
			logger.info("[HLC Reasoner: NutritionContext: ] " + classified.getCtxInstanceLocalName() + " classified as "
					+ classified.getCtxTypeLocalName());
			return classified;
		} else {
			logger.info("[HLC Reasoner: NutritionContext: ] The NutritionContext is not valid.");
			logger.info("[HLC Reasoner: NutritionContext: ] The NutritionContext is not valid.");
			Iterator<Report> i = report.getReports();
			while (i.hasNext()){
				logger.info(i.next());
				logger.info(i.next().toString());
			}
			return unclassified;
		}
	}
	/**
	 * Test method that applies the same business logic than inferHlc but
	 * calculates the elapsed time and prints messages through the standard
	 * output stream.
	 * 
	 * @param unclassified
	 *            Unclassified Nutrition Context instance.
	 * @return Classified Clinical Context instance.
	 */
	public ClinicalContext inferTestElapsedTime(ClinicalContext unclassified) {
		long s1 = System.currentTimeMillis();
		ValidityReport report = cv.validate(unclassified);
		long e1 = System.currentTimeMillis();
		logger.info("[HLC Reasoner: ClinicalContext: ] " + unclassified.getCtxInstanceLocalName() + " validation lasted "
				+ (e1 - s1) + " ms.");
		logger.info("[HLC Reasoner: ClinicalContext: ] " + unclassified.getCtxInstanceLocalName() + " validation lasted "
				+ (e1 - s1) + " ms.");
		if (report.isValid()) {
			long s2 = System.currentTimeMillis();
			ClinicalContext classified = cc.classify(unclassified);
			long e2 = System.currentTimeMillis();
			logger.info("[HLC Reasoner: ClinicalContext: ] " + classified.getCtxInstanceLocalName() + " classification lasted "
					+ (e2 - s2) + " ms.");
			logger.info("[HLC Reasoner: ClinicalContext: ] " + classified.getCtxInstanceLocalName() + " classification lasted "
					+ (e2 - s2) + " ms.");
			logger.info("[HLC Reasoner: ClinicalContext: ] " + classified.getCtxInstanceLocalName()
					+ " HLC Reasoner overall process lasted " + (e2 - s1) + " ms.");
			logger.info("[HLC Reasoner: ClinicalContext: ] " + classified.getCtxInstanceLocalName()
			+ " HLC Reasoner overall process lasted " + (e2 - s1) + " ms.");
			logger.info("[HLC Reasoner: ClinicalContext: ] " + classified.getCtxInstanceLocalName() + " classified as "
					+ classified.getCtxTypeLocalName());
			logger.info("[HLC Reasoner: ClinicalContext: ] " + classified.getCtxInstanceLocalName() + " classified as "
					+ classified.getCtxTypeLocalName());
			return classified;
		} else {
			logger.info("[HLC Reasoner: ClinicalContext: ] The ClinicalContext is not valid.");
			logger.info("[HLC Reasoner: ClinicalContext: ] The ClinicalContext is not valid.");
			Iterator<Report> i = report.getReports();
			while (i.hasNext()){
				logger.info(i.next());
				logger.info(i.next().toString());
			}
			return unclassified;
		}
	}	
}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/communication/RulesService.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.communication;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.uclab.scl.datamodel.SituationConditions;
import org.uclab.scl.datamodel.Situations;

public class RulesService {
  private static Logger LOG = LogManager.getRootLogger();
  
  private String method = "POST";
  private Situations situationsData = new Situations();
  private String url = "http://192.168.127.12:7070/SpringMVCHibernate/situationReasoner";
  private String contentType = "application/json";
  private String accept = "application/json";
  private String charset = "UTF-8";

  private String response;

  private InputStream inputStream;

  public RulesService() {}

  public String getMethod() {
    return method;
  }

  public RulesService setMethod(String method) {
    this.method = method;
    return this;
  }

  public RulesService setSituationsData(Situations data) {
    this.situationsData = data;
    return this;
  }

  public String getUrl() {
    return url;
  }

  public RulesService setUrl(String url) {
    this.url = url;
    return this;
  }

  public String getContentType() {
    return contentType;
  }

  public RulesService setContentType(String contentType) {
    this.contentType = contentType;
    return this;
  }

  public String getAccept() {
    return accept;
  }

  public RulesService setAccept(String accept) {
    this.accept = accept;
    return this;
  }

  public String getCharset() {
    return charset;
  }

  public RulesService setCharset(String charset) {
    this.charset = charset;
    return this;
  }

  public RulesService connect(String _url) {
    this.url = _url;
    return connect();
  }

  public RulesService connect() {
    if (url == null) {
      LOG.error("URL not set!");
      System.exit(0);
    }
    if (method.equals("POST") && situationsData.getListSConditions().isEmpty()) {
      LOG.error("No post data set!");
      System.exit(0);
    }

    OutputStream outputStream = null;
    byte[] outputBytes = null;
    HttpURLConnection httpConnection = null;
    try {
      httpConnection = (HttpURLConnection) ((new URL(url).openConnection()));
      httpConnection.setDoOutput(true);
      httpConnection.setRequestProperty("Content-Type", getContentType());
      httpConnection.setRequestProperty("Accept", getAccept());
      httpConnection.setRequestMethod(getMethod());
      httpConnection.connect();
      outputBytes = situationsDataToJsonString().getBytes(getCharset());
      outputStream = httpConnection.getOutputStream();
      outputStream.write(outputBytes);
      outputStream.close();
      inputStream = httpConnection.getInputStream();
    } catch (MalformedURLException ex) {
      LOG.error("MalformedURLException");
      LOG.error(ex.getMessage());
    } catch (ProtocolException ex) {
      LOG.error("ProtocolException");
      LOG.error(ex.getMessage());
    } catch (UnsupportedEncodingException ex) {
      LOG.error("UnsupportedEncodingException");
      LOG.error(ex.getMessage());
    } catch (IOException ex) {
      LOG.error("IOException");
      LOG.error(ex.getMessage());
    }
    return this;
  }

  public RulesService getResponse() {
    StringBuilder responseBuilder = new StringBuilder();
    try {
      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
          inputStream));
      String line = null;
      while ((line = bufferedReader.readLine()) != null) {
        responseBuilder.append(line);
      }
      bufferedReader.close();
    } catch (IOException ex) {
      LOG.error("IOException");
      LOG.error(ex.getMessage());
    }
    response = responseBuilder.toString();
    return this;
  }

  public RulesService setSituationID(String situationID) {
    this.situationsData.setSituationID(situationID);
    return this;
  }

  public RulesService setSituationDescription(String situationDescription) {
    this.situationsData.setSituationDescription(situationDescription);
    return this;
  }

  public RulesService addSituationCondition(
      SituationConditions situationCondition) {
    this.situationsData.addSituationCondition(situationCondition);
    return this;
  }

  public List<Map<String, Object>> parse() {
    List<Map<String, Object>> rulesList = new ArrayList<Map<String, Object>>();
    ObjectMapper mapper = new ObjectMapper();
    try {
      rulesList = mapper.readValue(response, new TypeReference<ArrayList<Map<String, Object>>>() {});
    } catch (Exception e) {
      e.printStackTrace();
    }
    return rulesList;
  }

  public String situationsDataToJsonString() {
    String situationsAsJson = null;
    try {
      situationsAsJson = new ObjectMapper().writeValueAsString(this.situationsData);
    } catch (IOException ex) {
      ex.printStackTrace();
    }
    return situationsAsJson;
  }
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/ContextOntologyManager/ContextRemovalManager.java<|end_filename|>
//http://stackoverflow.com/questions/16064992/apache-jena-deleting-all-data-in-the-model
package mm.icl.hlc.ContextOntologyManager;

import mm.icl.hlc.OntologyTools.HLCA;

import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.tdb.TDBFactory;

public class ContextRemovalManager {

	private static Model model;
	private static Dataset dataset;

	public static Model getJenaModel(){
	    if(model!=null){
	        return model;
	    }
	    else{
	        String directory = "E:\\ICL_LOG\\TDB" ;
	        try{
	            dataset = TDBFactory.createDataset(directory);
	            model = dataset.getNamedModel(HLCA.ns); //"DB"
	            return model;
	            
	        }catch(Exception e){
	            System.out.println("Error when retrieving model: "+e.getMessage());
	        }              
	    }
	    return null;
	}

	public static void SaveAndCloseModel(){
	    if(model!=null && dataset!=null){
	        model.commit();
	        model.close();
	        dataset.close();
	        System.out.println("SavedClosedModel");
	    }
	}

	public static  void ClearModel(){
		
		model=getJenaModel();

		if(model!=null ){
	        model.removeAll();
	        SaveAndCloseModel();
	        System.out.println("ClearedModel");
	    }
	}
	
//	public static void main(String[] args) {
//		
//		try{
//System.out.println("plz check it......");
// 
//ClearModel();
//		}
//		catch(Exception e)
//		{
//			
//		}
//		
//	}

}

<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/MachineLearningTools/featureextraction/KincetARFeatureExtraction.java<|end_filename|>
/*
Copyright [2016] [Thien]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.MachineLearningTools.featureextraction;


public class KincetARFeatureExtraction {
	double [] inputData;
	double [] x,y,z;
	
	
	int[] siD = {2,3,3,2,2,2,2,3,3,3,3,3,4,8,10,13,17,18,2,2,2,2,2,3,4,4,7,8,8,8,9,11,14,20,20,0,0,0,0,0,0,0,1,1,1,1,1,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5};
	int[] sjD = {17,10,17,10,13,14,18,11,13,14,18,23,13,17,20,20,20,20,7,11,21,23,24,24,11,17,20,10,18,23,18,20,20,23,24,1,2,3,4,8,18,20,2,3,14,18,20,6,16,19,20,6,7,12,15,16,21,22,6,7,10,14,16,18,20,21,23,24,13,14};
	int[] siA = {16,0,0,1,1,1,5,11,11,12,0,0,0,1,2,3,5,5,5,6,6,6,7,8,9,9,9,10,10,10,11,12,12,12,14,15,16,16,16,19,20,22,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4};
	int[] sjA = {23,11,23,11,23,24,10,12,16,23,13,21,24,10,12,17,11,23,24,11,23,24,23,11,10,11,23,12,16,23,23,13,21,24,16,16,20,21,24,20,23,23,1,2,3,4,7,10,15,20,22,2,14,15,20,5,14,15,18,11,12,13,14,15,16,18,19,11,23,24};
	/*
	int[] siD = {3,2,2,2,3,3,3,3,3,8,17,0,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,5,5,6,6,8,8,8,8,8,8,9,9,9,9,10,11,12,13,13,14,16,18,19,20,20,0,0,0,0,0,0,1,1,2,2};
	int[] sjD = {10,6,7,17,7,11,17,23,24,17,20,1,10,18,10,11,13,14,15,18,19,21,23,24,6,13,14,15,18,19,21,22,10,13,17,13,14,12,20,13,14,18,19,21,23,14,17,18,19,20,20,21,17,20,20,20,20,20,21,23,2,4,7,12,20,22,2,14,4,5};
	int[] siA = {2,0,2,2,3,3,5,5,11,11,12,12,14,17,0,0,0,0,1,1,2,2,2,2,2,3,3,3,3,3,3,3,3,3,5,6,8,9,9,10,10,10,12,12,15,15,16,18,19,19,19,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,2};
	int[] sjA = {12,23,14,15,5,15,13,17,12,16,13,20,20,20,1,3,8,13,3,8,4,5,6,18,19,4,6,12,14,16,17,18,19,22,12,22,18,10,23,11,12,23,21,23,20,24,23,20,20,22,24,2,4,7,9,11,20,21,22,2,4,6,7,10,12,14,15,20,21,7};
	*/
	public void setInputData(double[] inputData){
		this.inputData = inputData;
		separateData();
	}
	public int getAngleFeatureSize(){
		return siA.length;
	}
	public int getDistanceFeatureSize(){
		return siD.length;
	}
	private void separateData(){
		x = new double[25];
		y = new double[25];
		z = new double[25];
		for (int i = 0;  i < 25; i++){
			x[i]=inputData[i*3];
			y[i]=inputData[i*3+1];
			z[i]=inputData[i*3+2];
		}
		/*
		System.out.print("X = ");
		for (int i = 0;  i < 25; i++){
			System.out.print(x[i] + "  ");
		}
		System.out.println("");
		
		System.out.print("Y = ");
		for (int i = 0;  i < 25; i++){
			System.out.print(y[i] + "  ");
		}
		System.out.println("");
		
		System.out.print("Z = ");
		for (int i = 0;  i < 25; i++){
			System.out.print(z[i] + "  ");
		}
		System.out.println("");*/
	} 
	private double distance3d(int i, int j){
		double d= 0;
		try{
			d=Math.sqrt(Math.pow(x[i]-x[j],2)+Math.pow(y[i]-y[j],2)+Math.pow(z[i]-z[j],2));
			
		}catch(Exception e){
			//System.out.println("i = "+i + ", j = " +j);
		}
		return d;
	}
	
	private double angle3d(int i,int j){
		double deltax=x[j]-x[i];
        double deltay=y[j]-y[i];
        double a = Math.atan(deltay/deltax);
        if (deltay == 0)
                        a=0;
        else if (deltay > 0 && deltax > 0)
                        a=a/(2*Math.PI);
        else if (deltay > 0 && deltax < 0)
                        a=(a+Math.PI)/(2*Math.PI);
        else if (deltay <0 && deltax < 0)
                        a=(a+Math.PI)/(2*Math.PI);
        else if (deltay <0 && deltax > 0)
                        a=(a+2*Math.PI)/(2*Math.PI);
        return a;
	}
	
	 public double[] extractDistanceFeature(){
		 int numFeatures = siD.length;
		 double[] features = new double[numFeatures];
		 for (int i = 0; i < numFeatures; i++){
			 features[i]=distance3d(siD[i],sjD[i]);
		 }
		 return features;
	 }
	 
	 public double[] extractAngleFeature(){
		 int numFeatures = siA.length;
		 double[] features = new double[numFeatures];
		 for (int i = 0; i < numFeatures; i++){
			 features[i]=angle3d(siA[i],sjA[i]);
		 }
		 return features;
	 }

}

<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/HLCReasoner/ContextVerifier.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.HLCReasoner;
import java.util.Iterator;

import org.mindswap.pellet.jena.PelletInfGraph;
import org.mindswap.pellet.jena.PelletReasonerFactory;

import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntResource;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.reasoner.StandardValidityReport;
import com.hp.hpl.jena.reasoner.ValidityReport;
import com.hp.hpl.jena.reasoner.ValidityReport.Report;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;

import mm.icl.hlc.OntologyTools.HLCA;
import mm.icl.hlc.OntologyTools.InferredContextOntology;
import mm.icl.hlc.OntologyTools.NutritionContext;
import mm.icl.hlc.OntologyTools.ClinicalContext;
import mm.icl.hlc.OntologyTools.PhysicalActivityContext;
/**
 * Context Verifier: Subcomponent of the HLC Reasoner which performs a
 * consistency check (validation and verification) of the unclassified
 * PhysicalActivity and Nutrition context instance versus the Context Ontology Model.
 * 
 * @author <NAME> and <NAME>
 * @version 2.5
 * @since 2015-10-28
 */
public class ContextVerifier {
	/**
	 * Inferred version of the Context Ontology which represents the Mining
	 * Minds Context Model.
	 */
	private InferredContextOntology ont;
	/**
	 * Constructor of a new Context Verifier.
	 * 
	 * @param ont
	 *            Inferred version of the Context Ontology which represents the
	 *            Mining Minds Context Model.
	 */
	public ContextVerifier(InferredContextOntology ont) {
		this.ont = ont;
	}
	/**
	 * Method to validate and verify an unclassified PhysicalActivity and Nutrition context instance
	 * versus the Context Ontology Model.
	 * 
	 * @param unclassifiedHlc
	 *            Unclassified PhysicalActivity Context instance.
	 * @return true if the unclassified PhysicalActivity Context Instance passed the
	 *         consistency check, and false otherwise.
	 */
	public boolean isValid(PhysicalActivityContext unclassifiedHlc) {
		return (validate(unclassifiedHlc).isValid());
	}
	/**
	 * Method to validate and verify an unclassified Nutrition context instance
	 * versus the Context Ontology Model.
	 * 
	 * @param unclassifiedHlc
	 *            Unclassified Nutrition Context instance.
	 * @return true if the unclassified Nutrition Context Instance passed the
	 *         consistency check, and false otherwise.
	 */
	public boolean isValid(NutritionContext unclassifiedNutHlc) {
		return (validate(unclassifiedNutHlc).isValid());
	}
	/**
	 * Method to validate and verify an unclassified Nutrition context instance
	 * versus the Context Ontology Model.
	 * 
	 * @param unclassifiedHlc
	 *            Unclassified Nutrition Context instance.
	 * @return true if the unclassified Nutrition Context Instance passed the
	 *         consistency check, and false otherwise.
	 */
	public boolean isValid(ClinicalContext unclassifiedCliHlc) {
		return (validate(unclassifiedCliHlc).isValid());
	}
	/**
	 * Method to validate and verify an unclassified PhysicalActivity context instance
	 * versus the Context Ontology Model.
	 * 
	 * @param unclassifiedHlc
	 *            Unclassified PhysicalActivity Context instance.
	 * @return Validity Report which contains the description of the errors in
	 *         the consistency check of unclassifiedHlc.
	 */
	public ValidityReport validate(PhysicalActivityContext unclassifiedHlc) {
		OntModel hlcInst = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC,
				unclassifiedHlc.getCtxModel());
		hlcInst.addSubModel(ont.getCtxModel());
		ValidityReport validity = hlcInst.validate();
		if (validity.isValid()) {
			if (validity.isClean()) {
				ExtendedIterator<? extends OntResource> it = hlcInst.getOntClass(HLCA.pacClassName)   
						.listInstances(false);
				if (it.hasNext()) {
					OntResource inst = it.next();
					if (!it.hasNext()) {
						unclassifiedHlc.setHlcInstance(inst);
						((PelletInfGraph) hlcInst.getGraph()).close(false);
						return validity;
					} else {
						StandardValidityReport report = new StandardValidityReport();
						report.add(true, "PhysicalActivityContext contains several instances of the class", HLCA.pacClassName); 
						report.add(false, "-", inst.getURI());
						while (it.hasNext())
							report.add(false, "-", it.next().getURI());
						((PelletInfGraph) hlcInst.getGraph()).close(false);
						return report;
					}
				} else {
					((PelletInfGraph) hlcInst.getGraph()).close(false);
					StandardValidityReport report = new StandardValidityReport();
					report.add(true, "PhysicalActivityContext does not contain an instance of the class", HLCA.pacClassName); 
					return report;
				}
			} else {
				((PelletInfGraph) hlcInst.getGraph()).close(false);
				StandardValidityReport report = new StandardValidityReport();
				report.add(true, "PhysicalActivityContext contains logical errors", "");
				Iterator<Report> it = validity.getReports();
				while (it.hasNext())
					report.add(it.next());
				return report;
			}
		}
		((PelletInfGraph) hlcInst.getGraph()).close(false);
		return validity;
	}
	/**
	 * Method to validate and verify an unclassified Nutrition context instance
	 * versus the Context Ontology Model.
	 * 
	 * @param unclassifiedHlc
	 *            Unclassified Nutrition Context instance.
	 * @return Validity Report which contains the description of the errors in
	 *         the consistency check of unclassifiedHlc.
	 */
	public ValidityReport validate(NutritionContext unclassifiedNutHlc) {
		OntModel hlcInst = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC,
				unclassifiedNutHlc.getCtxModel());
		hlcInst.addSubModel(ont.getCtxModel());
		ValidityReport validity = hlcInst.validate();
		if (validity.isValid()) {
			if (validity.isClean()) {
				ExtendedIterator<? extends OntResource> it = hlcInst.getOntClass(HLCA.nutrClassName)   
						.listInstances(false);
				if (it.hasNext()) {
					OntResource inst = it.next();
					if (!it.hasNext()) {
						unclassifiedNutHlc.setHlcInstance(inst);
						((PelletInfGraph) hlcInst.getGraph()).close(false);
						return validity;
					} else {
						StandardValidityReport report = new StandardValidityReport();
						report.add(true, "NutritionContext contains several instances of the class", HLCA.nutrClassName);
						report.add(false, "-", inst.getURI());
						while (it.hasNext())
							report.add(false, "-", it.next().getURI());
						((PelletInfGraph) hlcInst.getGraph()).close(false);
						return report;
					}
				} else {
					((PelletInfGraph) hlcInst.getGraph()).close(false);
					StandardValidityReport report = new StandardValidityReport();
					report.add(true, "NutritionContext does not contain an instance of the class", HLCA.nutrClassName); 
					return report;
				}
			} else {
				((PelletInfGraph) hlcInst.getGraph()).close(false);
				StandardValidityReport report = new StandardValidityReport();
				report.add(true, "NutritionContext contains logical errors", "");
				Iterator<Report> it = validity.getReports();
				while (it.hasNext())
					report.add(it.next());
				return report;
			}
		}
		((PelletInfGraph) hlcInst.getGraph()).close(false);
		return validity;
	}
	/**
	 * Method to validate and verify an unclassified Nutrition context instance
	 * versus the Context Ontology Model.
	 * 
	 * @param unclassifiedHlc
	 *            Unclassified Nutrition Context instance.
	 * @return Validity Report which contains the description of the errors in
	 *         the consistency check of unclassifiedHlc.
	 */
	public ValidityReport validate(ClinicalContext unclassifiedCliHlc) {
		OntModel hlcInst = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC,
				unclassifiedCliHlc.getCtxModel());
		hlcInst.addSubModel(ont.getCtxModel());
		ValidityReport validity = hlcInst.validate();
		if (validity.isValid()) {
			if (validity.isClean()) {
				ExtendedIterator<? extends OntResource> it = hlcInst.getOntClass(HLCA.clinicalClassName)   
						.listInstances(false);
				if (it.hasNext()) {
					OntResource inst = it.next();
					if (!it.hasNext()) {
						unclassifiedCliHlc.setHlcInstance(inst);
						((PelletInfGraph) hlcInst.getGraph()).close(false);
						return validity;
					} else {
						StandardValidityReport report = new StandardValidityReport();
						report.add(true, "ClinicalContext contains several instances of the class", HLCA.clinicalClassName);
						report.add(false, "-", inst.getURI());
						while (it.hasNext())
							report.add(false, "-", it.next().getURI());
						((PelletInfGraph) hlcInst.getGraph()).close(false);
						return report;
					}
				} else {
					((PelletInfGraph) hlcInst.getGraph()).close(false);
					StandardValidityReport report = new StandardValidityReport();
					report.add(true, "ClinicalContext does not contain an instance of the class", HLCA.clinicalClassName); 
					return report;
				}
			} else {
				((PelletInfGraph) hlcInst.getGraph()).close(false);
				StandardValidityReport report = new StandardValidityReport();
				report.add(true, "ClinicalContext contains logical errors", "");
				Iterator<Report> it = validity.getReports();
				while (it.hasNext())
					report.add(it.next());
				return report;
			}
		}
		((PelletInfGraph) hlcInst.getGraph()).close(false);
		return validity;
	}
}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/Utilities/DisibilitiesUtility.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.Utilities;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.uclab.scl.datamodel.Disibilities;
import org.uclab.scl.datamodel.RiskFactors;

/**
 * 
 * @author User
 */
public class DisibilitiesUtility {

  private DisibilitiesUtility() {
  }

  public static DisibilitiesUtility getDisibilitiesUtility() {
    return DisibilitiesHolder.INSTANCE;
  }

  public static Map<String, String> getDisabilitiesMap(List<Disibilities> disibilities) {
    Map<String, String> disibilityDictionary = new HashMap<String, String>();

    Iterator<Disibilities> itr = disibilities.iterator();

    while (itr.hasNext()) {

      switch (itr.next().getDisabilityID()) {
      case 1:

        disibilityDictionary.put("Visual Impairment", "Yes");
        break;

      case 2:

        disibilityDictionary.put("Deep", "Yes");
        break;

      case 3:

        disibilityDictionary.put("Social and Emotional", "Yes");
        break;

      case 4:

        disibilityDictionary.put("Physical Disability", "Yes");
        break;

      case 5:

        disibilityDictionary.put("Musculoskeletal", "Yes");
        break;

      case 6:

        disibilityDictionary.put("None", "Yes");
        break;

      }
    }
    return disibilityDictionary;
  }

  private static class DisibilitiesHolder {

    private static final DisibilitiesUtility INSTANCE = new DisibilitiesUtility();
  }
}


<|start_filename|>data-curation-layer/data-persistence/LocalFileManagement.js<|end_filename|>

/**
 * @author <NAME>
 * @since 2016.11.21
 * @version 0.1

 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at

 *   http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


/**
 * @description Storing data in local(temp.txt).
 * @description Storing metadata in local(metadata.txt).
 * @module lfm(LocalFileManagement)
 * @param {string} parsed sequential JSON data.
 * @return {number} cnt
 */

var config = require('./config.json');
var fs = require('fs');
var unitSize = config.fileSizeUnit;

exports.lfm = function(userID, timestamp, contentbody){	

	var cnt;
	var filedata; 

	filedata = fs.readFileSync('temp.txt', 'utf-8');
	fs.writeFileSync('temp.txt', filedata + '\r\n' + userID + '  ' + timestamp + '  ' + contentbody);

	var stats = fs.statSync("temp.txt");
	var fileSizeInBytes = stats["size"];
	console.log("temp.txt file size is : " + fileSizeInBytes);

	if(fileSizeInBytes < unitSize)
	{
		console.log("File is not full");
		return -1;
	}
	else
	{
		cnt = fs.readFileSync('metadata.txt', 'utf-8');
		fs.writeFileSync('metadata.txt', parseInt(cnt)+1);
		console.log("File is Full : is seding to HDFS Server!");
		return cnt;
	}

	return -1;
};


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/ic/dataadapter/UserRecognizedHLCAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.ic.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.ic.UserRecognizedHLC;

/**
 * This is UserRecognizedHLCAdapter class which implements the Data Access Interface for CRUD operations
 * @author Taqdir
 */
public class UserRecognizedHLCAdapter implements DataAccessInterface {

    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(UserRecognizedHLCAdapter.class);
    public UserRecognizedHLCAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving UserRecognizedHLC. 
     * @param objUserRecognizedHLC
     * @return List of String
     */
    @Override
    public List<String> Save(Object objUserRecognizedHLC) {
        UserRecognizedHLC objInnerUserRecognizedHLC = new UserRecognizedHLC();
        objInnerUserRecognizedHLC =  (UserRecognizedHLC) objUserRecognizedHLC;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_UserRecognizedHLC(?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserID", objInnerUserRecognizedHLC.getUserId());
            objCallableStatement.setString("HLCLabel", objInnerUserRecognizedHLC.gethLCLabel());
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
             Date dtStartDate = sdf.parse(objInnerUserRecognizedHLC.getStartTime());
            Timestamp tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);
            
            objCallableStatement.setTimestamp("StartTime", tsStartDate);
            objCallableStatement.registerOutParameter("UserRecognizedHLCID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intUserRecognizedHLCID = objCallableStatement.getLong("UserRecognizedHLCID");
            objDbResponse.add(String.valueOf(intUserRecognizedHLCID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("User Recognized HighLC saved successfully, User Recognized HighLC Details="+objUserRecognizedHLC);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding User Recognized HighLC");
        	objDbResponse.add("Error in adding User Recognized HighLC");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for updating UserRecognizedHLC. 
     *Not implemented
     */
    @Override
    public <T> List<String> Update(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for retrieving UserRecognizedHLC.
     * @param objUserRecognizedHLC
     * @return List of UserRecognizedHLC 
     */
    @Override
    public List<UserRecognizedHLC> RetriveData(Object objUserRecognizedHLC) {
        
        UserRecognizedHLC objOuterUserRecognizedHLC = new UserRecognizedHLC();
        List<UserRecognizedHLC> objListInnerUserRecognizedHLC = new ArrayList<UserRecognizedHLC>();
        objOuterUserRecognizedHLC =  (UserRecognizedHLC) objUserRecognizedHLC;
        
        try
        {
            CallableStatement objCallableStatement = null;
            Timestamp tsStartDate = null;
            Timestamp tsEndDate = null;
            
            if(objOuterUserRecognizedHLC.getRequestType() == "LatestByUser")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_CurrentUserRecognizedHLCByUserID(?)}");
                objCallableStatement.setLong("UserID", objOuterUserRecognizedHLC.getUserId());
            }
            else if(objOuterUserRecognizedHLC.getRequestType() == "UserDateRange")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UserRecognizedHLCByUserID(?, ?, ?)}");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
                Date dtStartDate = sdf.parse(objOuterUserRecognizedHLC.getStartTime());
                tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);

                Date dtEndDate = sdf.parse(objOuterUserRecognizedHLC.getEndTime());
                tsEndDate = new Timestamp(dtEndDate.getYear(),dtEndDate.getMonth(), dtEndDate.getDate(), dtEndDate.getHours(), dtEndDate.getMinutes(),dtEndDate.getSeconds(),0);

                objCallableStatement.setLong("UserID", objOuterUserRecognizedHLC.getUserId());
                objCallableStatement.setTimestamp("StartTime", tsStartDate);
                objCallableStatement.setTimestamp("EndTime", tsEndDate);
            }
            
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                UserRecognizedHLC objInnerUserRecognizedHLC = new UserRecognizedHLC();
                objInnerUserRecognizedHLC.setUserRecognizedHLCId(objResultSet.getLong("UserRecognizedHLCID"));
                objInnerUserRecognizedHLC.setUserId(objResultSet.getLong("UserID"));
                objInnerUserRecognizedHLC.sethLCLabel(objResultSet.getString("HLCLabel"));
                
                if(objResultSet.getTimestamp("StartTime") != null)
                {
                    tsStartDate = objResultSet.getTimestamp("StartTime");// updated
                    objInnerUserRecognizedHLC.setStartTime( tsStartDate.toString());
                }
                else
                {
                    objInnerUserRecognizedHLC.setStartTime(null);
                }
                if(objResultSet.getTimestamp("EndTime") != null)
                {
                    tsEndDate = objResultSet.getTimestamp("EndTime");// updated
                    objInnerUserRecognizedHLC.setEndTime( tsEndDate.toString());
                }
                else
                {
                    objInnerUserRecognizedHLC.setEndTime( null );
                }
                        
                objInnerUserRecognizedHLC.setDuration(objResultSet.getLong("Duration"));
                
                objListInnerUserRecognizedHLC.add(objInnerUserRecognizedHLC);
            }
            objConn.close();
            logger.info("User Recognized HLC are loaded successfully.");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading User Recognized HLC");
        }   
        return objListInnerUserRecognizedHLC;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/outputModel/InterpretationModel/PhyActivityException.java<|end_filename|>
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.uclab.scl.outputModel.InterpretationModel;

/**
 * 
 * @author User
 */
public class PhyActivityException {

  private long recommendationExceptionID;

  private String exception;

  private String customRule;

  private long recommendationID;

  private String exceptionReason;

  public long getRecommendationExceptionID() {
    return recommendationExceptionID;
  }

  public void setRecommendationExceptionID(long recommendationExceptionID) {
    this.recommendationExceptionID = recommendationExceptionID;
  }

  public String getException() {
    return exception;
  }

  public void setException(String exception) {
    this.exception = exception;
  }

  public String getCustomRule() {
    return customRule;
  }

  public void setCustomRule(String customRule) {
    this.customRule = customRule;
  }

  public long getRecommendationID() {
    return recommendationID;
  }

  public void setRecommendationID(long recommendationID) {
    this.recommendationID = recommendationID;
  }

  public String getExceptionReason() {
    return exceptionReason;
  }

  public void setExceptionReason(String exceptionReason) {
    this.exceptionReason = exceptionReason;
  }

  @Override
  public String toString() {
    return "ClassPojo [recommendationExceptionID = "
        + recommendationExceptionID + ", exception = " + exception
        + ", customRule = " + customRule + ", recommendationID = "
        + recommendationID + ", exceptionReason = " + exceptionReason + "]";
  }

}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/MainServlet.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Kang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

This source code includes CDDL-licensed javax.servlet library
*/
package org.uclab.mm.icl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;

import org.uclab.mm.icl.llc.LLCManager.User;

@WebServlet(name="MainServlet", urlPatterns = {"/main"})
public class MainServlet implements Servlet {
	/**/
	public final static LLCServer server = new LLCServer(2950);
	//public final static HLCServer sserver = new HLCServer();
	private static final HashMap<Long, User> map = new HashMap<Long, User>(); // have to be moved somewhere

	private transient ServletConfig servletConfig;

	
	public static HashMap<Long, User> getUserMap(){
		return map;
	}
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public ServletConfig getServletConfig() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getServletInfo() {
		// TODO Auto-generated method stub
		return "Main Servlet for ICL 3.0";
	}

	@Override
	public void init(ServletConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		this.servletConfig = arg0;
	}

	@Override
	public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String servletName = servletConfig.getServletName();
		arg1.setContentType("text/html");
		PrintWriter writer = arg1.getWriter();
		writer.print("<html><head></head><body>Hello from " + servletName + "</body></html>" );
	}
	
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/ic/dataadapter/UserRecognizedActivityAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.ic.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.ic.UserRecognizedActivity;

/**
 * This is UserRecognizedActivityAdapter class which implements the Data Access Interface for CRUD operations
 * @author Taqdir
 */
public class UserRecognizedActivityAdapter implements DataAccessInterface{

    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(UserRecognizedActivityAdapter.class);
    public UserRecognizedActivityAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving UserRecognizedActivity.
     * @param objUserRecognizedActivity
     * @return List of String 
     */
    @Override
    public List<String> Save(Object objUserRecognizedActivity) {
        UserRecognizedActivity objInnerUserRecognizedActivity = new UserRecognizedActivity();
        objInnerUserRecognizedActivity =  (UserRecognizedActivity) objUserRecognizedActivity;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

             CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_UserRecognizedActivity(?, ?, ?, ?)}");
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
            Date dtStartDate = sdf.parse(objInnerUserRecognizedActivity.getStartTime());
            Timestamp tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);
                       
            objCallableStatement.setLong("UserID", objInnerUserRecognizedActivity.getUserId());
            objCallableStatement.setInt("ActivityID", objInnerUserRecognizedActivity.getActivityId());
            objCallableStatement.setTimestamp("StartTime", tsStartDate);
                                   
            objCallableStatement.registerOutParameter("UserRecognizedActivityID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intUserRecognizedActivityID = objCallableStatement.getLong("UserRecognizedActivityID");
            objDbResponse.add(String.valueOf(intUserRecognizedActivityID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("user recognized activities saved successfully, user recognized activities Details="+objUserRecognizedActivity);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding  user recognized activities");
        	objDbResponse.add("Error in adding user recognized activities");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for Updating UserRecognizedActivity.
     * Not implemented
     */
    @Override
    public <T> List<String> Update(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for retrieving UserRecognizedActivity.
     * @param objUserRecognizedActivity
     * @return List of UserRecognizedActivity 
     */
    @Override
    public List<UserRecognizedActivity> RetriveData(Object objUserRecognizedActivity) {
        UserRecognizedActivity objOuterUserRecognizedActivity = new UserRecognizedActivity();
        List<UserRecognizedActivity> objListInnerUserRecognizedActivity = new ArrayList<UserRecognizedActivity>();
        objOuterUserRecognizedActivity =  (UserRecognizedActivity) objUserRecognizedActivity;
        
        try
        {
            CallableStatement objCallableStatement = null;
            Timestamp tsStartDate = null;
            Timestamp tsEndDate = null;
            if(objOuterUserRecognizedActivity.getRequestType() == "LatestByUser")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_CurrentUserRecognizedActivityByUserID(?)}");
                objCallableStatement.setLong("UserID", objOuterUserRecognizedActivity.getUserId());
            }
            else if(objOuterUserRecognizedActivity.getRequestType() == "UserDateRange")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UserRecognizedActivityByUserID(?, ?, ?)}");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
                Date dtStartDate = sdf.parse(objOuterUserRecognizedActivity.getStartTime());
                tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);

                Date dtEndDate =sdf.parse( objOuterUserRecognizedActivity.getEndTime()); //.getTime();
                tsEndDate = new Timestamp(dtEndDate.getYear(),dtEndDate.getMonth(), dtEndDate.getDate(), dtEndDate.getHours(), dtEndDate.getMinutes(),dtEndDate.getSeconds(),0);

                objCallableStatement.setLong("UserID", objOuterUserRecognizedActivity.getUserId());
                objCallableStatement.setTimestamp("StartTime", tsStartDate);
                objCallableStatement.setTimestamp("EndTime", tsEndDate);
            }
            else if(objOuterUserRecognizedActivity.getRequestType() == "UserDateRangeAccumulate")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UserRecognizedActivityByUserIDAccumulate(?, ?, ?)}");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
                Date dtStartDate = sdf.parse(objOuterUserRecognizedActivity.getStartTime());
                tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);

                Date dtEndDate =sdf.parse( objOuterUserRecognizedActivity.getEndTime()); //.getTime();
                tsEndDate = new Timestamp(dtEndDate.getYear(),dtEndDate.getMonth(), dtEndDate.getDate(), dtEndDate.getHours(), dtEndDate.getMinutes(),dtEndDate.getSeconds(),0);

                objCallableStatement.setLong("UserID", objOuterUserRecognizedActivity.getUserId());
                objCallableStatement.setTimestamp("StartTime", tsStartDate);
                objCallableStatement.setTimestamp("EndTime", tsEndDate);
            }
                
            
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                UserRecognizedActivity objInnerUserRecognizedActivity = new UserRecognizedActivity();
                if(objResultSet.getLong("UserRecognizedActivityID") != 0)
                {
                    objInnerUserRecognizedActivity.setUserRecognizedActivityId(objResultSet.getLong("UserRecognizedActivityID"));
                }
                
                objInnerUserRecognizedActivity.setUserId(objResultSet.getLong("UserID"));
                objInnerUserRecognizedActivity.setActivityId(objResultSet.getInt("ActivityID"));
                objInnerUserRecognizedActivity.setActivityDescription(objResultSet.getString("ActivityDescription"));
                
                try
                {
                    if(objResultSet.getObject("StartTime") != null)
                    {
                        tsStartDate = objResultSet.getTimestamp("StartTime"); //updated
                        objInnerUserRecognizedActivity.setStartTime(tsStartDate.toString());
                    }
                }
                catch(Exception ex)
                {}
                
                try
                {
                    if(objResultSet.getObject("EndTime") != null)
                    {
                        tsEndDate = objResultSet.getTimestamp("EndTime"); // updated
                        objInnerUserRecognizedActivity.setEndTime(tsEndDate.toString());
                    }
                }
                catch(Exception ex)
                {
                }
                
                objInnerUserRecognizedActivity.setDuration(objResultSet.getLong("Duration"));
                objListInnerUserRecognizedActivity.add(objInnerUserRecognizedActivity);
            }
            objConn.close();
            logger.info("users recognized activities successfully loaded");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading users recognized activities");
        }   
        return objListInnerUserRecognizedActivity;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sl/UserAccelerometerDataVisulization.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sl;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author dcadmin
 */
@Entity
public class UserAccelerometerDataVisulization implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    // updated Taqdir Ali
    private Long userAccelerometerDataId;
    private Long userDeviceId;
    private Float xCoordinate ;
    private Float yCoordinate ;
    private Float zCoordinate ;
    private String timeStampStart;
    private String timeStampEnd;
    private String timeStamp;
    
    
    
    

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof UserAccelerometerDataVisulization)) {
            return false;
        }
        UserAccelerometerDataVisulization other = (UserAccelerometerDataVisulization) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.sl.UserrAccelerometerDataVisulization[ id=" + id + " ]";
    }

    /**
     * @return the userAccelerometerDataId
     */
    public Long getUserAccelerometerDataId() {
        return userAccelerometerDataId;
    }

    /**
     * @param userAccelerometerDataId the userAccelerometerDataId to set
     */
    public void setUserAccelerometerDataId(Long userAccelerometerDataId) {
        this.userAccelerometerDataId = userAccelerometerDataId;
    }

    /**
     * @return the userDeviceId
     */
    public Long getUserDeviceId() {
        return userDeviceId;
    }

    /**
     * @param userDeviceId the userDeviceId to set
     */
    public void setUserDeviceId(Long userDeviceId) {
        this.userDeviceId = userDeviceId;
    }

    /**
     * @return the xCoordinate
     */
    public Float getxCoordinate() {
        return xCoordinate;
    }

    /**
     * @param xCoordinate the xCoordinate to set
     */
    public void setxCoordinate(Float xCoordinate) {
        this.xCoordinate = xCoordinate;
    }

    /**
     * @return the yCoordinate
     */
    public Float getyCoordinate() {
        return yCoordinate;
    }

    /**
     * @param yCoordinate the yCoordinate to set
     */
    public void setyCoordinate(Float yCoordinate) {
        this.yCoordinate = yCoordinate;
    }

    /**
     * @return the zCoordinate
     */
    public Float getzCoordinate() {
        return zCoordinate;
    }

    /**
     * @param zCoordinate the zCoordinate to set
     */
    public void setzCoordinate(Float zCoordinate) {
        this.zCoordinate = zCoordinate;
    }

    /**
     * @return the timeStampStart
     */
    public String getTimeStampStart() {
        return timeStampStart;
    }

    /**
     * @param timeStampStart the timeStampStart to set
     */
    public void setTimeStampStart(String timeStampStart) {
        this.timeStampStart = timeStampStart;
    }

    /**
     * @return the timeStampEnd
     */
    public String getTimeStampEnd() {
        return timeStampEnd;
    }

    /**
     * @param timeStampEnd the timeStampEnd to set
     */
    public void setTimeStampEnd(String timeStampEnd) {
        this.timeStampEnd = timeStampEnd;
    }

    /**
     * @return the timeStamp
     */
    public String getTimeStamp() {
        return timeStamp;
    }

    /**
     * @param timeStamp the timeStamp to set
     */
    public void setTimeStamp(String timeStamp) {
        this.timeStamp = timeStamp;
    }
    
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/AER/jh/AudioBufferManagement.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Bang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.AER.jh;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;


public class AudioBufferManagement {


	AudioInputStream result;
	AudioFormat af;
	ConvertAudioData cad = new ConvertAudioData();

	public AudioBufferManagement(AudioFormat af) {
		this.af =af;
	}

	public AudioInputStream accumulateData(AudioInputStream input1,
			AudioInputStream input2) {
		byte[] data1 = null;
		byte[] data2 = null;
		byte[] merge =null;
		if(input1 != null){
			data1 = cad.convertByteBuffer(input1);
		}
		if(input2!=null){
			data2 = cad.convertByteBuffer(input2);
		}
		if(input1 !=null && input2 != null){
			merge = mergeBuffer(data1, data2);
		}
		if(input1 != null && input2 ==null){
			merge = data1;
		}
		if(input1 == null && input2 != null){
			merge = data2;
		}
		result = cad.convertAudioInputStream(merge,af);
		return result;
	}

	private byte[] mergeBuffer(byte[] data1, byte[] data2) {
		byte[] result = null;
		int cnt = 0;
		if (data1.length + data2.length > 0) {
			result = new byte[data1.length + data2.length];
			for (int i = 0; i < data1.length; i++) {
				result[cnt] = data1[i];
				cnt++;
			}
			for (int i = 0; i < data2.length; i++) {
				result[cnt] = data2[i];
				cnt++;
			}
		}
		return result;
	}
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/dc/dataadapter/UserDataAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.dc.dataadapter;

//import com.sun.xml.rpc.processor.modeler.j2ee.xml.string;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.dc.Users;

/**
 * This is UserDataAdapter class which implements the Data Access Interface for CRUD operations
 * @author Taqdir
 */
public class UserDataAdapter implements DataAccessInterface{

    private Connection objConn;
    
    private static final Logger logger = LoggerFactory.getLogger(UserDataAdapter.class);
    
    public UserDataAdapter()
    {
        
    }

    /**
     * This is implementation function for saving User.
     * @param objUser
     * @return List of String 
     */
    @Override
    public List<String> Save(Object objUser) {
        
        Users objInnerUser = new Users();
        objInnerUser =  (Users) objUser;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_User(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setString("FirstName", objInnerUser.getFirstName());
            objCallableStatement.setString("LastName", objInnerUser.getLastName());
            objCallableStatement.setString("MiddleName", objInnerUser.getMiddleName());
            objCallableStatement.setInt("GenderID", objInnerUser.getGenderId());
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
             Date dtDateOfBirth = sdf.parse(objInnerUser.getDateOfBirth());
            Timestamp tsDateOfBirth = new Timestamp(dtDateOfBirth.getYear(),dtDateOfBirth.getMonth(), dtDateOfBirth.getDate(), 00, 00, 00, 00);
            objCallableStatement.setTimestamp("DateOfBirth", tsDateOfBirth);
            
            objCallableStatement.setString("ContactNumber", objInnerUser.getContactNumber());
            objCallableStatement.setString("EmailAddress", objInnerUser.getEmailAddress());
            objCallableStatement.setString("Password", <PASSWORD>());
            objCallableStatement.setInt("MaritalStatusID", objInnerUser.getMartialStatusId());
            objCallableStatement.setInt("ActivityLevelID", objInnerUser.getActivityLevelId());
            objCallableStatement.setInt("OccupationID", objInnerUser.getOccupationId());
            objCallableStatement.setInt("UserTypeID", objInnerUser.getUserTypeID());
            
            objCallableStatement.registerOutParameter("UserID", Types.BIGINT);
            objCallableStatement.execute();
            
            int intUserID = objCallableStatement.getInt("UserID");
            objDbResponse.add(String.valueOf(intUserID));
            objDbResponse.add("No Error");
            

            objConn.close();
            logger.info("User saved successfully, User Details="+objUser);
        }
        catch (Exception e)
        {
        	logger.info("Error in saving user, User Details=");
        	objDbResponse.add("Error in saving user");
        }   
        
        return objDbResponse;
    }

    /**
     * This is implementation function for updating User.
     * @param objUser
     * @return List of string
     *  
     */
    @Override
    public List<String> Update(Object objUser) {
        
        Users objInnerUser = new Users();
        objInnerUser =  (Users) objUser;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_User(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserID", objInnerUser.getUserID());
            objCallableStatement.setString("FirstName", objInnerUser.getFirstName());
            objCallableStatement.setString("LastName", objInnerUser.getLastName());
            objCallableStatement.setString("MiddleName", objInnerUser.getMiddleName());
            objCallableStatement.setInt("GenderID", objInnerUser.getGenderId());
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
            Date dtDateOfBirth = sdf.parse(objInnerUser.getDateOfBirth());
            Timestamp tsDateOfBirth = new Timestamp(dtDateOfBirth.getYear(),dtDateOfBirth.getMonth(), dtDateOfBirth.getDate(), 00, 00, 00, 00);
            objCallableStatement.setTimestamp("DateOfBirth", tsDateOfBirth);
            
            objCallableStatement.setString("ContactNumber", objInnerUser.getContactNumber());
            objCallableStatement.setString("EmailAddress", objInnerUser.getEmailAddress());
            objCallableStatement.setString("Password", <PASSWORD>());
            objCallableStatement.setInt("MaritalStatusID", objInnerUser.getMartialStatusId());
            objCallableStatement.setInt("ActivityLevelID", objInnerUser.getActivityLevelId());
            objCallableStatement.setInt("OccupationID", objInnerUser.getOccupationId());
            objCallableStatement.setInt("UserTypeID", objInnerUser.getUserTypeID());
            
            objCallableStatement.execute();
            
            objDbResponse.add(String.valueOf(objInnerUser.getUserID()));
            objDbResponse.add("No Error");
            
            objConn.close();
            logger.info("User udpated successfully, User Details="+objUser);
        }
        catch (Exception e)
        {
        	logger.info("Error in updating user, User Details=");
        	objDbResponse.add("Error in saving user");
        }   
        
        return objDbResponse;
    }

    /**
     * This is implementation function for retrieving User. 
     * @param objUser
     * @return List of Users
     */
    @Override
    public List<Users> RetriveData(Object objUser) {
        
        Users objOuterUser = new Users();
        List<Users> objListInnerUser = new ArrayList<Users>();
        objOuterUser =  (Users) objUser;
        
        try
        {
            CallableStatement objCallableStatement = null;
            if(objOuterUser.getRequestType() == "UserData")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UserByID(?)}");
                objCallableStatement.setLong("UserID", objOuterUser.getUserID());
            }
            else if(objOuterUser.getRequestType() == "UserValidate")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Validate_User(?, ?)}");
                objCallableStatement.setString("EmailAddress", objOuterUser.getEmailAddress());
                objCallableStatement.setString("Password", objOuterUser.getPassword());
            }
            else if(objOuterUser.getRequestType() == "IsUserExist")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_IsExist_User(?)}");
                objCallableStatement.setString("EmailAddress", objOuterUser.getEmailAddress());
            }
            else if(objOuterUser.getRequestType() == "UsersListByExpert")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UsersListByExpertID(?)}");
                objCallableStatement.setLong("UserID", objOuterUser.getUserID());
            }
                
            
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                Users objInnerUser = new Users();
                objInnerUser.setUserID(objResultSet.getLong("UserID"));
                objInnerUser.setFirstName(objResultSet.getString("FirstName"));
                objInnerUser.setLastName(objResultSet.getString("LastName"));
                objInnerUser.setMiddleName(objResultSet.getString("MiddleName"));
                objInnerUser.setGenderId(objResultSet.getInt("GenderID"));
                
                Timestamp tsDateOfBirth = objResultSet.getTimestamp("DateOfBirth");
                objInnerUser.setDateOfBirth(tsDateOfBirth.toString());
               
                objInnerUser.setContactNumber(objResultSet.getString("ContactNumber"));
                objInnerUser.setEmailAddress(objResultSet.getString("EmailAddress"));
                objInnerUser.setPassword(objResultSet.getString("Password"));
                objInnerUser.setMartialStatusId(objResultSet.getInt("MaritalStatusID"));
                objInnerUser.setActivityLevelId(objResultSet.getInt("ActivityLevelID"));
                objInnerUser.setOccupationId(objResultSet.getInt("OccupationID"));
                                
                objInnerUser.setUserTypeID(objResultSet.getInt("UserTypeID"));
                if(objResultSet.getString("UserTypeDescription") != null)
                {
                    objInnerUser.setUserTypeDescription(objResultSet.getString("UserTypeDescription"));
                }
                
                objInnerUser.setGenderDescription(objResultSet.getString("GenderDescription"));
                objInnerUser.setMaritalStatusDescription(objResultSet.getString("MaritalStatusDescription"));
                objInnerUser.setOccupationDescription(objResultSet.getString("OccupationDescription"));
                
                objListInnerUser.add(objInnerUser);
            }
            objConn.close();
            logger.info("User loaded successfully.");
        }
        catch (Exception e)
        {
        	logger.info("Error in getting user");
        }   
        return objListInnerUser;
    }
    public <T> List<T> convert(List list, T t){ return list; }

    @Override
    public List<Object> Delete(Object objConn) {
        throw new UnsupportedOperationException("Not supported yet."); 
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/communication/DCCurrentContextWSClient.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.communication;

import java.util.List;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.uclab.scl.interpreterdatamodel.CurrentContext;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
/**
 * @version MM v2.5
 * @author Afzal
 *
 */
public class DCCurrentContextWSClient extends AbstractRestClient<CurrentContext, String> {
  
  /**
   * Instantiates WebService Client
   * <p>
   * @param baseURI
   */
  public DCCurrentContextWSClient(String baseURI) {
    super(baseURI);
  }
  
  /**
   * return current Context
   * 
   * <p>
   * @param Resource Url
   * @return current Context
   */
  @Override
  public CurrentContext GetData(String GET_ResourceURI) {
    List<CurrentContext> currentContextList = null;
    CurrentContext currentContext = null;
    try {
      ClientConfig config = new DefaultClientConfig();
      config.getClasses().add(JacksonJsonProvider.class);
      Client client = Client.create(config);
      WebResource service = client.resource(UriBuilder.fromUri(baseURI).build());
      currentContext = service.path(GET_ResourceURI).accept(MediaType.APPLICATION_JSON).get(new GenericType<CurrentContext>() {});
    } catch (Exception exp) {
      System.err.println(exp.getMessage());
    }
    return currentContext;
  }
  /**
   * 
   * <p>
   * @param Resource Uri
   * @param currentContext
   * @return String
   */
  @Override
  public String PostData(String POST_ResourceURI, CurrentContext postedResource) {
    throw new UnsupportedOperationException("Not supported yet.");
  }
}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/outputModel/PhysicalActivityIntepratedRecommendations.java<|end_filename|>
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.uclab.scl.outputModel;

import java.util.ArrayList;
import java.util.List;

import org.uclab.scl.outputModel.RecModel.PhyActivityFacts;
import org.uclab.scl.outputModel.RecModel.PhyActivityRecommendations;

/**
 * 
 * @author User
 */
public class PhysicalActivityIntepratedRecommendations {

  private List<PhyActivityRecommendations> phyActRecommendation = new ArrayList<PhyActivityRecommendations>();
  private List<PhyActivityFacts> phyActivityFacts = new ArrayList<PhyActivityFacts>();

  public List<PhyActivityRecommendations> getPhyActRecommendation() {
    return phyActRecommendation;
  }

  public void setPhyActRecommendation(
      List<PhyActivityRecommendations> phyActRecommendation) {
    this.phyActRecommendation = phyActRecommendation;
  }

  /**
   * @return the phyActivityFacts
   */
  public List<PhyActivityFacts> getPhyActivityFacts() {
    return phyActivityFacts;
  }

  /**
   * @param phyActivityFacts
   *          the phyActivityFacts to set
   */
  public void setPhyActivityFacts(List<PhyActivityFacts> phyActivityFacts) {
    this.phyActivityFacts = phyActivityFacts;
  }

}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/framework/RecInterpreter/PARecommender/MultiRecAlternativeRecEval.java<|end_filename|>
/* Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.scl.framework.RecInterpreter.PARecommender;

import java.util.HashMap;
import java.util.Scanner;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.uclab.scl.datamodel.contextMapper.*;

public class MultiRecAlternativeRecEval {
	private static Logger LOG = LogManager.getRootLogger();

  static HashMap<String, String> mapWeatherRec = new HashMap<>();
  static HashMap<String, String> mapDisableRec = new HashMap<>();
  static HashMap<String, String> mapRec_rec = new HashMap<>();

  @SuppressWarnings("unchecked")
  public static int[] recFiltrationAlternative(String rec, String currentContext, String userid) throws Exception {

    RecommendationMapper recommendationMapper = new RecommendationMapper();

    LOG.debug("NOW IN MultiRecAltRec Func");
    mapRec_rec = recommendationMapper.recMapper();
    int[] contentResult = ContextEvaluator.generateContextMatrix(currentContext);

    String temp = mapRec_rec.containsKey(rec) ? mapRec_rec.get(rec) : mapRec_rec.get(null);
    int index = 0;
    if (temp != null)
      index = Integer.parseInt(temp);
    else {
      LOG.debug("Recommendation NOT FOUND in the repository");
      LOG.debug("Default case applied");
      index = Integer.parseInt(mapRec_rec.get("D"));
      LOG.debug("index value " + index);
    }

    int[] aggregate = new int[contentResult.length];
    System.arraycopy(contentResult, 0, aggregate, 0, contentResult.length);
    int sum = 0;
    int prefSum = 0;

    // Displaying AR_list
    LOG.debug("Displaying AR_List");
    for (int i = 0; i < aggregate.length; i++) {
      LOG.debug(aggregate[i] + " ");
      sum += aggregate[i];
    }
    LOG.debug(" ");

    int[] originalRec = new int[aggregate.length];
    java.util.Arrays.fill(originalRec, 0);

    if (aggregate[index] == 0) {
      LOG.debug("Alternative Rec needed");
      if (sum == 0) {
        LOG.debug("okay neither original rec is fine nor we have an alternative rec !!!");
        int temp_critical_ctxt[] = multiRecCriticalContext(currentContext);
        System.arraycopy(temp_critical_ctxt, 0, aggregate, 0,
            temp_critical_ctxt.length);
      } else if ((sum > 1) && (sum != 0)) { // PREFERENCE CHKING
        LOG.debug("okay now we have multiple alternative rec; now Preference check needed");
        int[] ARP = evalMultiRecPreferences(aggregate, userid, currentContext);
        LOG.debug("Displaying ARP_List");
        for (int i = 0; i < ARP.length; i++) {
          LOG.debug(ARP[i] + " ");
          prefSum += ARP[i];
          // aggregate[i] = ARP[i];
        }
        if (prefSum == 0) {
          LOG.debug("Well ARP is 0 because Preference chk made it so, GO BACK TO AR !!!");
          System.arraycopy(contentResult, 0, aggregate, 0, contentResult.length); // forward aggregate
        } else if ((prefSum > 1) && (prefSum != 0)) {
          LOG.debug("now we got multiple preference based recommendations, forwarding");
          System.arraycopy(ARP, 0, aggregate, 0, ARP.length);
        } else {
          LOG.debug("after Preference chk left with only 1 recommendation, forwarding");
          System.arraycopy(ARP, 0, aggregate, 0, ARP.length);
        }
      } else
        LOG.debug("we have only one alternative rec, so forward that to Explanation Generator");
    }
    // Alternative Rec code here
    else {
      LOG.debug("Recommendation is Fine as per the current context; so Forward to Explanation Generator");
      // Forward recommendation to explanation generator
      originalRec[index] = 1;
      System.arraycopy(originalRec, 0, aggregate, 0, originalRec.length);
    }
    return (aggregate);
  }

  private static int[] evalMultiRecPreferences(int[] AR, String userid,String receivedContext) throws Exception {
    int[] ARP = PreferenceTesting.mainPrefTest(AR, userid, receivedContext);
    int[] prefAggregate = new int[AR.length];
    for (int i = 0; i < AR.length; i++) {
      if ((AR[i] == 1) && (ARP[i] == 1))
        prefAggregate[i] = 1;
      else
        prefAggregate[i] = 0;
    }
    return (prefAggregate);
  }

  @SuppressWarnings("unchecked")
  private static int[] multiRecCriticalContext(String context_string) throws Exception {

    WeatherMapper weatherMapper = new WeatherMapper();
    DisableMapper disableMapper = new DisableMapper();

    mapWeatherRec = weatherMapper.weatherMapper();
    mapDisableRec = disableMapper.disableMapper();
    String context[] = context_string.split(",");

    char[] weather = mapWeatherRec.get(context[2]).replaceAll(",", "").toCharArray();
    char[] disable = mapDisableRec.get(context[4]).replaceAll(",", "").toCharArray();
    // disability and weather(rainy)
    int ccSum = 0;
    int[] result = new int[disable.length];
    boolean weatherRainy = context_string.contains("rainy");
    // CONTEXTUAL MATRIX
    for (int i = 0; i < disable.length; i++)
      if (weatherRainy) {
        // LOG.debugln("Rainy weather flag on");
        if ((weather[i] == '1') && (disable[i] == '1'))
          result[i] = 1;
        else
          result[i] = 0;
      } else {        
        result[i] = Character.getNumericValue(disable[i]);        
      }
    if (weatherRainy) {
      LOG.debug("Critical Context array for weather=rainy when CC vector ->  0");
      for (int i = 0; i < disable.length; i++) {
        ccSum += result[i];
        LOG.debug(result[i] + " ");
      }
    }
    int ccTemp;
    if (ccSum == 0) {
      // System.arraycopy( disable, 0, result, 0, disable.length );
      LOG.debug("Critical Context array for diability when CC vector is 0");
      for (int i = 0; i < disable.length; i++) {
        ccTemp = Character.getNumericValue(disable[i]);
        result[i] = ccTemp;
        LOG.debug(result[i] + " ");
      }
    }
    return (result);

  }
}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/framework/recbuilder/UnsupportedTypeException.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.framework.recbuilder;

/**
 * UnsupportedTypeException
 * <p>
 * This class handles all sort of exceptions that occurs due to unsupported type (data types not supported by this 
 * application) of parameters or operators
 * 
 * @author Sadiq
 * @version 2.5
 * @since july 2014
 *
 */
public class UnsupportedTypeException extends Exception {
  
  private static final long serialVersionUID = -8522054585057940498L;
  
  public UnsupportedTypeException() { 
    super(); 
  }
  public UnsupportedTypeException(String message) { 
    super(message); 
  }
  public UnsupportedTypeException(String message, Throwable cause) { 
    super(message, cause); 
  }
  public UnsupportedTypeException(Throwable cause) { 
    super(cause); 
  }
  
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/MachineLearningTools/featureextraction/KincetARFeatureExtraction4.java<|end_filename|>
/*
Copyright [2016] [Thien]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.MachineLearningTools.featureextraction;

import java.util.ArrayList;
import java.util.List;

public class KincetARFeatureExtraction4 {
	KincetARFeatureExtraction kf = new KincetARFeatureExtraction();
	
	double inputs[][];
	double mat[][] = new double[30][140];
	
	
	/**
	 * set input data to extract features for kinect activity recognition
	 * @param inputs input data to set
	 */
	public void setInputData(double[][] inputs) {
		this.inputs = inputs;
	}
	
	
	/**
	 * calculate features. This function must be called after calling setInputData()
	 */
	public void calcFeatures(){
		
		for(int i = 0; i<inputs.length; i++){
			kf.setInputData(inputs[i]);
			double[] dd = kf.extractDistanceFeature();
			double[] aa = kf.extractAngleFeature();
			for(int j = 0; j<dd.length; j++){
				mat[i][j] = dd[j];
			}
			for(int j = 0; j<dd.length; j++){
				mat[i][j+aa.length] = aa[j];
			}
		}
	}
	
	/**
	 * calculate mean of kinect data. This function must be called after setInputData()
	 * @return mean calculated mean of kinect data
	 */
	private double[] calcMean(){
		double[] ret = new double[mat[0].length*2];
		int size = mat.length;
		for(int i = 0; i<mat[0].length; i++){
			double summ = 0;
			for(int j = 0; j<mat.length; j++){
				summ += mat[j][i];
			}
			ret[i] = summ/size;
		}
		
		for(int i = 0; i<mat[0].length; i++){
			double sqSumm = 0;
			for(int j = 0; j<mat.length; j++){
				sqSumm += (mat[j][i]-ret[i])*(mat[j][i]-ret[i])/(size-1);
			}
			
			ret[mat[0].length+i] = Math.sqrt(sqSumm);
		}
		
		return ret;
	}
	
	/**
	 * extract features. this function must be called after calling setInputData() function.
	 * @return features for kinect activity recognition
	 */
	public double[] extractFeatures() {
		// Extract features for each frame
		calcFeatures();
		return calcMean();
	}
	
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/HLCBuilder/HLCBuilder.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.HLCBuilder;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.apache.log4j.Logger;
import java.util.concurrent.ExecutorService;
import mm.icl.hlc.ContextOntologyManager.ContextOntologyManager;
import mm.icl.hlc.HLCNotifier.HLCNotifier;
import mm.icl.hlc.HLCReasoner.HLCReasoner;
import mm.icl.utils.FileUtil;
/**
 * HLCBuilder: HLC Builder which aligns concurrent
 * low-level contexts of the same user.
 * 
 * @author Nailbrainz
 * @version 2.5
 * @since 2015-11-06
 */
public class HLCBuilder {
	private static Logger logger = Logger.getLogger(HLCBuilder.class);
    ContextInstantiator inst;
    ContextSynchronizer sync;
    HLCReasoner r;
	HLCNotifier n;
	CxtSyncCounter counter;
    public HLCBuilder(ContextOntologyManager contextMng, ExecutorService es){
    	inst = new ContextInstantiator(contextMng.getContextOntology());
		r = new HLCReasoner(contextMng.getInferredContextOntology());
		n = new HLCNotifier(contextMng.getContextOntology());
		sync = new ContextSynchronizer(contextMng.getContextOntology(), inst, r, n, es);
		counter = new CxtSyncCounter(3);
    }
    public CxtSyncCounter getCounterRunnable(){
    	return counter;
    }
    class CxtSyncCounter implements Runnable {
		int windowSize;
		public CxtSyncCounter(int windowSize){
			this.windowSize = windowSize;
		}
		@Override
		public void run() {
			synchronized(this){
				Calendar windowStart, windowEnd;
				windowStart = Calendar.getInstance();
				int delay = 17;
				windowStart.add(Calendar.SECOND, -(delay));
				while(true){
					try {
						wait(windowSize*1000);
						windowEnd = Calendar.getInstance();
						windowEnd.add(Calendar.SECOND, -(delay));
						logger.info("Synchronizing for window (" + windowStart.get(Calendar.SECOND) + ":" +windowStart.get(Calendar.MILLISECOND) + ", " + windowEnd.get(Calendar.SECOND) + ":" +windowEnd.get(Calendar.MILLISECOND) + ")");
						logger.info("Synchronizing for window (" + windowStart.getTime() + ", " + windowEnd.getTime() + ")");
						sync.synchronizeTest(windowStart, windowEnd, r, n);
						windowStart = windowEnd;
					} catch (InterruptedException e) {
						logger.error("Error while Processing HLCBuilder.  Message: " + e.getMessage());
						e.printStackTrace();
					}
				}
			}
		}
    }
}

<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/ic/dataadapter/UserRecognizedActivityAccumulateAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.ic.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.ic.UserRecognizedActivityAccumulate;

/** 
 * This is UserRecognizedActivityAccumulateAdapter class which implements the Data Access Interface for CRUD operations
 * @author <NAME>
 */
public class UserRecognizedActivityAccumulateAdapter implements DataAccessInterface {

    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(UserRecognizedActivityAccumulateAdapter.class);
    public UserRecognizedActivityAccumulateAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving UserRecognizedActivityAccumulate. 
     * @param objUserRecognizedActivityAccumulate
     * @return List of String
     */
    @Override
    public List<String> Save(Object objUserRecognizedActivityAccumulate) {
        
        UserRecognizedActivityAccumulate objInnerUserRecognizedActivityAccumulate = new UserRecognizedActivityAccumulate();
        objInnerUserRecognizedActivityAccumulate =  (UserRecognizedActivityAccumulate) objUserRecognizedActivityAccumulate;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

             CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_UserRecognizedActivityAccumulate(?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserID", objInnerUserRecognizedActivityAccumulate.getUserId());
            objCallableStatement.setInt("ActivityID", objInnerUserRecognizedActivityAccumulate.getActivityId());
            if(objInnerUserRecognizedActivityAccumulate.getActivityDate() != null)
            {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
                Date dtActivityDate = sdf.parse(objInnerUserRecognizedActivityAccumulate.getActivityDate());
                Timestamp tsActivityDate = new Timestamp(dtActivityDate.getYear(),dtActivityDate.getMonth(), dtActivityDate.getDate(), dtActivityDate.getHours(), dtActivityDate.getMinutes(),dtActivityDate.getSeconds(),0);
                objCallableStatement.setTimestamp("ActivityDate", tsActivityDate);
            }
            
            objCallableStatement.setLong("Duration", objInnerUserRecognizedActivityAccumulate.getDuration());
                                               
            objCallableStatement.registerOutParameter("UserRecognizedActivityAccumulateID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intUserRecognizedActivityAccumulateID = objCallableStatement.getLong("UserRecognizedActivityAccumulateID");
            objDbResponse.add(String.valueOf(intUserRecognizedActivityAccumulateID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("User Recognized Activity Accumulate saved successfully, User Details="+objUserRecognizedActivityAccumulate);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding User Recognized Activity Accumulate");
        	objDbResponse.add("Error in adding User Recognized Activity Accumulate");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for updating UserRecognizedActivityAccumulate.
     * @param objUserRecognizedActivityAccumulate
     * @return List of String 
     */
    @Override
    public List<String> Update(Object objUserRecognizedActivityAccumulate) {
        
        UserRecognizedActivityAccumulate objInnerUserRecognizedActivityAccumulate = new UserRecognizedActivityAccumulate();
        objInnerUserRecognizedActivityAccumulate =  (UserRecognizedActivityAccumulate) objUserRecognizedActivityAccumulate;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

             CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_UserRecognizedActivityAccumulate(?, ?, ?, ?, ?)}");
            objCallableStatement.setLong("UserRecognizedActivityAccumulateID", objInnerUserRecognizedActivityAccumulate.getUserRecognizedActivityAccumulateID());
            objCallableStatement.setLong("UserID", objInnerUserRecognizedActivityAccumulate.getUserId());
            objCallableStatement.setInt("ActivityID", objInnerUserRecognizedActivityAccumulate.getActivityId());
            if(objInnerUserRecognizedActivityAccumulate.getActivityDate() != null)
            {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
                Date dtActivityDate = sdf.parse(objInnerUserRecognizedActivityAccumulate.getActivityDate());
                Timestamp tsActivityDate = new Timestamp(dtActivityDate.getYear(),dtActivityDate.getMonth(), dtActivityDate.getDate(), dtActivityDate.getHours(), dtActivityDate.getMinutes(),dtActivityDate.getSeconds(),0);
                objCallableStatement.setTimestamp("ActivityDate", tsActivityDate);
            }
            
            objCallableStatement.setLong("Duration", objInnerUserRecognizedActivityAccumulate.getDuration());
            
            objCallableStatement.execute();
            
            Long intUserRecognizedActivityAccumulateID = objInnerUserRecognizedActivityAccumulate.getUserRecognizedActivityAccumulateID();
            objDbResponse.add(String.valueOf(intUserRecognizedActivityAccumulateID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Recognized Activity Accumulate updated successfully, User Details="+objUserRecognizedActivityAccumulate);
        }
        catch (Exception e)
        {
        	logger.info("Error in updating Recognized Activity Accumulate");
        	objDbResponse.add("Error in updating Recognized Activity Accumulate");
        } 
        return objDbResponse;
        
    }

    /**
     * This is implementation function for retrieving UserRecognizedActivityAccumulate. 
     * @param objUserRecognizedActivityAccumulate
     * @return List of RetriveUserRecognizedActivityAccumulate
     */
    @Override
    public List<UserRecognizedActivityAccumulate> RetriveData(Object objUserRecognizedActivityAccumulate) {
        UserRecognizedActivityAccumulate objOuterUserRecognizedActivityAccumulate = new UserRecognizedActivityAccumulate();
        List<UserRecognizedActivityAccumulate> objListInnerUserRecognizedActivityAccumulate = new ArrayList<UserRecognizedActivityAccumulate>();
        objOuterUserRecognizedActivityAccumulate =  (UserRecognizedActivityAccumulate) objUserRecognizedActivityAccumulate;
        
        try
        {
            CallableStatement objCallableStatement = null;
            if(objOuterUserRecognizedActivityAccumulate.getRequestType() == "UserDateRange")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UserRecognizedActivityAccumulateByUserIDDateRange(?, ?, ?)}");
                objCallableStatement.setLong("UserID", objOuterUserRecognizedActivityAccumulate.getUserId());
                
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
                if(objOuterUserRecognizedActivityAccumulate.getStartTime()!= null)
                {
                    Date dtStartDate = sdf.parse(objOuterUserRecognizedActivityAccumulate.getStartTime());
                    Timestamp tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);
                    objCallableStatement.setTimestamp("StartDate", tsStartDate);
                }
                if(objOuterUserRecognizedActivityAccumulate.getEndTime()!= null)
                {
                    Date dtEndDate = sdf.parse(objOuterUserRecognizedActivityAccumulate.getEndTime());
                    Timestamp tsEndDate = new Timestamp(dtEndDate.getYear(),dtEndDate.getMonth(), dtEndDate.getDate(), dtEndDate.getHours(), dtEndDate.getMinutes(),dtEndDate.getSeconds(),0);
                    objCallableStatement.setTimestamp("EndDate", tsEndDate);
                }
            }
            else if(objOuterUserRecognizedActivityAccumulate.getRequestType() == "UserOneDate")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UserRecognizedActivityAccumulateByUserIDOneDate(?, ?)}");
                objCallableStatement.setLong("UserID", objOuterUserRecognizedActivityAccumulate.getUserId());
                
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
                if(objOuterUserRecognizedActivityAccumulate.getActivityDate()!= null)
                {
                    Date dtActivityDate = sdf.parse(objOuterUserRecognizedActivityAccumulate.getActivityDate());
                    Timestamp tsActivityDate = new Timestamp(dtActivityDate.getYear(),dtActivityDate.getMonth(), dtActivityDate.getDate(), dtActivityDate.getHours(), dtActivityDate.getMinutes(),dtActivityDate.getSeconds(),0);
                    objCallableStatement.setTimestamp("ActivityDate", tsActivityDate);
                }
            }
            else if(objOuterUserRecognizedActivityAccumulate.getRequestType() == "ActivitiesDateRange")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UserRecognizedActivityAccumulateByActivityIDs(?, ?, ?)}");
                objCallableStatement.setString("ActivityIDs", objOuterUserRecognizedActivityAccumulate.getActivityIDs());
                
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
                if(objOuterUserRecognizedActivityAccumulate.getStartTime()!= null)
                {
                    Date dtStartDate = sdf.parse(objOuterUserRecognizedActivityAccumulate.getStartTime());
                    Timestamp tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);
                    objCallableStatement.setTimestamp("StartDate", tsStartDate);
                }
                if(objOuterUserRecognizedActivityAccumulate.getEndTime()!= null)
                {
                    Date dtEndDate = sdf.parse(objOuterUserRecognizedActivityAccumulate.getEndTime());
                    Timestamp tsEndDate = new Timestamp(dtEndDate.getYear(),dtEndDate.getMonth(), dtEndDate.getDate(), dtEndDate.getHours(), dtEndDate.getMinutes(),dtEndDate.getSeconds(),0);
                    objCallableStatement.setTimestamp("EndDate", tsEndDate);
                }
            }
            
            ResultSet objResultSet = objCallableStatement.executeQuery();
            while(objResultSet.next())
            {
                UserRecognizedActivityAccumulate objInnerUserRecognizedActivityAccumulate = new UserRecognizedActivityAccumulate();
                objInnerUserRecognizedActivityAccumulate.setUserRecognizedActivityAccumulateID(objResultSet.getLong("UserRecognizedActivityAccumulateID"));
                objInnerUserRecognizedActivityAccumulate.setUserId(objResultSet.getLong("UserID"));
                objInnerUserRecognizedActivityAccumulate.setActivityId(objResultSet.getInt("ActivityID"));
                
                if(objResultSet.getTimestamp("ActivityDate") != null)
                {
                    Timestamp tsActivityDate = objResultSet.getTimestamp("ActivityDate");
                    objInnerUserRecognizedActivityAccumulate.setActivityDate(tsActivityDate.toString());
                }
                objInnerUserRecognizedActivityAccumulate.setDuration(objResultSet.getInt("Duration"));
                objInnerUserRecognizedActivityAccumulate.setActivityDescription(objResultSet.getString("ActivityDescription"));
               
                objListInnerUserRecognizedActivityAccumulate.add(objInnerUserRecognizedActivityAccumulate);
            }
            objConn.close();
            logger.info("Recognized Activity Accumulate are loaded successfully.");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading Recognized Activity Accumulate");
        }   
        return objListInnerUserRecognizedActivityAccumulate;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/datamodel/Disibilities.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.datamodel;

import java.io.Serializable;

/**
 * @version MM v2.5
 * @author Afzal
 *
 */
public class Disibilities implements Serializable{
  
  private long id;
  private String requestType;
  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public String getRequestType() {
    return requestType;
  }

  public void setRequestType(String requestType) {
    this.requestType = requestType;
  }

  private String disabilityDescription;
  private int disabilityID;
  private String statusDescription;
  private int statusID;
  private int userDisabilityID;
  private int userID;

  /**
   * @return the disabilityDescription
   */
  public String getDisabilityDescription() {
    return disabilityDescription;
  }

  /**
   * @param disabilityDescription
   *          the disabilityDescription to set
   */
  public void setDisabilityDescription(String disabilityDescription) {
    this.disabilityDescription = disabilityDescription;
  }

  /**
   * @return the disabilityID
   */
  public int getDisabilityID() {
    return disabilityID;
  }

  /**
   * @param disabilityID
   *          the disabilityID to set
   */
  public void setDisabilityID(int disabilityID) {
    this.disabilityID = disabilityID;
  }

  /**
   * @return the statusDescription
   */
  public String getStatusDescription() {
    return statusDescription;
  }

  /**
   * @param statusDescription
   *          the statusDescription to set
   */
  public void setStatusDescription(String statusDescription) {
    this.statusDescription = statusDescription;
  }

  /**
   * @return the statusID
   */
  public int getStatusID() {
    return statusID;
  }

  /**
   * @param statusID
   *          the statusID to set
   */
  public void setStatusID(int statusID) {
    this.statusID = statusID;
  }

  /**
   * @return the userDisabilityID
   */
  public int getUserDisabilityID() {
    return userDisabilityID;
  }

  /**
   * @param userDisabilityID
   *          the userDisabilityID to set
   */
  public void setUserDisabilityID(int userDisabilityID) {
    this.userDisabilityID = userDisabilityID;
  }

  /**
   * @return the userID
   */
  public int getUserID() {
    return userID;
  }

  /**
   * @param userID
   *          the userID to set
   */
  public void setUserID(int userID) {
    this.userID = userID;
  }

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/ic/UserAccelerometerData.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.ic;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author Taqdir
 */
@Entity
public class UserAccelerometerData implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private Long userAccelerometerDataId;
    private Long userDeviceId;
    private List<Float> xCoordinate = new ArrayList<Float>();
    private List<Float> yCoordinate = new ArrayList<Float>();
    private List<Float> zCoordinate = new ArrayList<Float>();
    //private GregorianCalendar timeStamp; updated
    private String timeStamp;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof UserAccelerometerData)) {
            return false;
        }
        UserAccelerometerData other = (UserAccelerometerData) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.ic.UserAccelerometerData[ id=" + id + " ]";
    }

    /**
     * @return the userAccelerometerDataId
     */
    public Long getUserAccelerometerDataId() {
        return userAccelerometerDataId;
    }

    /**
     * @param userAccelerometerDataId the userAccelerometerDataId to set
     */
    public void setUserAccelerometerDataId(Long userAccelerometerDataId) {
        this.userAccelerometerDataId = userAccelerometerDataId;
    }

    /**
     * @return the userDeviceId
     */
    public Long getUserDeviceId() {
        return userDeviceId;
    }

    /**
     * @param userDeviceId the userDeviceId to set
     */
    public void setUserDeviceId(Long userDeviceId) {
        this.userDeviceId = userDeviceId;
    }

    

    /**
     * @return the timeStamp
     */ 
    // Updated one.
    public String getTimeStamp() {
        return timeStamp;
    }

    /**
     * @param timeStamp the timeStamp to set
     */
  /*  public void setTimeStamp(GregorianCalendar timeStamp) {  // updated
        this.timeStamp = timeStamp;
    }*/
     public void setTimeStamp(String timeStamp) {
        this.timeStamp = timeStamp;
    }

    /**
     * @return the xCoordinate
     */
    public List<Float> getxCoordinate() {
        return xCoordinate;
    }

    /**
     * @param xCoordinate the xCoordinate to set
     */
    public void setxCoordinate(List<Float> xCoordinate) {
        this.xCoordinate = xCoordinate;
    }

    /**
     * @return the yCoordinate
     */
    public List<Float> getyCoordinate() {
        return yCoordinate;
    }

    /**
     * @param yCoordinate the yCoordinate to set
     */
    public void setyCoordinate(List<Float> yCoordinate) {
        this.yCoordinate = yCoordinate;
    }

    /**
     * @return the zCoordinate
     */
    public List<Float> getzCoordinate() {
        return zCoordinate;
    }

    /**
     * @param zCoordinate the zCoordinate to set
     */
    public void setzCoordinate(List<Float> zCoordinate) {
        this.zCoordinate = zCoordinate;
    }
    
}


<|start_filename|>data-curation-layer/data-persistence/DataManufacture.js<|end_filename|>
/**
 * @author <NAME>
 * @since 2016.11.21
 * @version 0.1
 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at

 *   http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var bodyParser  =require('body-parser');

/**
 * @description Sorting a data object
 * @description Extract data in object using by index 
 * @module dmf(DataManufacture) 
 * @param {JSON} req - The JSON format data recieved by Syncronization module
 * @return {object} result - This module returns object which has 3 factor{
 * obj[index[0]] => contentBody
 * obj[index[1]] => timestamp
 * obj[index[2]] => userID
 * }
 */
exports.dmf = function(req){ 


var index = []; //Array for index
var obj = new Object(); //Create a object
obj = req.body;
for(var x in obj)
{
	index.push(x);
}

index.sort(function (a, b) {    
   return a == b ? 0 : (a > b ? 1 : -1); 
}); 


var result = [];
result[0] = obj[index[2]];
result[1] = obj[index[1]];
result[2] = obj[index[0]]

return result;
};



<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/dc/UserFacilities.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.dc;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author Taqdir
 */
@Entity
public class UserFacilities implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    
    private Long userFacilityId;
    private Long userId; 
    private int facilityId;
    

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof UserFacilities)) {
            return false;
        }
        UserFacilities other = (UserFacilities) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.dc.UserFacilities[ id=" + id + " ]";
    }

    /**
     * @return the userFacilityId
     */
    public long getUserFacilityId() {
        return userFacilityId;
    }

    /**
     * @param userFacilityId the userFacilityId to set
     */
    public void setUserFacilityId(long userFacilityId) {
        this.userFacilityId = userFacilityId;
    }

    /**
     * @return the userId
     */
    public Long getUserId() {
        return userId;
    }

    /**
     * @param userId the userId to set
     */
    public void setUserId(Long userId) {
        this.userId = userId;
    }

    /**
     * @return the facilityId
     */
    public int getFacilityId() {
        return facilityId;
    }

    /**
     * @param facilityId the facilityId to set
     */
    public void setFacilityId(int facilityId) {
        this.facilityId = facilityId;
    }
    
}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/framework/RecInterpreter/RecInterpreter.java<|end_filename|>
/* Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.scl.framework.RecInterpreter;

import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.uclab.scl.interpreterdatamodel.FiredRule;
import org.uclab.scl.interpreterdatamodel.InterpretationIngredients;
import org.uclab.scl.framework.AbstractInterpreterPacket;
import org.uclab.scl.framework.AbstractRecInterpreter;
import org.uclab.scl.framework.RecInterpreter.Explanation.ExplanationBuilder;

public class RecInterpreter extends AbstractRecInterpreter {
  private static Logger LOG = LogManager.getRootLogger();

  /**
   * This function provides a mechanism to channel the control to the required  logic based on the nature of recommendation received 
   * e.g. in case of food based recommendation this function will transfer control to "FoodRecInterpretation" component 
   */
  @Override
  public void interpretRecommendation(AbstractInterpreterPacket interpreterPacket) {
    InterpretationIngredients interpretationIngredients = (InterpretationIngredients) interpreterPacket.getRecommendationInput();
    List<FiredRule> rules = interpretationIngredients.getFiredRule();
    try {
      if (rules.get(0).getConclusionList().get(0).getConclusionKey().equalsIgnoreCase("Food")) {
        (new FoodRecInterpretations()).getFoodRecommendation(interpreterPacket);
      } else {
    	  PARecInterpretations physicalInterpretation = new PARecInterpretations();
    	  physicalInterpretation.setRecExpalanation(new ExplanationBuilder());
    	  physicalInterpretation.buildPARecInterpretations(interpreterPacket);
      }
    }
    catch (Exception exp) {
      LOG.error(exp.getMessage());
    }
  }
}


<|start_filename|>knowledge-curation-layer/DDKAT/src/main/java/org/uclab/mm/kcl/ddkat/datapreprocessor/FeaturesSelector.java<|end_filename|>
/**
 * Copyright [2017] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.mm.kcl.ddkat.datapreprocessor;

import java.io.File;
import java.util.ArrayList;

import weka.filters.Filter;
import weka.filters.supervised.attribute.AttributeSelection;
import weka.attributeSelection.CfsSubsetEval;
import weka.attributeSelection.GreedyStepwise;
import weka.core.Instances;
import weka.core.converters.ArffSaver;
import weka.core.converters.CSVLoader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// TODO: Auto-generated Javadoc
/**
 * This class filters the data to address the issue of the curse of dimensionality and then stores the filtered data.
 */
public class FeaturesSelector {
	
	/** The confirmation message. */
	private ArrayList<String> confirmationMessage;
	
	/** The Constant log. */
	private static final Logger log = LoggerFactory.getLogger(FeaturesSelector.class);
	
	/** base directory to store resource data files */
	private static final String BASE_DIR = System.getProperty("user.home") + "/DDKAT/resources/";
		
	/**
	 * Constructor to instantiate a new FeaturesSelector object.
	 *
	 * @throws Exception the exception
	 */
	public FeaturesSelector() throws Exception {
		
		filterData();
	}
	
	
	/**
	 * Method to filter the input data using GreedyStepwise approach.
	 *
	 * @throws Exception the exception
	 */
	public void filterData() throws Exception {
		
		this.confirmationMessage = new ArrayList<String>();
		
		Instances inputData, outputData;
		String inputFile = BASE_DIR + "OriginalDataSet.csv";
	
		// load CSV file
		CSVLoader fileLoader=new CSVLoader();
		fileLoader.setSource(new File(inputFile));
	    inputData = fileLoader.getDataSet();
		
	    inputData.setClassIndex(inputData.numAttributes() - 1); 
		AttributeSelection filter = new AttributeSelection();
        CfsSubsetEval eval = new CfsSubsetEval();
        GreedyStepwise search = new GreedyStepwise();
        search.setSearchBackwards(true);
        filter.setEvaluator(eval);
        filter.setSearch(search);
        filter.setInputFormat(inputData);
        outputData = Filter.useFilter(inputData, filter);
          
        int indices = outputData.numAttributes();
        String selectedAttributesString="";
        for (int i=0; i < indices; i++) {
            selectedAttributesString += "\n"+outputData.attribute(i).toString() +", ";
          }
        selectedAttributesString = selectedAttributesString.substring(0, selectedAttributesString.length()-2);
        
        saveFilteredData(inputFile, outputData);
        
 	}
	
	/**
	 * Method to store the filtered data.
	 *
	 * @param filePath the file path
	 * @param outputData the output data
	 * @throws Exception the exception
	 */
	public void saveFilteredData(String filePath, Instances outputData) throws Exception {
        
        // save ARFF file
        String outputFile = filePath.substring(0,filePath.lastIndexOf('/'));
        outputFile = outputFile + "/ProcessedDataSet.arff";
        log.info("Output file : "+outputFile);

        ArffSaver saver = new ArffSaver();
        saver.setInstances(outputData);
        saver.setFile(new File(outputFile));
        saver.writeBatch();
                 
        String confirmationMessageStr = "Data is successfully filtered and is stored at : "+outputFile;
        log.info(confirmationMessageStr);
        this.confirmationMessage.add(confirmationMessageStr); 
	}
	
	/**
	 * Method to get the confirmation message of data filtration.
	 *
	 * @return the confirmation message
	 */
	public ArrayList<String> getConfirmationMessage() {
		return confirmationMessage;
	}

	/**
	 * Method to set the confirmation message of data filtration.
	 *
	 * @param confirmationMessage the new confirmation message
	 */
	public void setConfirmationMessage(ArrayList<String> confirmationMessage) {
		this.confirmationMessage = confirmationMessage;
	}

}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/config/RecognizerType.java<|end_filename|>
/*
Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.mm.icl.llc.config;

import org.uclab.mm.icl.llc.AER.vui.AudioEmotionRecognizerV;
import org.uclab.mm.icl.llc.LLCRecognizer.AudioEmotionRecognizer;
import org.uclab.mm.icl.llc.LLCRecognizer.GPSLocationRecognizer;
import org.uclab.mm.icl.llc.LLCRecognizer.InertialActivityRecognizer;
import org.uclab.mm.icl.llc.LLCRecognizer.LLCRecognizer;
import org.uclab.mm.icl.llc.LLCRecognizer.FoodRecognizer;
import org.uclab.mm.icl.llc.LLCRecognizer.VideoActivityRecognizer;
import org.uclab.mm.icl.llc.MachineLearningTools.ExtClassification;
import org.uclab.mm.icl.utils.FileUtil;
import weka.classifiers.functions.SMO;
import weka.core.SelectedTag;



/**
 * Enum for the different recognizer type for different context. Consumes the Datatype and generates ContextType data
 * @author Nailbrainz
 *
 */
public enum RecognizerType {
	SER(0), ER(1), IAR(2), VAR(3), LR(4), FR(5);
	
	
    private int value;
    
    /**
     * Unique constructor of RecognizerType.
     * @param _value
     */
    private RecognizerType(int _value){
        value = _value;
    }
  //, Food(5), EmoPic(6);

/*public static String[] actLabels = {"Stretching","Standing","Sitting","Sweeping"
			,"Walking","Running","ClimbingStairs","Eating","LyingDown","Jumping", "Cycling", "NoActivity"};*/
   
    /**
     * Returns the context which each recognizer produces
     * @return ContextType enum, context which each recognizer produces
     */
    public ContextType getContext(){
    	RecognizerType rec = this.values()[value];
        switch(rec){
	    	case SER:
	    		return ContextType.Emotion;
	    	case ER:
	    		return ContextType.Emotion;
	    	case IAR:
	    		return ContextType.Activity;
	    	case VAR:
	    		return ContextType.Activity;
	    	case LR:
	    		return ContextType.Location;
	    	case FR:
	    		return ContextType.Food;
	    }
    	return null;
    }
    
    /**
     * Returns the corresponding recognizer
     * @param rec recognizer type to return
     * @param userID user ID to set
     * @return instance of the corresponding recognizer
     */
    public LLCRecognizer getRecognizer(long userID){
    	
    	RecognizerType rec = this.values()[value];
        switch(rec){
        case SER:
        	String[] labels = { "Anger", "Happiness", "Sadness"};
        	String path = FileUtil.getRootPath()+"/training/modeldataV2.7.txt";
        	SMO svm = new SMO(); // Define Classifier with Weka
    		try {
    			svm.setOptions(weka.core.Utils
    					.splitOptions("-C 1.0 -L 0.0010 -P 1.0E-12 -N 1 -V -1 -W 1 -K \"weka.classifiers.functions.supportVector.RBFKernel -C 250007 -G 0.01\""));
    			svm.setFilterType(new SelectedTag(SMO.FILTER_STANDARDIZE, SMO.TAGS_FILTER));
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		ExtClassification classifier = new ExtClassification(path, 78*2, labels, svm);
    		AudioEmotionRecognizer aer = new AudioEmotionRecognizer(classifier, path, userID);
        	
        	return aer;
        case ER:
        	return new AudioEmotionRecognizerV(userID);
        case IAR:
        	return new InertialActivityRecognizer(userID);
        case VAR:
        	return new VideoActivityRecognizer(userID);
        case LR:
        	//get user loc coord / label with userID by restful service
        	return new GPSLocationRecognizer(userID);
        case FR:
        	return new FoodRecognizer(userID);
        }
        return null;
    }
    
    
    
   
  
    /**
     * Returns the boolean value which indicates whether the current recognizer is running or not
     * @return boolean value which indicates whether the current recognizer is running or not
     */
    public boolean isOn(){
    	return  ICLConfig.isRecogOn.get(value);
    }
    

    /**
     * Returns the string which best describes the current recognizer type
     */
    public String toString(){
    	return this.name();
    }
    
    /**
     * Returns the value for the current context, which is configed inside the enum
     * @return integer value of the current context
     */
    public int getValue(){
        return value;
    }
    
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/llm/FoodItem.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.llm;

/**
 *
 * @author Rizvi
 */
public class FoodItem {
    
    private String FoodID;
    private String FoodCategory;
    private String FoodNutrientName;
    private String FoodName;

    /**
     * @return the FoodID
     */
    public String getFoodID() {
        return FoodID;
    }

    /**
     * @param FoodID the FoodID to set
     */
    public void setFoodID(String FoodID) {
        this.FoodID = FoodID;
    }

    /**
     * @return the FoodCategory
     */
    public String getFoodCategory() {
        return FoodCategory;
    }

    /**
     * @param FoodCategory the FoodCategory to set
     */
    public void setFoodCategory(String FoodCategory) {
        this.FoodCategory = FoodCategory;
    }

    /**
     * @return the FoodNutrientName
     */
    public String getFoodNutrientName() {
        return FoodNutrientName;
    }

    /**
     * @param FoodNutrientName the FoodNutrientName to set
     */
    public void setFoodNutrientName(String FoodNutrientName) {
        this.FoodNutrientName = FoodNutrientName;
    }

    /**
     * @return the FoodName
     */
    public String getFoodName() {
        return FoodName;
    }

    /**
     * @param FoodName the FoodName to set
     */
    public void setFoodName(String FoodName) {
        this.FoodName = FoodName;
    }
    
    
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sl/UserGPSDataVisulization.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author dcadmin
 */
@Entity
public class UserGPSDataVisulization implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private Long userGPSDataId;
    private Long userDeviceId;
   
    private Float latitude;
    private Float longitude;
    private Float speed;
    private String timeStampStart;
    private String timeStampEnd;
    private String timeStamp;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof UserGPSDataVisulization)) {
            return false;
        }
        UserGPSDataVisulization other = (UserGPSDataVisulization) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.sl.UserGPSDataVisulization[ id=" + id + " ]";
    }

    /**
     * @return the userGPSDataId
     */
    public Long getUserGPSDataId() {
        return userGPSDataId;
    }

    /**
     * @param userGPSDataId the userGPSDataId to set
     */
    public void setUserGPSDataId(Long userGPSDataId) {
        this.userGPSDataId = userGPSDataId;
    }

    /**
     * @return the userDeviceId
     */
    public Long getUserDeviceId() {
        return userDeviceId;
    }

    /**
     * @param userDeviceId the userDeviceId to set
     */
    public void setUserDeviceId(Long userDeviceId) {
        this.userDeviceId = userDeviceId;
    }

    /**
     * @return the latitude
     */
    public Float getLatitude() {
        return latitude;
    }

    /**
     * @param latitude the latitude to set
     */
    public void setLatitude(Float latitude) {
        this.latitude = latitude;
    }

    /**
     * @return the longitude
     */
    public Float getLongitude() {
        return longitude;
    }

    /**
     * @param longitude the longitude to set
     */
    public void setLongitude(Float longitude) {
        this.longitude = longitude;
    }

    /**
     * @return the speed
     */
    public Float getSpeed() {
        return speed;
    }

    /**
     * @param speed the speed to set
     */
    public void setSpeed(Float speed) {
        this.speed = speed;
    }

    /**
     * @return the timeStampStart
     */
    public String getTimeStampStart() {
        return timeStampStart;
    }

    /**
     * @param timeStampStart the timeStampStart to set
     */
    public void setTimeStampStart(String timeStampStart) {
        this.timeStampStart = timeStampStart;
    }

    /**
     * @return the timeStampEnd
     */
    public String getTimeStampEnd() {
        return timeStampEnd;
    }

    /**
     * @param timeStampEnd the timeStampEnd to set
     */
    public void setTimeStampEnd(String timeStampEnd) {
        this.timeStampEnd = timeStampEnd;
    }

    /**
     * @return the timeStamp
     */
    public String getTimeStamp() {
        return timeStamp;
    }

    /**
     * @param timeStamp the timeStamp to set
     */
    public void setTimeStamp(String timeStamp) {
        this.timeStamp = timeStamp;
    }

   
   
    
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/ic/UserPreferredLocation.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.ic;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author Taqdir
 */
@Entity
public class UserPreferredLocation implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private Long userPreferredLocationId;
    private Long userId;
    private Float latitude;
    private Float longitude;
    private String locationLabel;
    private String locationDescription;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof UserPreferredLocation)) {
            return false;
        }
        UserPreferredLocation other = (UserPreferredLocation) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.ic.UserPreferredLocation[ id=" + id + " ]";
    }

    /**
     * @return the userPreferredLocationId
     */
    public Long getUserPreferredLocationId() {
        return userPreferredLocationId;
    }

    /**
     * @param userPreferredLocationId the userPreferredLocationId to set
     */
    public void setUserPreferredLocationId(Long userPreferredLocationId) {
        this.userPreferredLocationId = userPreferredLocationId;
    }

    /**
     * @return the userId
     */
    public Long getUserId() {
        return userId;
    }

    /**
     * @param userId the userId to set
     */
    public void setUserId(Long userId) {
        this.userId = userId;
    }

    /**
     * @return the latitude
     */
    public Float getLatitude() {
        return latitude;
    }

    /**
     * @param latitude the latitude to set
     */
    public void setLatitude(Float latitude) {
        this.latitude = latitude;
    }

    /**
     * @return the longitude
     */
    public Float getLongitude() {
        return longitude;
    }

    /**
     * @param longitude the longitude to set
     */
    public void setLongitude(Float longitude) {
        this.longitude = longitude;
    }

    /**
     * @return the locationLabel
     */
    public String getLocationLabel() {
        return locationLabel;
    }

    /**
     * @param locationLabel the locationLabel to set
     */
    public void setLocationLabel(String locationLabel) {
        this.locationLabel = locationLabel;
    }

    /**
     * @return the locationDescription
     */
    public String getLocationDescription() {
        return locationDescription;
    }

    /**
     * @param locationDescription the locationDescription to set
     */
    public void setLocationDescription(String locationDescription) {
        this.locationDescription = locationDescription;
    }
    
}


<|start_filename|>knowledge-curation-layer/i-kat/src/main/java/org/uclab/mm/kcl/edkat/datamodel/User.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.kcl.edkat.datamodel;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.JoinColumn;


/**
 * Entity bean with JPA annotations
 * Hibernate provides JPA implementation
 * @author <NAME>
 *
 */

@Entity
@Table(name="tblUsers")
public class User {

	@Id
    @Column(name="UserID")
    @GeneratedValue(strategy=GenerationType.AUTO)
	private int UserID;
	
	@Column(name="UserName")
	private String userName;
	
	@Column(name="LoginID")
	private String loginID;
	
	@Column(name="Password")
	private String password;
	
	@Column(name="EmailAddress")
	private String emailAddress;
	
	@Column(name="DateOfBirth")
	private Date dateOfBirth;
	
	@Column(name="DesignationID")
	private Integer designationID;
	
	@Column(name="ActiveYNID")
	private Integer activeYNID;

	public int getUserID() {
		return UserID;
	}

	public void setUserID(int userID) {
		UserID = userID;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getLoginID() {
		return loginID;
	}

	public void setLoginID(String loginID) {
		this.loginID = loginID;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getEmailAddress() {
		return emailAddress;
	}

	public void setEmailAddress(String emailAddress) {
		this.emailAddress = emailAddress;
	}

	public Date getDateOfBirth() {
		return dateOfBirth;
	}

	public void setDateOfBirth(Date dateOfBirth) {
		this.dateOfBirth = dateOfBirth;
	}

	public Integer getDesignationID() {
		return designationID;
	}

	public void setDesignationID(Integer designationID) {
		this.designationID = designationID;
	}

	public Integer getActiveYNID() {
		return activeYNID;
	}

	public void setActiveYNID(Integer activeYNID) {
		this.activeYNID = activeYNID;
	}
	
	
	
	
	
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/ic/UserRecognizedHLC.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.ic;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author Taqdir
 */
public class UserRecognizedHLC implements Serializable {
     private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private Long userRecognizedHLCId;
    private Long userId;
    private String hLCLabel;
    private String startTime;
    private String endTime;
    private Long duration;

    private String requestType;
    
    /**
     * @return the userRecognizedHLCId
     */
    public Long getUserRecognizedHLCId() {
        return userRecognizedHLCId;
    }

    /**
     * @param userRecognizedHLCId the userRecognizedHLCId to set
     */
    public void setUserRecognizedHLCId(Long userRecognizedHLCId) {
        this.userRecognizedHLCId = userRecognizedHLCId;
    }

    /**
     * @return the userId
     */
    public Long getUserId() {
        return userId;
    }

    /**
     * @param userId the userId to set
     */
    public void setUserId(Long userId) {
        this.userId = userId;
    }

    /**
     * @return the startTime
     */
    public String getStartTime() {
        return startTime;
    }

    /**
     * @param startTime the startTime to set
     */
    public void setStartTime(String startTime) {
        this.startTime = startTime;
    }

    /**
     * @return the endTime
     */
    public String getEndTime() {
        return endTime;
    }

    /**
     * @param endTime the endTime to set
     */
    public void setEndTime(String endTime) {
        this.endTime = endTime;
    }

    /**
     * @return the duration
     */
    public Long getDuration() {
        return duration;
    }

    /**
     * @param duration the duration to set
     */
    public void setDuration(Long duration) {
        this.duration = duration;
    }

    /**
     * @return the id
     */
    public Long getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * @return the hLCLabel
     */
    public String gethLCLabel() {
        return hLCLabel;
    }

    /**
     * @param hLCLabel the hLCLabel to set
     */
    public void sethLCLabel(String hLCLabel) {
        this.hLCLabel = hLCLabel;
    }

    /**
     * @return the requestType
     */
    public String getRequestType() {
        return requestType;
    }

    /**
     * @param requestType the requestType to set
     */
    public void setRequestType(String requestType) {
        this.requestType = requestType;
    }
    
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/test/java/org/uclab/mm/datamodel/sc/dataadapter/testcases/RecommendationAdapterTest.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc.dataadapter.testcases;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.uclab.mm.datamodel.AbstractDataBridge;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.DatabaseStorage;
import org.uclab.mm.datamodel.sc.Recommendation;
import org.uclab.mm.datamodel.sc.dataadapter.RecommendationAdapter;


/**
 * This is a class for testing the insertion, fetching, and update of Recommendation
 * @author <NAME>
 *
 */
public class RecommendationAdapterTest {

	/**
	 * This is function for testing the insertion, fetching, and update of Recommendation 
	 */
	@Test
	public void test() {
		/* Preparing input object for insertion*/
		Recommendation objOuterRecommendation = new Recommendation();
		Recommendation objInnerRecommendation = new Recommendation();
		List<Recommendation> objListRecommendation = new  ArrayList<Recommendation>();
		
		objOuterRecommendation.setRecommendationIdentifier("A0001");
		objOuterRecommendation.setSituationID(22244L);
		objOuterRecommendation.setRecommendationDescription("testing for unit testing");
		objOuterRecommendation.setRecommendationTypeID(1);
		objOuterRecommendation.setConditionValue("condValue");
		objOuterRecommendation.setRecommendationLevelID(1);
		objOuterRecommendation.setRecommendationStatusID(1);
		objOuterRecommendation.setRecommendationDate("2016 12 12 01:30:01");
	
		/* Testing of insertion function*/
		 DataAccessInterface objDAInterface = new RecommendationAdapter();
         AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
         List<String> lstResponse = objADBridge.SaveRecommendation(objOuterRecommendation);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerRecommendation.setUserID(2L);
        	 objInnerRecommendation.setRequestType("ByUserOnly");
        	 DataAccessInterface objDAInterfaceRetrieval = new RecommendationAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListRecommendation = objADBridgeRetrieval.RetriveRecommendation(objInnerRecommendation);
        	 objInnerRecommendation = objListRecommendation.get(0);
         }
         
         assertEquals(objOuterRecommendation.getRecommendationDescription(), objInnerRecommendation.getRecommendationDescription());
         
         /* Testing of Update function*/
         objInnerRecommendation.setRecommendationDescription("testing for unit testing updated");
         objInnerRecommendation.setRecommendationDate("2016 12 12 01:30:01");
         DataAccessInterface objDAInterfaceUpdate = new RecommendationAdapter();
         AbstractDataBridge objADBridgeUpdate = new DatabaseStorage(objDAInterfaceUpdate);
         lstResponse = objADBridgeUpdate.UpdateRecommendation(objInnerRecommendation);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerRecommendation.setUserID(2L);
        	 objInnerRecommendation.setRequestType("ByUserOnly");
        	 DataAccessInterface objDAInterfaceRetrieval = new RecommendationAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListRecommendation = objADBridgeRetrieval.RetriveRecommendation(objInnerRecommendation);
        	 objInnerRecommendation = objListRecommendation.get(0);
         }
         
         assertEquals(objInnerRecommendation.getRecommendationDescription(), "testing for unit testing updated");
	}

}


<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/monitoring/NutritionMonitor.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */
package org.uclab.mm.dcl.llm.monitoring;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;
import java.sql.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import org.apache.log4j.Logger;
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.uclab.mm.dcl.llm.dataaccess.DBConnection;
import org.uclab.mm.dcl.llm.objectmodel.FoodLog;
import org.uclab.mm.dcl.llm.objectmodel.SituationConditions;
import org.uclab.mm.dcl.llm.objectmodel.SituationEvent;
import org.uclab.mm.dcl.llm.objectmodel.SituationLog;
import org.uclab.mm.dcl.llm.objectmodel.SituationNotification;

/**
 * This class is responsible to monitor the nutrition. It will not only monitor the nutrition but 
 * also perform all those actions which are required to share the monitored information with the 
 * wellness services. This class implements an interface of the monitoring strategy which has a declaration 
 * of monitoring functions. 
 * @author Rizvi
 */
public class NutritionMonitor implements MonitoringStrategy{


  String situationLogID = null;
  static org.apache.log4j.Logger log = Logger.getLogger(NutritionMonitor.class.getName());

  /**
   * 
   * @param dbConn
   * @param a
   * @throws SQLException 
   * This method is to keep the format of MonitoringStrategy interface.
   */
  public void doMonitor(Connection dbConn, String a) throws SQLException{

  }
/**
 * 
 * @param ObjFoodLog 
 * This method is used to monitor the quantity of food component in a a daytime period, if a particular ingredient cross 
 * daily recommended limit...it will intimate to wellness services by absorbing the service. It uses a stored procedure
 * which is used to perform calculation of nutrition of a particular user with in a day time limit (6:00 am to 23:59 pm).
 */
  public void doMonitor(FoodLog ObjFoodLog){
    int Result = 0;
    String ActLevel = null;
    int MapId = 0;
    int ConsumeFat = 0;
    int UserId = 0;
    RestServiceNotification objRestServiceNotification = null;
    Connection conn = null;
    int c = -1;
    java.sql.CallableStatement cstmt = null;
    try{
       conn = DBConnection.getDBConnection().getConnection();
      Long a = ObjFoodLog.getUserId();
      String s = ObjFoodLog.getFoodName();
      cstmt = conn.prepareCall("{call usp_NutiritionMonitorvdemo( " + a + "," + s + "," + "?,?,?,?,?)}");
      cstmt.setInt(1, 5);
      cstmt.registerOutParameter(1, java.sql.Types.INTEGER);
      cstmt.registerOutParameter(2, java.sql.Types.VARCHAR);
      cstmt.registerOutParameter(3, java.sql.Types.INTEGER);
      cstmt.registerOutParameter(4, java.sql.Types.INTEGER);
      cstmt.registerOutParameter(5, java.sql.Types.INTEGER);
      cstmt.execute();
      System.out.println("***************Local Testing****************");
      System.out.println(" @result: " + cstmt.getInt(1));
      System.out.println(" @ActStatus: " + cstmt.getString(2));
      System.out.println(" @madId: " + cstmt.getInt(3));
      System.out.println(" @ConsumeFat: " + cstmt.getInt(4));
      System.out.println(" @UserID : " + cstmt.getInt(5));
      System.out.println("*************** End Local Testing****************");
      Result = cstmt.getInt(1);
      ActLevel = cstmt.getString(2);
      MapId = cstmt.getInt(3);
      ConsumeFat = cstmt.getInt(4);
      UserId = cstmt.getInt(5);
      String stUserId = UserId + "";
      String stConsumeFat = ConsumeFat + "";
      String stMapId = MapId + "";
      if (cstmt.getInt(1) == 0){
        System.out.println(" No need to intimate : " + cstmt.getInt(1));
      } else if (cstmt.getInt(1) == 1){
        System.out.println(" Plz intimate the SCL for Recomendation" + cstmt.getInt(1));
        objRestServiceNotification = new RestServiceNotification();
        //communicate the information to the SCL
        //objRestServiceNotification.notifyToRestService(getNotificationMessage(stMapId, stUserId, stConsumeFat), "http://192.168.3.11:8080/SCLMiningMind2.5/webresources/SCLService/PushPARecommendation");
        System.out.println(" *******************************************");
      } else{
        System.out.println(" Sorry very wrong Information" + cstmt.getInt(1));
      }
      //situationLogID = AddFoodLog(ObjFoodLog);
    } catch(SQLException sqlException){
      sqlException.printStackTrace();
    } catch (Exception exp){
      StringWriter errors = new StringWriter();
      exp.printStackTrace(new PrintWriter(errors));
    }
    //return situationLogID;
  }
/**
 * 
 * @param ObjFoodLog
 * @return 
 * This method is used to log the food information, whenever user take food and want to log it for recording and logging.
 */
  protected String AddFoodLog(FoodLog ObjFoodLog){
    try{
      ClientConfig config = new DefaultClientConfig();
      config.getClasses().add(JacksonJsonProvider.class);      
      Client client = Client.create(config);
      final String baseURI = "http://192.168.3.11:8080/MMDataCurationRestfulService/webresources/InformationCuration/AddFoodLog";
      WebResource srv = client.resource(UriBuilder.fromUri(baseURI).build());
      ClientResponse serverResponse = srv.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, ObjFoodLog);
      situationLogID = serverResponse.getEntity(new GenericType<List<String>>(){}).get(0);
      System.out.println(" SituationLog ID: " + situationLogID);
    } catch (Exception exp){
      String error = exp.getMessage();
      System.err.println(error + ": ");
      exp.printStackTrace();
    }
    return situationLogID;
  }
/**
 * 
 * @param MapId
 * @param UserId
 * @param ConsumedFat
 * @return 
 * This method is used to build notification message when a user's food particular ingredients cross a threshold value.
 * This message constitutes of the monitoring condition and constraints related to that particular monitoring condition. The building
 * of such message is quite informative to the wellness services because it constitutes of monitoring condition and related constraints.
 */
 
  protected SituationNotification getNotificationMessage(String MapId, String UserId, String ConsumedFat){
    Connection conn = null;
    Statement sta = null;
    System.out.println(" Notification SCL is called");
    conn = DBConnection.getDBConnection().getConnection();
    List<SituationConditions> objListSituationConditions = new ArrayList<SituationConditions>();
    SituationEvent objSituationEvent = new SituationEvent();
    SituationNotification objSituationNotification = new SituationNotification();
    SituationConditions objSituationConditionsMonitor = new SituationConditions();
    SituationConditions objSituationConditionsMeasuring = new SituationConditions();
    SituationConditions objSituationConditionsConstraints = new SituationConditions();
    SituationLog objSituationLog = new SituationLog();

    try{
      CallableStatement callableStatement = conn.prepareCall("{call usp_NutritionMonitoringEvents(" + MapId + ")}");
      ResultSet rs = callableStatement.executeQuery();
      if (rs != null){
        while (rs.next()){
          String stActivity = rs.getString("Activity");
          String stActivityOperator = rs.getString("ActivityOperator");
          String stActivityValue = rs.getString("Activityvalue");
          String stActivityDataType = rs.getString("ActivityDataType");
          String stMeasuringMetric = rs.getString("MeasuringMetric");
          String stMeasuringOperator = rs.getString("MeasuringOperator");
          String stMeasuringTargetValue = rs.getString("MeasuringTargetValue");
          String stMeasuringDataType = rs.getString("MeasuringDataType");

          objSituationLog.setUserID(UserId);
          objSituationLog.setSituationCategoryID("16");
          objSituationLog.setSituationDescription("Fat " + stMeasuringTargetValue);
          objSituationLog.setSituationDate();

          objSituationConditionsMeasuring.setConditionKey(stMeasuringMetric);
          objSituationConditionsMeasuring.setConditionValue(stMeasuringTargetValue);
          objSituationConditionsMeasuring.setConditionValueOperator(stMeasuringOperator);
          objSituationConditionsMeasuring.setConditionType(stMeasuringDataType);

          objSituationConditionsMonitor.setConditionKey(stActivity);
          objSituationConditionsMonitor.setConditionValue(stActivityValue);
          objSituationConditionsMonitor.setConditionValueOperator(stActivityOperator);
          objSituationConditionsMonitor.setConditionType(stActivityDataType);

          System.out.println("********** Situation Triggered **********");
          System.out.println("\t User Id:" + UserId);
          System.out.println("\t Situation Details:");
          System.out.println("\t Current Activity:" + objSituationConditionsMonitor.getConditionValue());
          System.out.println("\t Consumed Fat:" + objSituationConditionsMeasuring.getConditionValue());
          System.out.println("*****************************************\n");
          System.out.println("****** SCL Recomendation Response *******");

          objListSituationConditions.add(objSituationConditionsMonitor);
          objListSituationConditions.add(objSituationConditionsMeasuring);

        }// end of loop
      }
      ///////////////stored procedure////////////
      CallableStatement callableStatement1 = conn.prepareCall("{call usp_NutritionSituationConstraints(" + MapId + ")}");

      ResultSet rs1 = callableStatement1.executeQuery();
      if (rs1 != null){
        while (rs1.next()){
          String stConstraintKey = rs1.getString("ConstraintKey");
          String stConstraintOperator = rs1.getString("ConstraintOperator");
          String stConstraintValue = rs1.getString("ConstraintValue");
          String stConstraintDataType = rs1.getString("ConstraintDataType");
          System.out.println(stConstraintKey + " " + stConstraintOperator + " " + stConstraintValue + " " + stConstraintDataType + " ");

          objSituationConditionsConstraints.setConditionKey(stConstraintKey);
          objSituationConditionsConstraints.setConditionValue(stConstraintValue);
          objSituationConditionsConstraints.setConditionValueOperator(stConstraintOperator);
          objSituationConditionsConstraints.setConditionType(stConstraintDataType);
          objListSituationConditions.add(objSituationConditionsConstraints);

          System.out.println("********** Situation Constrainds **********");
          System.out.println("\t Mapping ID:" + situationLogID);
          System.out.println("\t User Id:" + UserId);
          System.out.println("\t Situation Details:");
          System.out.println("\t Activity Constraint:" + objSituationConditionsConstraints.getConditionKey());
          System.out.println("\t Activity Constraint Value:" + objSituationConditionsConstraints.getConditionValue());
          System.out.println("*****************************************\n");
          System.out.println("****** SCL Recomendation Response *******");
        }// end of for
      }
        situationLogID = getSituationLog(objSituationLog);
        objSituationEvent.setListSConditions(objListSituationConditions);
        objSituationEvent.setSituationID(situationLogID);
        objSituationNotification.setSituationEvent(objSituationEvent);
        objSituationNotification.setUserID(UserId);  
    } catch (SQLException sqlException){
      String error = sqlException.getMessage();
      System.err.println(error + ": ");
      sqlException.printStackTrace();
    }
    
   return objSituationNotification;
  }
/**
 * 
 * @param objSituationLog
 * @return 
 * This method is used to get the logID which is required by SCL for reasoning to obtain the appropriate recommendation. 
 */
  protected static String getSituationLog(SituationLog objSituationLog){
    String situationLogID = null;
    try{
      ClientConfig config = new DefaultClientConfig();
      config.getClasses().add(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider.class);
      Client client = Client.create(config);
      final String baseURI = "http://192.168.3.11:8080/MMDataCurationRestfulService/webresources/ServiceCuration/AddSituation";
      WebResource srv = client.resource(UriBuilder.fromUri(baseURI).build());
      ClientResponse serverResponse = srv.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, objSituationLog);
      situationLogID = serverResponse.getEntity(new GenericType<List<String>>(){
      }).get(0);
    } catch (Exception exp){
      String error = exp.getMessage();
     // System.err.println(error + ":::::: ");
     // exp.printStackTrace();
    }
    return situationLogID;
  }

}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/rs/SCLServiceResource.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.rs;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.uclab.scl.Utilities.ComputationUtilityMethods;
import org.uclab.scl.communication.CommunicationManager;
import org.uclab.scl.datamodel.Conclusion;
import org.uclab.scl.datamodel.Disibilities;
import org.uclab.scl.datamodel.FiredRule;
import org.uclab.scl.datamodel.PhysiologicalFactors;
import org.uclab.scl.datamodel.RecommendationIngredients;
import org.uclab.scl.datamodel.RiskFactors;
import org.uclab.scl.datamodel.SituationConditions;
import org.uclab.scl.datamodel.SituationEvent;
import org.uclab.scl.datamodel.SituationNotification;
import org.uclab.scl.datamodel.User;
import org.uclab.scl.framework.Reasoner;
import org.uclab.scl.framework.ReasonerEnum;
import org.uclab.scl.framework.recbuilder.RecBuilder;
import org.uclab.scl.framework.recbuilder.RecBuilderPacket;
import org.uclab.scl.outputModel.SCLResponse;
import org.uclab.scl.outputModel.RecModel.PhyActivityRecommendations;

/**
 * REST Web Service
 * @version MM v2.5
 * @author Afzal
 */
@Path("SCLService")
public class SCLServiceResource {
  private static Logger LOG = LogManager.getRootLogger();
  CommunicationManager dclManager = CommunicationManager.getCommunicationManager();
  

  @Context
  private UriInfo context;

  /**
   * Constructor that creates a new instance of SCLServiceResource
   */
  public SCLServiceResource() {
  }

  
  /**
   * This service method is developed to build rule-based recommendation. 
   * It takes situation notification object as input return the recommendation results accordingly.
   * @param situationNotification
   * @return
   */

  @Path("PushPARecommendation")
  @POST
  @Produces("application/json")
  @Consumes("application/json")
  public SCLResponse buildSituationBasedPARecommendation(SituationNotification situationNotification) {

    SCLResponse response = new SCLResponse();
    List<String> result = new ArrayList<>();

    try {
      Reasoner rbr = Reasoner.getRuleBaseReasoner();
      RecBuilder recomBuilder = (RecBuilder) rbr.getMatchedRules(ReasonerEnum.SITUATION_PAREASONER);

      RecommendationIngredients recIngredients = new RecommendationIngredients();
      ComputationUtilityMethods cUtility = ComputationUtilityMethods.getComputationUtilityMethods();
      String situationValues = "";
      for (SituationConditions sc : situationNotification.getSituationEvent().getListSConditions()) {
        situationValues = situationValues + sc.getConditionValue() + " ";
      }
      LOG.debug("Situation Event Received from Lifelog Monitor (LLM): " + situationValues + "\n*************");

      User user = dclManager.getUser(Long.parseLong(situationNotification.getUserID()));
      List<RiskFactors> riskFactors = dclManager.getRiskFactors(Long.parseLong(situationNotification.getUserID()));
      List<Disibilities> disibilities = dclManager.getDisibilities(Long.parseLong(situationNotification.getUserID()));
      List<PhysiologicalFactors> physFactors = dclManager.getPhysiologicalFactors(Long.parseLong(situationNotification.getUserID()));
      
      recIngredients.setRiskFactors(riskFactors);
      recIngredients.setDisibilities(disibilities);
      recIngredients.setUser(user);
      recIngredients.setsNotification(situationNotification);
      recIngredients.setPhysFactors(physFactors);

      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
      Date dob = new Date();
      dob = sdf.parse(user.getDateOfBirth());
      recIngredients.setAgeGroup(cUtility.getAgeGroup(dob));
      LOG.debug("Call for situation reasoner...");
      RecBuilderPacket paRecBuilderInputPacket = new RecBuilderPacket();
      paRecBuilderInputPacket.setRecommendationInput(recIngredients);
      recomBuilder.buildRecommendation(paRecBuilderInputPacket);
      LOG.debug("Sittuation reasoner passed!");
      List<FiredRule> rules = paRecBuilderInputPacket.getRecommendationOutput();

      List<PhyActivityRecommendations> paRecommendations = new ArrayList<PhyActivityRecommendations>();
      PhyActivityRecommendations paRecommendation = new PhyActivityRecommendations();

      String currentDate = cUtility.getCurrentDate();

      LOG.debug("Final Resolved Rule(s): ");
      for (FiredRule fr : rules) {
        result.add("\n*******************************\nRecommendation Builder\n*******************************\nRecommendation(" + fr.getRuleId() + "): " + fr.getRuleConclusion());
        LOG.debug(fr.getRuleConclusion());
        for (Conclusion c : fr.getConclusionList()) {
          result.add(c.getConclusionKey() + c.getConclusionOperator() + c.getConclusionValue());
          LOG.debug(c.getConclusionKey() + c.getConclusionOperator() + c.getConclusionValue());
        }

      }

      List<String> resultRecPersistence = null;
      if (!(paRecommendations.isEmpty())) {
        resultRecPersistence = dclManager.persistPhysicalRecommendations(paRecommendations);
      }
      String recommendationID = resultRecPersistence.get(0);
      result.add(recommendationID);
      result.add("No Error");
    }
    catch (Exception e) {
      result.add("Error:");
      result.add(e.getMessage());
    }
    response.setResult(result);
    return response;

  }
  


  /**
   * PUT method for updating or creating an instance of SCLServiceResource
   * 
   * @param content
   *          representation for the resource
   * @return an HTTP response with content of the updated or created resource.
   */
  @PUT
  @Consumes("application/json")
  public void putJson(String content) {
  }

  @Path("TestLLMJSONFormat/")
  @GET
  @Produces("application/json")
  public SituationNotification getTestSitNotification() {
    SituationNotification sNotif = new SituationNotification();
    sNotif.setUserID("1");

    SituationEvent sEvt = new SituationEvent();
    sEvt.setSituationID("112");
    Set<SituationConditions> sitCon = new HashSet<>();

    SituationConditions sitCon1 = new SituationConditions();
    sitCon1.setConditionKey("Activity Level");
    sitCon1.setConditionValueOperator("String");
    sitCon1.setConditionValue("Sedentary");
    sitCon1.setConditionValueOperator("=");
    sitCon.add(sitCon1);

    SituationConditions sitCon2 = new SituationConditions();
    sitCon2.setConditionKey("Consumed Fat");
    sitCon2.setConditionValue("85");
    sitCon2.setConditionValueOperator(">");
    sitCon2.setConditionType("String");
    sitCon.add(sitCon2);

    sEvt.setListSConditions(sitCon);

    sNotif.setSituationEvent(sEvt);

    return sNotif;
  }
}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/communication/CommunicationManager.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.communication;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.uclab.scl.datamodel.Disibilities;
import org.uclab.scl.datamodel.PhysiologicalFactors;
import org.uclab.scl.datamodel.RiskFactors;
import org.uclab.scl.datamodel.User;
import org.uclab.scl.datamodel.UserSchedule;
import org.uclab.scl.outputModel.Achievement.Achievement;
import org.uclab.scl.outputModel.RecModel.PhyActivityFacts;
import org.uclab.scl.outputModel.RecModel.PhyActivityRecommendations;
/**
 * This class holds all the client methods for external layer communication in order to get, store, and update data from/to the databases.
 * @version MM v2.5
 * @author Afzal
 *
 */
public class CommunicationManager {
  private static Logger LOG = LogManager.getRootLogger();
  
  private String LIFELOG_DCL_SERVER1 = "http://127.0.0.1:8080/MMDataCurationRestfulService/webresources/DataCuration";
  private String LIFELOG_DCL_SERVER2 = "http://127.0.0.1:8081/MMDataCurationRestfulService/webresources/InformationCuration";
  private String LIFELOG_ICL_SERVER = "http://127.0.0.1:8082/MMDataCurationRestfulService/webresources/InformationCuration";
  private String LIFELOG_SCL_SERVER = "http://127.0.0.1:8083/MMDataCurationRestfulService/webresources/ServiceCuration";
  private String LIFELOG_SL_SERVER = "http://127.0.0.1/MMv2.5/snsservice.php?";
  
  private CommunicationManager() {
    if(!loadConfiguration()){
      LOG.error("Cannot load configuration file <Application.properties>");
    }
  }
  private boolean loadConfiguration(){
    try{
      Properties prop = new Properties();
      InputStream propInstream = new FileInputStream(getClass().getClassLoader().getResource("Application.properties").getFile());
      prop.load(propInstream);
      propInstream.close();
      LIFELOG_DCL_SERVER1 = prop.getProperty("LIFELOG_DCL_SERVER1");
      LIFELOG_DCL_SERVER2 = prop.getProperty("LIFELOG_DCL_SERVER2");
      LIFELOG_ICL_SERVER = prop.getProperty("LIFELOG_ICL_SERVER");
      LIFELOG_SCL_SERVER = prop.getProperty("LIFELOG_SCL_SERVER");
      LIFELOG_SL_SERVER = prop.getProperty("LIFELOG_SL_SERVER");
      
    }catch(IOException e){
      return false;
    }
    return true;
  }
  
  /**
   * This method takes user identifier and returns the whole record of that user stored in the database.
   * <p>
   * @param userID
   * @return user
   */
  public User getUser(long userID) {
    AbstractRestClient<User, String> userWSClient = new DCUserWSClient(LIFELOG_DCL_SERVER1);
    String resourceUser_GETURI = "/User/" + String.valueOf(userID);
    User user = userWSClient.GetData(resourceUser_GETURI);
    return user;

  }
  
  /**
   * Based on the user identifier, the list of disibilities of that user are returned.
   * <p>
   * @param userID
   * @return disibilites list
   */
  public List<Disibilities> getDisibilities(long userID) {
    AbstractRestClient<List<Disibilities>, String> disibilitiesClient = new DCDisibilitiesWSClient(LIFELOG_DCL_SERVER1);
    String resourceDisibilities_GETURI = "/UserDisabilities/" + String.valueOf(userID);
    List<Disibilities> disibilities = disibilitiesClient.GetData(resourceDisibilities_GETURI);
    return disibilities;
  }
  /**
   * Based on the user identifier, the list of risk factors of that user are returned.
   * <p>
   * @param userID
   * @return ristFactor list
   */
  public List<RiskFactors> getRiskFactors(long userID) {
    AbstractRestClient<List<RiskFactors>, String> riskFactorWSClient = new DCRiskFactorsWSClient(LIFELOG_DCL_SERVER1);
    String resourceRiskFactor_GETURI = "/RiskFactors/" + String.valueOf(userID);
    List<RiskFactors> riskFactors = riskFactorWSClient.GetData(resourceRiskFactor_GETURI);
    return riskFactors;
  }
  /**
   * Based on user identifier, the list of physical activity recommendations are returned.
   * <p>
   * @param userID
   * @return PhysicalActivityRecommendation list
   */
  public List<PhyActivityRecommendations> getPhysicalRecommendations(long userID) {
    AbstractRestClient<List<PhyActivityRecommendations>, List<String>> phyActityRecommWSClient = new PhysicalActivityRecommenationWSClient(LIFELOG_SCL_SERVER);
    String resourceFacts_GETURI = "/Recommendation/" + String.valueOf(userID);
    List<PhyActivityRecommendations> recommendations = phyActityRecommWSClient.GetData(resourceFacts_GETURI);
    return recommendations;
  }
  /**
   * Based on user identifier, the list of physiological factors (height, weight etc.) are returned.
   * <p>
   * @param userID
   * @return physiologicalFactors list
   */
  public List<PhysiologicalFactors> getPhysiologicalFactors(long userID) {
    AbstractRestClient<List<PhysiologicalFactors>, String> phyiologicalFactorsWSClient = new DCPhysiologicalFactorsWSClient(LIFELOG_DCL_SERVER1);
    String resourceFacts_GETURI = "/PhysiologicalFactors/" + String.valueOf(userID);
    List<PhysiologicalFactors> physiologicalFactors = phyiologicalFactorsWSClient.GetData(resourceFacts_GETURI);
    return physiologicalFactors;
  }
  
  /**
   * This method is used to persist the recommendation generated by the system in the Lifelog database and returns the success or failure message.
   * <p>
   * @param pActRecommendations
   * @return List<String>
   */
  public List<String> persistPhysicalRecommendations(List<PhyActivityRecommendations> pActRecommendations) {
    AbstractRestClient<List<PhyActivityRecommendations>, List<String>> phyActityRecommWSClient = new PhysicalActivityRecommenationWSClient(LIFELOG_SCL_SERVER);
    String resourcePhyActRecURI = "/AddRecommendation";
    List<String> recommendationResult = phyActityRecommWSClient.PostData(resourcePhyActRecURI, pActRecommendations);
    return recommendationResult;
  }
  
  /**
   * This method is used to update the already stored recommendation in the Lifelog database identified with recommendation identifier for a particular user.
   * <p>
   * @param pActRecommendations
   * @return List<String>
   */
  public List<String> updatePhysicalRecommendations(List<PhyActivityRecommendations> pActRecommendations) {
    AbstractRestClient<List<PhyActivityRecommendations>, List<String>> phyActityRecommWSClient = new PhysicalActivityRecommenationWSClient(LIFELOG_SCL_SERVER);
    String resourcePhyActRecURI = "/UpdateRecommendation";
    List<String> recommendationResult = phyActityRecommWSClient.PostData(resourcePhyActRecURI, pActRecommendations);
    return recommendationResult;
  }
  
  /**
   * Based on user identifier, the list of physical activity educational facts are returned.
   * <p>
   * @param userID
   * @return PhysicalActivityFacts List
   */
  public List<PhyActivityFacts> getPAFacts(long userID) {
    AbstractRestClient<List<PhyActivityFacts>, List<String>> pAFactClient = new PhysicalActivityFactsWSClient(LIFELOG_SCL_SERVER);
    String resourceFacts_GETURI = "/Facts/" + String.valueOf(userID);
    List<PhyActivityFacts> facts = pAFactClient.GetData(resourceFacts_GETURI);
    return facts;
  }
  
  /**
   * This method used is used to save the physical activity educational facts in the Lifelog database.
   * <p>
   * @param pAFacts
   * @return List<String>
   */
  public List<String> persistPAFacts(List<PhyActivityFacts> pAFacts) {
    AbstractRestClient<List<PhyActivityFacts>, List<String>> pAFactClient = new PhysicalActivityFactsWSClient(LIFELOG_SCL_SERVER);
    String resourcePhyActFactURI = "/AddFacts";
    List<String> factsPersistenceResult = pAFactClient.PostData(resourcePhyActFactURI, pAFacts);
    return factsPersistenceResult;
  }
  /**
   * This method is used to update the physical activity educational facts in the Lifelog databse traced with Facts identifier for a particular user.
   * <p>
   * @param pAFacts
   * @return List<String>
   */
  public List<String> updatePAFacts(List<PhyActivityFacts> pAFacts) {
    AbstractRestClient<List<PhyActivityFacts>, List<String>> pAFactClient = new PhysicalActivityFactsWSClient(LIFELOG_SCL_SERVER);
    String resourcePhyActFactURI = "/UpdateFacts";
    List<String> factsPersistenceResult = pAFactClient.PostData(resourcePhyActFactURI, pAFacts);
    return factsPersistenceResult;
  }
  /**
   * Based on user id set in user schedule object, the list of user schedule objects is returned.
   * <p>
   * @param usrSchedule
   * @return userSchedule
   */
  public List<UserSchedule> getUserSchedule(UserSchedule usrSchedule) {
    AbstractRestClient<List<UserSchedule>, List<UserSchedule>> usrScheduleWSClient = new DCUserScheduleWSClient(LIFELOG_DCL_SERVER1);
    String resourceUserSchedule = "/GetUserScheduleByIDandTime";
    List<UserSchedule> usrScheduleRequest = new ArrayList<>();
    usrScheduleRequest.add(usrSchedule);
    List<UserSchedule> usrScheduleDetails = usrScheduleWSClient.PostData(resourceUserSchedule, usrScheduleRequest);
    return usrScheduleDetails;
  }
  /**
   * This method is used to save the achievements of a user in the Lifelog database.
   * <p>
   * @param achievement
   * @return List<String>
   */
  public List<String> persistAchievement(Achievement achievement) {
    AbstractRestClient<Achievement, List<String>> achievementClient = new PhysicalActivityAchievementWSClient(LIFELOG_SCL_SERVER);
    String resourcePhyActAchievemntURI = "/AddAchievements";
    List<String> achievementResult = achievementClient.PostData(resourcePhyActAchievemntURI, achievement);
    return achievementResult;
  }
  
  /**
   * Singleton pattern: making sure one instance of DataCurationCommunicationManager
   * <p>
   * @return Communication Manager
   */
  public static CommunicationManager getCommunicationManager() {
    return CommunicationManagerHolder.INSTANCE;
  }

  private static class CommunicationManagerHolder {
    private static final CommunicationManager INSTANCE = new CommunicationManager();
  }
}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/interpreterdatamodel/FoodLog.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.interpreterdatamodel;

import java.io.Serializable;

import org.codehaus.jackson.annotate.JsonProperty;

/**
 * @version MM v2.5
 * @author Afzal
 *
 */
public class FoodLog implements Serializable {
  
  @JsonProperty("id")
  private long id;
  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public String getRequestType() {
    return requestType;
  }

  public void setRequestType(String requestType) {
    this.requestType = requestType;
  }

  @JsonProperty("requestType")
  private String requestType;
  
  @JsonProperty("eatingTime")
  private String eatingTime;
  @JsonProperty("foodName")
  private String foodName;
  @JsonProperty("totalCarbohydrate")
  private long totalCarbohydrate;
  @JsonProperty("totalFat")
  private long totalFat;
  @JsonProperty("totalFoodItem")
  private long totalFoodItem;
  @JsonProperty("totalProtein")
  private long totalProtein;
  @JsonProperty("userId")
  private long userId;

  // private String totalCarbs;
  // private String totalProts;

  /**
   * 
   * @return The eatingTime
   */
  @JsonProperty("eatingTime")
  public String getEatingTime() {
    return eatingTime;
  }

  /**
   * 
   * @param eatingTime
   *          The eatingTime
   */
  @JsonProperty("eatingTime")
  public void setEatingTime(String eatingTime) {
    this.eatingTime = eatingTime;
  }

  /**
   * 
   * @return The foodName
   */
  @JsonProperty("foodName")
  public String getFoodName() {
    return foodName;
  }

  /**
   * 
   * @param foodName
   *          The foodName
   */
  @JsonProperty("foodName")
  public void setFoodName(String foodName) {
    this.foodName = foodName;
  }

  /**
   * 
   * @return The totalCarbohydrate
   */
  @JsonProperty("totalCarbohydrate")
  public long getTotalCarbohydrate() {
    return totalCarbohydrate;
  }

  /**
   * 
   * @param totalCarbohydrate
   *          The totalCarbohydrate
   */
  @JsonProperty("totalCarbohydrate")
  public void setTotalCarbohydrate(long totalCarbohydrate) {
    this.totalCarbohydrate = totalCarbohydrate;
  }

  /**
   * 
   * @return The totalFat
   */
  @JsonProperty("totalFat")
  public long getTotalFat() {
    return totalFat;
  }

  /**
   * 
   * @param totalFat
   *          The totalFat
   */
  @JsonProperty("totalFat")
  public void setTotalFat(long totalFat) {
    this.totalFat = totalFat;
  }

  /**
   * 
   * @return The totalFoodItem
   */
  @JsonProperty("totalFoodItem")
  public long getTotalFoodItem() {
    return totalFoodItem;
  }

  /**
   * 
   * @param totalFoodItem
   *          The totalFoodItem
   */
  @JsonProperty("totalFoodItem")
  public void setTotalFoodItem(long totalFoodItem) {
    this.totalFoodItem = totalFoodItem;
  }

  /**
   * 
   * @return The totalProtein
   */
  @JsonProperty("totalProtein")
  public long getTotalProtein() {
    return totalProtein;
  }

  /**
   * 
   * @param totalProtein
   *          The totalProtein
   */
  @JsonProperty("totalProtein")
  public void setTotalProtein(long totalProtein) {
    this.totalProtein = totalProtein;
  }

  /**
   * 
   * @return The userId
   */
  @JsonProperty("userId")
  public long getUserId() {
    return userId;
  }

  /**
   * 
   * @param userId
   *          The userId
   */
  @JsonProperty("userId")
  public void setUserId(long userId) {
    this.userId = userId;
  }

  /**
   * @return the totalCarbs
   */
  // public String getTotalCarbs() {
  // return totalCarbs;
  // }
  //
  // /**
  // * @param totalCarbs the totalCarbs to set
  // */
  // public void setTotalCarbs(String totalCarbs) {
  // this.totalCarbs = totalCarbs;
  // }
  //
  // /**
  // * @return the totalProts
  // */
  // public String getTotalProts() {
  // return totalProts;
  // }
  //
  // /**
  // * @param totalProts the totalProts to set
  // */
  // public void setTotalProts(String totalProts) {
  // this.totalProts = totalProts;
  // }

  @Override
  public String toString() {
    String keyValue = "\"Consumed Fat\":\"" + this.getTotalFat() + "\",\n";
    keyValue += "\"Consumed Protein\":\"" + this.getTotalProtein() + "\",\n";
    keyValue += "\"Consumed Carbohydrate\":\"" + this.getTotalCarbohydrate()
        + "\",";

    return keyValue;
  }

}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/framework/RecInterpreter/FoodItemRecommender/CategoryToFooditemsMapper.java<|end_filename|>
/* Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.scl.framework.RecInterpreter.FoodItemRecommender;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;

public class CategoryToFooditemsMapper {
  static HashMap<String, String> mapCatToFooditems = new HashMap<>();
  private static final String filePath = "FoodCatToFooditems.txt";
  private static Scanner scanFile;

  public HashMap CatToFooditemsMapper() throws FileNotFoundException {
    try {
      scanFile = new Scanner(this.getClass().getClassLoader().getResourceAsStream(filePath));
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
    String readFile = null;
    String key = null;
    String value = "";

    int test = 0;
    while (scanFile.hasNextLine()) {
      readFile = scanFile.nextLine();
      String array[] = readFile.split(",");
      key = array[0];
      
      while (test < array.length) {
        if (test == 0) {
          test += 1;
        } else if (test == 1) {
          value = array[test];
          test += 1;
        } else {
          value = value + "," + array[test];
          test += 1;
        }
        mapCatToFooditems.put(key, value);
      } // inner-while
      test = 0;
      key = null;
      value = "";
    } // outer-while
    scanFile.close();
    return mapCatToFooditems;
  }// main
}


<|start_filename|>data-curation-layer/data-acquisition-and-synchronization/sync_code.js<|end_filename|>
/*Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

/* ***********************************************************************************************
Author: <NAME>
Affiliation: UC Lab
Project: Mining Mind
Created date: 2016-03-23
Revised date: 2016-10-27
Last revised date: 2016-11-10
Reason: add audio/image support
Functionality: do the synchronization for unlimited data source.
*********************************************************************************************** */

/*Required libraries***********************************************************************************************/
var express		=require('express');
var loki        =require('lokijs');
var bodyParser  =require('body-parser');
var requestify  =require('requestify');
var fs = require('fs');
var util = require('util');
var nodeProcess = require('process');
var config = require('./config.json');
var apiHelper=require('./api.js');
var multer  =   require('multer');
/*Required libraries***********************************************************************************************/

/*Load configuration***********************************************************************************************/
var nDataSource=config.nDataSource;	// number of data source. 
									//Theoretically, this source code can
									//handle unlimited number of data source.
var deadline =config.deadline;//deadline to issue the forced (bad) data sync
var destUrl=config.destUrl;
var serverPort=config.serverPort;	// number of data source. 
/*Load configuration***********************************************************************************************/

/*Global variables***********************************************************************************************/
//var tempDate=new Date("2000/01/01");
//var summaryDuration=tempDate.getTime();
//var nSync=0;
var storage =   multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now());
  }
});
var upload = multer({ storage : storage}).single('userFile');//name of upload MUST equals to the name of FILE FIELD in uploaded form// ATTENTIONNNN
/*Global variables***********************************************************************************************/

/*Server initialization***********************************************************************************************/
var app	=express();
	app.use(bodyParser.json());
var urlencodedParser = bodyParser.urlencoded({ extended: true })
var db =new loki('sync_temp');
var buffer =db.addCollection('buffer');//main collection for data sync
var historyData =db.addCollection('history');//most previous data for covering the missing value
/*Server initialization***********************************************************************************************/

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

//following is the processing code for the HTTP POST restful, the route /newData is the entry point for all of data source
app.post('/newData', urlencodedParser,  function (req,res){	
		console.log(req.body);
		var revDataType= req.body.id;//id/type of the data source. For example: android source is 1, k'nect is 2, accelerometer is 3, GPS is 4.
        var revUserId = req.body.revUserId;//id of user
        var revTimeStamp = req.body.timestamp;//time stamp of incoming data.
        var revContent = req.body.data;//content of the data				
		var timeDataCome=Date.now();		
		var timeObjData=new Date(timeDataCome);
		
		/*console.log("xxxxxxxxxxxxxxxxxxxxxxxx");
		console.log("Data comes at: "+timeObjData.toUTCString());
		console.log("Data type: "+revDataType);
		console.log("User ID: "+revUserId);
		console.log("Time stamp: "+revTimeStamp);
		console.log("Data content: "+revContent);
		console.log("End xxxxxxxxxxxxxxxxxxxxxxxx");*/
		
		/*We depend on the existence of the user to determine that the data is existed or not. The logic is simple.
		There are three cases: 
		1. data of type X is existed, and the incoming data is also X--> update the data of type X with the new one and check for the sync completion.
		2. data of type X is not existed, but the data of the other types--> it means that the sync has already 
			started. Just create new record for X and check for the sync completion.
		3. No data of any type is existed--> Create the record of incoming type and start the sync.
			Note: only the first data can start the sync process. The later data are only and check for the sync completion.
			If the quantity is exceeded, then send the data collection, save one copy to history and clear the sent data from buffer.*/
        var record = buffer.find({userID: revUserId});
        if(record.length){//the first and second case.
			var dataNotExist=1;//flag for data existence.
			for(var i = 0; i < record.length; i++){//iterate through the data to check for existence.
				if(record[i].dataType == revDataType){//data type is matched--> update new data and break the iteration.
					record[i].timeStamp=revTimeStamp;
					record[i].contentBody=revContent;
					buffer.update(record[i]);
					dataNotExist=0;//data existed, no need to add new data.
					break;
				}
			}
			if(dataNotExist){//gone through the data checking but no matched--> create new record for the data.
				addNewData(buffer,revDataType,revTimeStamp,revContent,revUserId);
            }          
        }else{//no data existence of any type of source. Create new record and start the sync process. The sync handle is also keep into the record.
			var badSyncClock=setTimeout(function(){ badSync(buffer,revUserId,historyData) },deadline);
			//console.log("++++++++");
			//var time2Sync=Date.now();
			//summaryDuration=summaryDuration-time2Sync;
			//var timeObj=new Date(time2Sync);
			//console.log("Time to start sync:"+ timeObj);
			//console.log("++++++++");
			//this called the bad sync because it relies on the deadline. When deadline comes but some data are still missing, then cover them with the most previous historical data.
            addNewData(buffer,revDataType,revTimeStamp,revContent,revUserId,badSyncClock,1);			
        }
		var xSync=apiHelper.coreSync(buffer,revUserId,historyData,nDataSource,config);		
		res.json(xSync);
});

app.post('/newFile',function(req,res){
    upload(req,res,function(err) {
		console.log(util.inspect(req));
        if(err) {
            return res.end("Error uploading file.");
        }
		
		/*console.log(util.inspect(req.file));				
		console.log(req.body.revUserId);
		console.log(req.body.timestamp);
		console.log(req.file.filename);	*/		
        res.end("File is uploaded");
		var exttype = req.file.mimetype.split("/");
		var ext=exttype[1];
		var type=exttype[0];
		var revDataType="";//id/type of the data source. For example: audio is 5, video/image is 6.
		if(type=="audio")	
			revDataType=5;
		else
			revDataType=6;
        var revUserId = req.body.revUserId;//id of user
        var revTimeStamp = req.body.timestamp;//time stamp of incoming data.
        var revContent = type+"_"+revUserId+'_'+revTimeStamp+'.'+ext;//content of the data
		fs.rename('./uploads/'+req.file.filename, './uploads/'+revContent, function(err) {
		if ( err ) console.log('ERROR: ' + err);
		});
		var record = buffer.find({userID: revUserId});
        if(record.length){//the first and second case.
			var dataNotExist=1;//flag for data existence.
			for(var i = 0; i < record.length; i++){//iterate through the data to check for existence.
				if(record[i].dataType == revDataType){//data type is matched--> update new data and break the iteration.
					record[i].timeStamp=revTimeStamp;
					record[i].contentBody=revContent;
					buffer.update(record[i]);
					dataNotExist=0;//data existed, no need to add new data.
					break;
				}
			}
			if(dataNotExist){//gone through the data checking but no matched--> create new record for the data.
				addNewData(buffer,revDataType,revTimeStamp,revContent,revUserId);
            }          
        }else{//no data existence of any type of source. Create new record and start the sync process. The sync handle is also keep into the record.
			var badSyncClock=setTimeout(function(){ badSync(buffer,revUserId,historyData) },deadline);
			//console.log("++++++++");
			//var time2Sync=Date.now();
			//summaryDuration=summaryDuration-time2Sync;
			//var timeObj=new Date(time2Sync);
			//console.log("Time to start sync:"+ timeObj);
			//console.log("++++++++");
			//this called the bad sync because it relies on the deadline. When deadline comes but some data are still missing, then cover them with the most previous historical data.
            addNewData(buffer,revDataType,revTimeStamp,revContent,revUserId,badSyncClock,1);			
        }
		var xSync=apiHelper.coreSync(buffer,revUserId,historyData,nDataSource,config);	
		
		
    });
});

/*****************************************************
Function: badSync
Content: bad guys do the bad thing if the coreSync does not work well because of the shortage of data.
Input parameters: badSync(objLoki,mUserId,history)
1. objLoki: the reference to the buffer collection.
2. mUserId: the id of the user.
3. history: the reference to the history collection.
Output: no.
*****************************************************/
function badSync(objLoki,mUserId,history)
{	
	//Query the most previous historical data collection for data covering.
	var record = history.find({userID: mUserId});	
	//Force the data synchronization no matter the data is enough or not.
	//Remember that before doing the bad sync, I also check for the chance of good sync for one last time. If we are lucky, so we will not miss the latest data.
	var xSync= apiHelper.coreSync(objLoki,mUserId,history,nDataSource,config,1,record[0]);	
}

/*****************************************************
Function: addNewData
Content: as its name, add new data to the buffer.
Input parameters: coreSync(objLoki,dType,dTstamp,dContent,dUserid,syncClock,first_touch)
1. objLoki: the reference to the buffer collection.
2. dType,dTstamp,dContent,dUserid: the content and meta of the incoming data.
3. syncClock: optional, the reference to the bad sync clock. We need to keep this ref to cancel it later if the sync completed before the deadline.
4. first_touch: optional, this flag indicates that the sync needs to start after this first record is created.

Output: no
*****************************************************/
function addNewData(objLoki,dType,dTstamp,dContent,dUserid,syncClock,first_touch)
{
	var dChunk={};
	dChunk.dataType = dType;
	dChunk.timeStamp = dTstamp;
	dChunk.contentBody=dContent;
	dChunk.userID=dUserid;
	if(typeof first_touch != 'undefined')
			{
				dChunk.syncStartTime=dTstamp;
				dChunk.syncYet=0;//the handle to determine that this is the first record.
				dChunk.syncClockRef=syncClock;
			}
	objLoki.insert(dChunk);
	//console.log(util.inspect(objLoki)) 
}
//check whether any instances of node js are existed -->
var nodePID = fs.readFileSync('pid','utf8');
var checkInstance=require('is-running')(nodePID);
//<--check whether any instances of node js are existed
if (!checkInstance)//no instance
{
//start the syncronization server on port 8081
app.listen(serverPort, function (){
	console.log('Synchronization server is listening at port '+serverPort+'.');
	if (nodeProcess.pid) {
		fs.writeFile("pid", nodeProcess.pid, function(err) {
		if(err) {
			return console.log(err);
		}
		//console.log("The file was saved!"+destUrl[0]["url"]);
		apiHelper.sensorQtyAdjust(5,config);
		//apiHelper.destAdjust([{"url":"http://xyz2.com"},{"url":"http://xyz3.com"}],config);
		}); 
	
	}
});
}
else{
console.log("Cannot start Synchronization server because of the existence of other instance.");
}







/*****************************************************
Apendix:
data form history:
[
	{
	  "userID": "12232",
	  
	  "timeStamp_1232": "2016",
	  "contentBody_1232": "con meo",
	  
	  "timeStamp_123": "2016",
	  "contentBody_123": "con meo",
	  
	  "meta": {
		"revision": 0,
		"created": 1458793197366,
		"version": 0
	  },
	  "$loki": 1
	}
]
data from buffer:
[
  {
    "user_122324": {
      "data_122": {
        "timeStamp": "20160312",
        "content": "zhgbckdjfkld"
      }
    },
    "meta": {
      "revision": 0,
      "created": 1458752201592,
      "version": 0
    },
    "$loki": 1
  },
  {
    "user_122324": {
      "data_122": {
        "timeStamp": "20160312",
        "content": "zhgbckdjfkld"
      }
    },
    "meta": {
      "revision": 0,
      "created": 1458752201592,
      "version": 0
    },
    "$loki": 1
  }
]
*****************************************************/

<|start_filename|>knowledge-curation-layer/i-kat/src/main/java/org/uclab/mm/kcl/edkat/controller/UserController.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.kcl.edkat.controller;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.uclab.mm.kcl.edkat.datamodel.Rule;
import org.uclab.mm.kcl.edkat.datamodel.SituationRuleWrapper;
import org.uclab.mm.kcl.edkat.datamodel.User;
import org.uclab.mm.kcl.edkat.service.UserService;

/**
 * This is controller class for the users,  this controller currently handles users' login but will implement
 * create, update, retrieve of users of the application
 * @author  <NAME>
 * @version 1.0
 * @since   2015-08-16
 * */

@Controller
@SessionAttributes("user")
public class UserController {

	/**
	 * Object creation of UserService
	*/
	private UserService objUserService;
	
	 private static final Logger logger = LoggerFactory.getLogger(UserController.class);

	/**
	 * Setter of UserService's object
	*/
	@Autowired(required=true)
    @Qualifier(value="objUserService")
	public void setObjUserService(UserService objUserService) {
		this.objUserService = objUserService;
	}
	
	/**
	 * This method render login screen
	 * @return Login string
	*/
	@RequestMapping(value = "/login", method = RequestMethod.GET)
    public String listRules(Model model) {
		try
		{
			User user = new User();
			model.addAttribute("user", user);
	        logger.info("login rendered successfully");
		}
		catch(Exception ex)
		{
			 logger.info("Error in rendering login");
			 
		}
		return "Login";
    }
	
	/**
	 * This method validate the user by user id and password.
	 * @param user
	 * @return string
	*/
	@RequestMapping(value= "/user/validate", method = RequestMethod.POST)
    public String validateUser(@ModelAttribute("user") User user, Model model) {
		try
		{
			user = objUserService.validateUser(user);
			if(user.getUserID() != 0)
			{
				model.addAttribute("user", user);
				logger.info("User validated successfully");
				return "redirect:/rules";
			}
			else
			{
				model.addAttribute("error", "Invalid ID or Password.");
				logger.info("User validated successfully");
				return "Login";
			}
	        
		}
		catch(Exception ex)
		{
			 logger.info("Error in validating user");
			 return "Login";
		}
	
	}

}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/framework/RecInterpreter/PARecommender/ContextEvaluator.java<|end_filename|>
/* Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.scl.framework.RecInterpreter.PARecommender;

import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.uclab.scl.datamodel.contextMapper.*;

public class ContextEvaluator {
  private static Logger LOG = LogManager.getRootLogger();
  
  static HashMap<String, String> mapWeatherRec = new HashMap<>();
  static HashMap<String, String> mapLocationRec = new HashMap<>();
  static HashMap<String, String> mapHLCRec = new HashMap<>();
  static HashMap<String, String> mapEmotionRec = new HashMap<>();
  static HashMap<String, String> mapDisableRec = new HashMap<>();


  @SuppressWarnings("unchecked")
  public static int[] generateContextMatrix(String receivedContext) throws Exception {

    DisableMapper mapDisable = new DisableMapper();
    EmotionMapper mapEmotion = new EmotionMapper();
    HLCMapper mapHLC = new HLCMapper();
    LocationMapper mapLoc = new LocationMapper();
    WeatherMapper mapWeather = new WeatherMapper();

    mapWeatherRec = mapWeather.weatherMapper();
    mapLocationRec = mapLoc.locationMapper();
    mapHLCRec = mapHLC.hlcMapper();
    mapEmotionRec = mapEmotion.emotionMapper();
    mapDisableRec = mapDisable.disableMapper();


    String context[] = receivedContext.split(",");
   // LOG.debug("Rec: Walking,Running,Stretching,Cyclng,Sitting");
    
    char[] loc = mapLocationRec.get(context[0]).replaceAll(",", "").toCharArray();
   // LOG.debug("Location"  + mapLocationRec.get(context[0]));
    
    char[] hlc = mapHLCRec.get(context[1]).replaceAll(",", "").toCharArray();
  //  LOG.debug("HLC"  + mapHLCRec.get(context[1]));
    
    char[] weather = mapWeatherRec.get(context[2]).replaceAll(",", "").toCharArray();
  //  LOG.debug("Weather"  + mapWeatherRec.get(context[2]));
    
    char[] emotion = mapEmotionRec.get(context[3]).replaceAll(",", "").toCharArray();
  //  LOG.debug("Emotion"  + mapEmotionRec.get(context[3]));
    
    char[] disable = mapDisableRec.get(context[4]).replaceAll(",", "").toCharArray();
  //  LOG.debug("Injury"  + mapDisableRec.get(context[4]));
    
    // CONTEXTUAL MATRIX
    int[] aggregateVector = new int[loc.length];
    for (int i = 0; i < aggregateVector.length; i++)
      if ((loc[i] == '1') && (hlc[i] == '1') && (weather[i] == '1') && (emotion[i] == '1') && (disable[i] == '1')) {
        aggregateVector[i] = 1;
      } else {
        aggregateVector[i] = 0;
      }
    return (aggregateVector);
  }
}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/interpreterdatamodel/SNSTrends.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.interpreterdatamodel;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
import org.codehaus.jackson.annotate.JsonProperty;
//import javax.xml.bind.annotation.XmlRootElement;
//
/**
 * @version MM v2.5
 * @author Afzal
 *
 */
@XmlRootElement
public class SNSTrends implements Serializable {

  @JsonProperty("name")
  private List<String> name = new ArrayList<>();

  @JsonProperty("total")
  private List<String> total = new ArrayList<>();

  /**
   * 
   * @return The name
   */
  @JsonProperty("name")
  public List<String> getName() {
    return name;
  }

  /**
   * 
   * @param name
   *          The name
   */
  @JsonProperty("name")
  public void setName(List<String> name) {
    this.name = name;
  }

  /**
   * 
   * @return The total
   */
  @JsonProperty("total")
  public List<String> getTotal() {
    return total;
  }

  /**
   * 
   * @param total
   *          The total
   */
  @JsonProperty("total")
  public void setTotal(List<String> total) {
    this.total = total;
  }

}

<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/ContextOntologyManager/AbstractHandler.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.ContextOntologyManager;

import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Resource;

import mm.icl.hlc.OntologyTools.ContextOntology;
import mm.icl.hlc.OntologyTools.LowLevelContext;
import mm.icl.hlc.OntologyTools.NutritionContext;
import mm.icl.hlc.OntologyTools.PhysicalActivityContext;
/**
 * Abstract Handler contains all Function required by. Context Handler  
 * for Certain other Context for many Ontologies. It provides 
 * Most Common methods for re-use purpose by implementing Pattern
 * 
 * @author <NAME>
 * @version 2.5
 * @since 2016-10-28
 */
public abstract class AbstractHandler {
	public abstract void initialize(String directory, ContextOntology ont);
	public abstract PhysicalActivityContext retrievePreviousHlcAndStoreNew(PhysicalActivityContext newHlc);
	public abstract NutritionContext retrievePreviousHlcAndStoreNew(NutritionContext newHlc);
	public abstract  void storeNewLlc(LowLevelContext newLlc);
	public abstract void finalizePreviousLlc(OntClass category, Resource user, Literal time);
}


<|start_filename|>data-curation-layer/active-data-reader/src/main/resources/HiveConnect/Connect.java<|end_filename|>
package HiveConnect;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Connect
 */
public class Connect extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Connect() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// response.getWriter().append("Served at:
		// ").append(request.getContextPath());
		PrintWriter out = response.getWriter();
		try {
			Class.forName("org.apache.hive.jdbc.HiveDriver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			out.println("Can't Load Database Driver");
		}

		try {
			DriverManager.getConnection("jdbc:hive2://172.16.17.32:10000/test1", "hive", "hive");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			out.println("Can't Connect the Database");
			return;
		}
		 out.println("Connected to the Database");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/CurrentContextPacket.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.uclab.mm.datamodel.ic.FoodLog;
import org.uclab.mm.datamodel.ic.UserDetectedLocation;
import org.uclab.mm.datamodel.ic.UserRecognizedActivity;
import org.uclab.mm.datamodel.ic.UserRecognizedEmotion;
import org.uclab.mm.datamodel.ic.UserRecognizedHLC;

/**
 *
 * @author <NAME>
 */
@Entity
public class CurrentContextPacket implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private Long userID;
    private String startTime;
    private String endTime;
    
    private List<UserRecognizedActivity> objListUserRecognizedActivity = new ArrayList<UserRecognizedActivity>();
    private List<UserDetectedLocation> objListUserDetectedLocation = new ArrayList<UserDetectedLocation>();
    private List<UserRecognizedEmotion> objListUserRecognizedEmotion = new ArrayList<UserRecognizedEmotion>();
    private List<UserRecognizedHLC> objListUserRecognizedHLC = new ArrayList<UserRecognizedHLC>();
    private List<FoodLog>  objListFoodLog = new ArrayList<FoodLog>();
    

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof CurrentContextPacket)) {
            return false;
        }
        CurrentContextPacket other = (CurrentContextPacket) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.sc.CurrentContextPacket[ id=" + id + " ]";
    }

    /**
     * @return the userID
     */
    public Long getUserID() {
        return userID;
    }

    /**
     * @param userID the userID to set
     */
    public void setUserID(Long userID) {
        this.userID = userID;
    }

    /**
     * @return the startTime
     */
    public String getStartTime() {
        return startTime;
    }

    /**
     * @param startTime the startTime to set
     */
    public void setStartTime(String startTime) {
        this.startTime = startTime;
    }

    /**
     * @return the endTime
     */
    public String getEndTime() {
        return endTime;
    }

    /**
     * @param endTime the endTime to set
     */
    public void setEndTime(String endTime) {
        this.endTime = endTime;
    }

    /**
     * @return the objListUserRecognizedActivity
     */
    public List<UserRecognizedActivity> getObjListUserRecognizedActivity() {
        return objListUserRecognizedActivity;
    }

    /**
     * @param objListUserRecognizedActivity the objListUserRecognizedActivity to set
     */
    public void setObjListUserRecognizedActivity(List<UserRecognizedActivity> objListUserRecognizedActivity) {
        this.objListUserRecognizedActivity = objListUserRecognizedActivity;
    }

    /**
     * @return the objListUserDetectedLocation
     */
    public List<UserDetectedLocation> getObjListUserDetectedLocation() {
        return objListUserDetectedLocation;
    }

    /**
     * @param objListUserDetectedLocation the objListUserDetectedLocation to set
     */
    public void setObjListUserDetectedLocation(List<UserDetectedLocation> objListUserDetectedLocation) {
        this.objListUserDetectedLocation = objListUserDetectedLocation;
    }

    /**
     * @return the objListUserRecognizedEmotion
     */
    public List<UserRecognizedEmotion> getObjListUserRecognizedEmotion() {
        return objListUserRecognizedEmotion;
    }

    /**
     * @param objListUserRecognizedEmotion the objListUserRecognizedEmotion to set
     */
    public void setObjListUserRecognizedEmotion(List<UserRecognizedEmotion> objListUserRecognizedEmotion) {
        this.objListUserRecognizedEmotion = objListUserRecognizedEmotion;
    }

    /**
     * @return the objListUserRecognizedHLC
     */
    public List<UserRecognizedHLC> getObjListUserRecognizedHLC() {
        return objListUserRecognizedHLC;
    }

    /**
     * @param objListUserRecognizedHLC the objListUserRecognizedHLC to set
     */
    public void setObjListUserRecognizedHLC(List<UserRecognizedHLC> objListUserRecognizedHLC) {
        this.objListUserRecognizedHLC = objListUserRecognizedHLC;
    }

    /**
     * @return the objListFoodLog
     */
    public List<FoodLog> getObjListFoodLog() {
        return objListFoodLog;
    }

    /**
     * @param objListFoodLog the objListFoodLog to set
     */
    public void setObjListFoodLog(List<FoodLog> objListFoodLog) {
        this.objListFoodLog = objListFoodLog;
    }
    
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/AER/jh/jAudioPreProcessing.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Bang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.AER.jh;

import jAudioFeatureExtractor.AudioFeatures.LPC;
import jAudioFeatureExtractor.jAudioTools.AudioSamples;
import jAudioFeatureExtractor.jAudioTools.FFT;

import java.io.File;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;

public class jAudioPreProcessing {
	private double sampling_rate;
	
	public double[] getPowerSpectrum(AudioInputStream ais) throws Exception {
		double[] samples = preProcessRecording(ais);
		FFT fft = new FFT(samples, null, false, true);
		double[] result = fft.getPowerSpectrum();
		return result;
	}

	public double[] getLPC(AudioInputStream ais) throws Exception {
		double[] samples = preProcessRecording(ais);
		LPC lpc = new LPC();
		double[] result = lpc.extractFeature(samples, sampling_rate, null);
		return result;
	}

	public double[] getMagnitudeSpectrum(AudioInputStream ais) throws Exception {
		double[] samples = preProcessRecording(ais);
		FFT fft = new FFT(samples, null, false, true);
		double[] result = fft.getMagnitudeSpectrum();
		return result;
	}
	public double[] getRealValue(AudioInputStream ais) throws Exception {
		double[] samples = preProcessRecording(ais);
		FFT fft = new FFT(samples, null, false, true);
		double[] result = fft.getRealValues();
		return result;
	}
	private double[] preProcessRecording(AudioInputStream ais) throws Exception {
		ais.reset();
		// Get the original audio and its format
		AudioInputStream original_stream = ais;
		AudioFormat original_format = original_stream.getFormat();
		sampling_rate = original_format.getSampleRate();

		// Set the bit depth
		int bit_depth = original_format.getSampleSizeInBits();
		if (bit_depth != 8 && bit_depth != 16)
			bit_depth = 16;

		// If the audio is not PCM signed big endian, then convert it to PCM
		// signed
		// This is particularly necessary when dealing with MP3s
		AudioInputStream second_stream = original_stream;
		if (original_format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED
				|| original_format.isBigEndian() == false) {
			AudioFormat new_format = new AudioFormat(
					AudioFormat.Encoding.PCM_SIGNED,
					original_format.getSampleRate(), bit_depth,
					original_format.getChannels(),
					original_format.getChannels() * (bit_depth / 8),
					original_format.getSampleRate(), true);
			second_stream = AudioSystem.getAudioInputStream(new_format,
					original_stream);
		}

		// Convert to the set sampling rate, if it is not already at this
		// sampling rate.
		// Also, convert to an appropriate bit depth if necessary.
		AudioInputStream new_stream = second_stream;
		if (original_format.getSampleRate() != (float) sampling_rate
				|| bit_depth != original_format.getSampleSizeInBits()) {
			AudioFormat new_format = new AudioFormat(
					AudioFormat.Encoding.PCM_SIGNED,
					original_format.getSampleRate(), bit_depth,
					original_format.getChannels(),
					original_format.getChannels() * (bit_depth / 8),
					original_format.getSampleRate(), true);
			new_stream = AudioSystem.getAudioInputStream(new_format,
					second_stream);
		}

		// Extract data from the AudioInputStream
		AudioSamples audio_data = new AudioSamples(new_stream,
				"unique", false);
		
		
		
		// Normalise samples if this option has been requested
		/*if (normalise)
			audio_data.normalizeMixedDownSamples();*/

		// Return all channels compressed into one
		return audio_data.getSamplesMixedDown();
		//return audio_data.normalizeMixedDownSamples();

	}

}


<|start_filename|>knowledge-curation-layer/i-kat/src/main/webapp/WEB-INF/views/Login.jsp<|end_filename|>
<!--
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

-->	
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link href="${pageContext.request.contextPath}/resources/css/bootstrap.min.css" rel="stylesheet">
	<link href="${pageContext.request.contextPath}/resources/css/bootstrap-responsive.min.css" rel="stylesheet">
	<link href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600" rel="stylesheet">
	<link href="${pageContext.request.contextPath}/resources/css/font-awesome.css" rel="stylesheet">
	<link href="${pageContext.request.contextPath}/resources/css/style.css" rel="stylesheet">
	<link href="${pageContext.request.contextPath}/resources/css/pages/dashboard.css" rel="stylesheet">
	<link href="${pageContext.request.contextPath}/resources/css/pages/signin.css" rel="stylesheet" type="text/css">
	<link href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600" rel="stylesheet">
        <title>User Login</title>
    </head>
    <body>
        <div class="navbar navbar-fixed-top">
		<div class="navbar-inner">
		<div class="container">
			<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
				<span class="icon-bar"></span>
				<span class="icon-bar"></span>
				<span class="icon-bar"></span>
			</a>
			 <a class="brand" href="#"> <img src="${pageContext.request.contextPath}/resources/images/MMlogo.png" /> &nbsp;Expert-Driven Intelligent Knowledge Authoring Tool</a>
			<div class="nav-collapse">
				<ul class="nav pull-right">
					<li class="">						
						<a href="#" class="">
							Don't have an account?
						</a>
					</li>
					<li class="">						
						<a href="#" class="">
							<i class="icon-chevron-left"></i>
							Back to Homepage
						</a>
					</li>
				</ul>
			</div><!--/.nav-collapse -->	
		</div> <!-- /container -->
	</div> <!-- /navbar-inner -->
</div> <!-- /navbar -->
        <div class="account-container">
		<div class="content clearfix">
			<c:url var="addAction" value="/user/validate" ></c:url>
        	<form:form method="post" action="${addAction}" name="login" commandName="user">
			<h1>Member Login</h1>		
			<div class="login-fields">
				<p>Please provide your details</p>
				<div class="field">
					<input type="text" id="loginID" name="loginID" value="" placeholder="login ID" class="login username-field" />
				</div> <!-- /field -->
				<div class="field">
					<input type="password" id="password" name="password" value="" placeholder="Password" class="login password-field" />
				</div> <!-- /password -->
				<div style="color:red">${error}</div>
			</div> <!-- /login-fields -->
			<div class="login-actions">
				<span class="login-checkbox">
					<input id="Field" name="Field" type="checkbox" class="field login-checkbox" value="First Choice" tabindex="4" />
					<label class="choice" for="Field">Keep me signed in</label>
				</span>
				<input type="submit" value="Login" class='btn btn-lg btn-primary addnewrow pull-right mBottom' />
			</div> <!-- .actions -->
			</form:form>
	</div> <!-- /content -->
</div> <!-- /account-container -->
<div class="login-extra">
	<a href="#">Reset Password</a>
</div> <!-- /login-extra -->
</body>
</html>

<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/objectmodel/SituationEvents.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */
package org.uclab.mm.dcl.llm.objectmodel;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * This class is to manage the multiple complex object model which may consist of list of object.
 * @author Rizvi
 */
@XmlRootElement()
public class SituationEvents implements Serializable{

  private List<SituationEvent> listSEvents = new ArrayList<SituationEvent>();

  /**
   * This method is used to get the object from the list of objects. 
   * @return the listSEvents
   */
  public List<SituationEvent> getListSEvents(){
    return listSEvents;
  }

  /**
   * This method is used to set the object in the list of objects. 
   * Set the values of situations that need to be monitored and monitored from the Lifelog.
   * @param listSEvents the listSEvents to set
   */
  public void setListSEvents(List<SituationEvent> listSEvents){
    this.listSEvents = listSEvents;
  }
}


<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/test/java/org/uclab/mm/dcl/llm/monitoring/PhysicalActivityMonitorTest.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */
package org.uclab.mm.dcl.llm.monitoring;

import java.sql.Connection;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
import org.uclab.mm.dcl.llm.objectmodel.FoodLog;
import org.uclab.mm.dcl.llm.objectmodel.SituationLog;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.uclab.mm.dcl.llm.dataaccess.DBConnection;
import org.uclab.mm.dcl.llm.exception.DatabaseConnectionProblem;

/**
 *This class is used to define test cases for monitoring the physical activities.
 * @author Rizvi
 */
public class PhysicalActivityMonitorTest{
  
  public PhysicalActivityMonitorTest(){
  }
  
  @BeforeClass
  public static void setUpClass(){
  }
  
  @AfterClass
  public static void tearDownClass(){
  }
  
  @Before
  public void setUp(){
  }
  
  @After
  public void tearDown(){
  }

  /**
   * Test of doMonitor method, of class PhysicalActivityMonitor.
   */
  @Test//(expected=RuntimeException.class)
  public void testDoMonitor_Connection_String()throws Exception
  {
    
    try{
   
    System.out.println("doMonitor");
    Connection conn = DBConnection.getDBConnection().getConnection();
    String a = "";
    PhysicalActivityMonitor instance = new PhysicalActivityMonitor();
    instance.doMonitor(conn, a);
    }
    catch(Exception e)
    {
      System.out.println(e.getMessage());
    }
  }

    /**
   * Test of doMonitor method, of class PhysicalActivityMonitor.
   */
  @Test
  public void testDoMonitor_Connection_String2()throws Exception
  {
    
    try{
   
    System.out.println("doMonitor");
    Connection conn = DBConnection.getDBConnection().getConnection();
    String a = "";
    PhysicalActivityMonitor instance = new PhysicalActivityMonitor();
    instance.doMonitor(conn, a);
    }
    catch(Exception e)
    {
      System.out.println(e.getMessage());
    }
  }
    
  
}

 

 


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/communication/ConditionsValueService.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.communication;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

public class ConditionsValueService {
  private static Logger LOG = LogManager.getRootLogger();
  
  /**
   * Reads and Returns file contents
   * 
   * @param filePath
   * @return file contents
   */
  public static String readFromFile(String filePath) {
    BufferedReader br = null;
    StringBuilder ruleBuilder = new StringBuilder();
    try {
      br = new BufferedReader(new FileReader(filePath));
      String line = null;
      while ((line = br.readLine()) != null) {
        line = line.trim();
        if (line.isEmpty() || line.startsWith("#")) {
          continue;
        }
        ruleBuilder.append(line);
      }
    } catch (IOException ioex) {
      LOG.error(ioex.getMessage());
    } finally {
      try {
        br.close();
      } catch (IOException iox) {
        LOG.error(iox.getMessage());
      }
    }
    return ruleBuilder.toString();
  }
  
  /**
   * parse file contents into HashMap object
   * 
   * @param filePath
   * @return HashMap
   */
  public static Map<String, Object> parse(String filePath) {
    String response = readFromFile(filePath);
    Map<String, Object> facts = null;
    ObjectMapper mapper = new ObjectMapper();
    try {
      facts = mapper.readValue(response, new TypeReference<HashMap<String, Object>>() {});
    } catch (Exception e) {
      e.printStackTrace();
    }
    return facts;
  }
  /**
   * 
   * @param parse string into json format
   * 
   * @param format
   * @return HashMap
   */
  public static Map<String, Object> parse(String text, int format) {
    Map<String, Object> keyValueConditions = null;
    if (format == 1) {
      ObjectMapper mapper = new ObjectMapper();
      try {
        keyValueConditions = mapper.readValue(text, new TypeReference<HashMap<String, Object>>() {});
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return keyValueConditions;
  }
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/test/java/mm/icl/hlc/ContextOntologyManager/ContextQueryHLCRetrievalTest.java<|end_filename|>
package mm.icl.hlc.ContextOntologyManager;

import static org.junit.Assert.*;

import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;

import mm.icl.hlc.ContextOntologyManager.ContextHandler;
import mm.icl.hlc.ContextOntologyManager.ContextOntologyManager;
import mm.icl.hlc.OntologyTools.Context;
import mm.icl.hlc.OntologyTools.LowLevelContext;




import org.junit.Test;

public class ContextQueryHLCRetrievalTest {
	static final String directory ="E:\\ICL_LOG\\TDB";         
	
	static final String sparqlQueryHlc = 
			"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> "
			+ "PREFIX owl: <http://www.w3.org/2002/07/owl#> "
			+ "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> "
			+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "
			+ "PREFIX icl2: <http://www.miningminds.re.kr/icl/context/context-v2-5.owl#> "
			+ "SELECT ?hlc "
			+ "WHERE { "
			+ "?hlc rdf:type icl2:PhysicalActivityContext. "
			+ "}";
			
		public static void main(String[] args) {

	}
	@Test
	public final void test() {

		ContextOntologyManager mng = new ContextOntologyManager(directory);
		
		if(mng.correctInitialization()) {
		
			Iterator<Context> it = ContextHandler.retrieveContextInstancesMatchingSparqlQuery(sparqlQueryHlc).iterator();
	
			
			while(it.hasNext()) {
				
				System.out.println("------------------------");
				
				Context inst = it.next();
				
//				inst.getCtxModel().write(System.out, "RDF/XML");
				inst.getCtxModel().write(System.out, "Turtle");
				
				
			}

		}
		else  {
			System.out.println("No HLC because there are no LLC _________");
		}
	
	}

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/ic/dataadapter/DeviceAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.ic.dataadapter;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.dc.Users;
import org.uclab.mm.datamodel.ic.Device;
/**
 * This is DeviceAdapter class which implements the Data Access Interface for CRUD operations
 * @author Taqdir
 */
public class DeviceAdapter implements  DataAccessInterface{

     private Connection objConn;
     private static final Logger logger = LoggerFactory.getLogger(DeviceAdapter.class);
    public DeviceAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving Device. 
     * @param objDevice
     * @return List of String
     */
    @Override
    public List<String> Save(Object objDevice) {
        Device objInnerDevice = new Device();
        objInnerDevice =  (Device) objDevice;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_Device(?, ?, ?, ?, ?)}");
            
            objCallableStatement.setString("DeviceName", objInnerDevice.getDeviceName());
            objCallableStatement.setInt("DeviceTypeID", objInnerDevice.getDeviceTypeId());
            objCallableStatement.setString("DeviceModel", objInnerDevice.getDeviceModel());
            
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
             Date dtRegistrationDate = sdf.parse(objInnerDevice.getRegistrationDate());
            
            
            
            Timestamp tsRegistrationDate = new Timestamp(dtRegistrationDate.getYear(),dtRegistrationDate.getMonth(), dtRegistrationDate.getDate(), 00, 00, 00, 00);
            objCallableStatement.setTimestamp("RegistrationDate", tsRegistrationDate);
            
            objCallableStatement.registerOutParameter("DeviceID", Types.BIGINT);
            objCallableStatement.execute();
            
            int intDeviceID = objCallableStatement.getInt("DeviceID");
            objDbResponse.add(String.valueOf(intDeviceID));
            objDbResponse.add("No Error");
            
            objConn.close();
            logger.info("Device saved successfully, Device Details="+objDevice);
        }
        catch (Exception e)
        {
        	logger.info("Error in registring Device");
        	objDbResponse.add("Error in registering Device");
        }   
        
        return objDbResponse;
    }

    /**
     * This is implementation function for updating Device. 
     * @param objDevice
     * @return List of String
     */
    @Override
    public List<String> Update(Object objDevice) {
        Device objInnerDevice = new Device();
        objInnerDevice =  (Device) objDevice;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_Device(?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("DeviceID", objInnerDevice.getDeviceId());
            objCallableStatement.setString("DeviceName", objInnerDevice.getDeviceName());
            objCallableStatement.setInt("DeviceTypeID", objInnerDevice.getDeviceTypeId());
            objCallableStatement.setString("DeviceModel", objInnerDevice.getDeviceModel());
            
             SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
             Date dtRegistrationDate = sdf.parse(objInnerDevice.getRegistrationDate());
            
            Timestamp tsRegistrationDate = new Timestamp(dtRegistrationDate.getYear(),dtRegistrationDate.getMonth(), dtRegistrationDate.getDate(), 00, 00, 00, 00);
            objCallableStatement.setTimestamp("RegistrationDate", tsRegistrationDate);
           
            objCallableStatement.execute();
            
            objDbResponse.add(String.valueOf(objInnerDevice.getDeviceId()));
            objDbResponse.add("No Error");
            
            objConn.close();
            logger.info("Device updated successfully, Device Details="+objDevice);
        }
        catch (Exception e)
        {
        	logger.info("Error in updated Device");
        	objDbResponse.add("Error in updated Device");
        }   
        
        return objDbResponse;
    }

    /**
     * This is implementation function for retrieving Device. 
     * @param objDevice
     * @return List of String
     */
    @Override
    public List<Device> RetriveData(Object objDevice) {
        
        Device objOuterDevice = new Device();
        List<Device> objListInnerDevice = new ArrayList<Device>();
        objOuterDevice =  (Device) objDevice;
        
        try
        {
            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_DeviceByID(?)}");
            objCallableStatement.setLong("DeviceID", objOuterDevice.getDeviceId());
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                Device objInnerDevice = new Device();
                objInnerDevice.setDeviceId(objResultSet.getLong("DeviceID"));
                objInnerDevice.setDeviceName(objResultSet.getString("DeviceName"));
                objInnerDevice.setDeviceTypeId(objResultSet.getInt("DeviceTypeID"));
                objInnerDevice.setDeviceModel(objResultSet.getString("DeviceModel"));
                
                if(objResultSet.getTimestamp("RegistrationDate") != null)
                {
                    Timestamp tsRegistrationDate = objResultSet.getTimestamp("RegistrationDate");// updated
                    objInnerDevice.setRegistrationDate(tsRegistrationDate .toString()); // updated
                }
                else
                {
                    objInnerDevice.setRegistrationDate(null);
                }
                objListInnerDevice.add(objInnerDevice);
            }
            objConn.close();
            logger.info("Device loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in Device loadeding");
        }   
        return objListInnerDevice;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet."); 
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sl/HashClass.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.sl;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

/**
 *
 * @author Taqdir
 */
public class HashClass {
    protected static String hashinput;
    /**
     * The constructor of HashClass will take user id and device id and combine
     * it with current time stamp to generate unique input for hash function
     * @param uid user id
     * @param deviceid  device id
     */
     HashClass(String uid, String deviceid){
      String timestamp=Long.toString(System.currentTimeMillis());
       hashinput=uid+deviceid+timestamp;  
    }
    public HashClass(String uid){
      String timestamp=Long.toString(System.currentTimeMillis());
       hashinput=uid+timestamp;  
    }
    /**
     * 
     * @return  String value of SHA1 
     */
    
    
    public static String getHashSha1()
{
    //String timestamp=Long.toString(System.currentTimeMillis());
    //String hash_function_input=uid+deviceid+timestamp;
    String sha1 = "";
    try
    {
        MessageDigest crypt = MessageDigest.getInstance("SHA-1");
        crypt.reset();
        crypt.update(hashinput.getBytes("UTF-8"));
        sha1 = byteToHex(crypt.digest());
    }
    catch(NoSuchAlgorithmException e)
    {
        e.printStackTrace();
    }
    catch(UnsupportedEncodingException e)
    {
        e.printStackTrace();
    }
    return sha1;
}

private static String byteToHex(final byte[] hash)
{
    Formatter formatter = new Formatter();
    for (byte b : hash)
    {
        formatter.format("%02x", b);
    }
    String result = formatter.toString();
    formatter.close();
    return result;
}
//***********************
public String getHashMD5() {
        byte[] source;
        try {
            //Get byte according by specified coding.
            source = hashinput.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            source = hashinput.getBytes();
        }
        String MD5result = null;
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7',
                '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(source);
            //The result should be one 128 integer
            byte temp[] = md.digest();
            char str[] = new char[16 * 2];
            int k = 0;
            for (int i = 0; i < 16; i++) {
                byte byte0 = temp[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            MD5result = new String(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return MD5result;
    }
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/AER/jh/AERClassification.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Bang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.AER.jh;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import org.uclab.mm.icl.llc.LLCManager.ContextLabel;
import org.uclab.mm.icl.llc.MachineLearningTools.ExtClassification;
import org.uclab.mm.icl.llc.MachineLearningTools.classification.Classification;

import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.core.Attribute;
import weka.core.FastVector;
import weka.core.Instance;
import weka.core.Instances;
/**
 * This Class build the MMv2.5 Audio based ER predictive model by all of classifier from weka library
 * @author <NAME>
 *
 */
public class AERClassification extends Classification<double[]> {
	ExtClassification ec;

	
	@Override
	public String Classify(double[] data) {
		// TODO Auto-generated method stub
		//result = getEmotion(learningDataset, predictiveModel, data);
		return "NoEmotion";
	}
	/**
	 * classify Emotion
	 * @param data
	 * @return int
	 */
	public int classifyEmotion(double[] data) {
		int result = 0;
		try {
			result = ec.classify(data);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * set training data path, features information, labels and classifier
	 * @param filename
	 * @param FEATURES_NUM
	 * @param label
	 * @param classifier
	 */
	public AERClassification(String filename, int FEATURES_NUM, String[] labels, Classifier classifier ) {
		ec = new ExtClassification(filename, FEATURES_NUM, labels, classifier);
	}
	

}


<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/test/java/org/uclab/mm/dcl/llm/monitoring/NutritionMonitorTest.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */
package org.uclab.mm.dcl.llm.monitoring;

import java.sql.Connection;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.uclab.mm.dcl.llm.objectmodel.FoodLog;
import org.uclab.mm.dcl.llm.objectmodel.SituationLog;
import org.uclab.mm.dcl.llm.objectmodel.SituationNotification;

/**
 * This class is used to define test cases for monitoring the nutrition.
 * @author Rizvi
 */
public class NutritionMonitorTest{
  
  public NutritionMonitorTest(){
  }
  
  @BeforeClass
  public static void setUpClass(){
  }
  
  @AfterClass
  public static void tearDownClass(){
  }
  
  @Before
  public void setUp(){
  }
  
  @After
  public void tearDown(){
  }

  /**
   * Test of doMonitor method, of class NutritionMonitor for null values.
   * This method is used to  
   */
 @Test
  public void testDoMonitor_Connection_String() throws Exception{
    System.out.println("doMonitor");
    Connection dbConn = null;
    String a = "";
    NutritionMonitor instance = new NutritionMonitor();
    instance.doMonitor(dbConn, a);

  }

  /**
   * Test of doMonitor method, of class NutritionMonitor for initial value of food.
   */
  @Test
  public void testDoMonitor_FoodLog(){
    System.out.println("doMonitor");
    FoodLog ObjFoodLog=new FoodLog();
    Long a=35L;
    String b="Chicken";
     ObjFoodLog.setUserId(a);
      ObjFoodLog.setFoodName(b);
    NutritionMonitor instance = new NutritionMonitor();
    instance.doMonitor(ObjFoodLog);

  }


    /**
   * Test of doMonitor method, of class NutritionMonitor for incremental value of food.
   */
  @Test
  public void testDoMonitor_FoodLog1(){
    System.out.println("doMonitor");
    FoodLog ObjFoodLog=new FoodLog();
    Long a=35L;
    String b="Chicken";
     ObjFoodLog.setUserId(a);
      ObjFoodLog.setFoodName(b);
    NutritionMonitor instance = new NutritionMonitor();
    instance.doMonitor(ObjFoodLog);
    }
  
    /**
   * Test of doMonitor method, of class NutritionMonitor for incremental value of food.
   */
  @Test
  public void testDoMonitor_FoodLog2(){
    System.out.println("doMonitor");
    FoodLog ObjFoodLog=new FoodLog();
    Long a=35L;
    String b="Chicken";
     ObjFoodLog.setUserId(a);
      ObjFoodLog.setFoodName(b);
    NutritionMonitor instance = new NutritionMonitor();
    instance.doMonitor(ObjFoodLog);

  }
  
  /**
   * Test of doMonitor method, of class NutritionMonitor for incremental value of food.
   */
  @Test
  public void testDoMonitor_FoodLog3(){
    System.out.println("doMonitor");
    FoodLog ObjFoodLog=new FoodLog();
    Long a=35L;
    String b="Chicken";
     ObjFoodLog.setUserId(a);
      ObjFoodLog.setFoodName(b);
    NutritionMonitor instance = new NutritionMonitor();
    instance.doMonitor(ObjFoodLog);
    
  }
  
  /**
   * Test of getNotificationMessage method, of class NutritionMonitor for threshold value of nutrition.
   */
  @Test(expected=java.lang.AssertionError.class)
  public void testGetNotificationMessage(){
    System.out.println("getNotificationMessage");
    String MapId = "651";
    String UserId = "35";
    String ConsumedFat = "85";
    NutritionMonitor instance = new NutritionMonitor();
    SituationNotification expResult = null;
    SituationNotification result = instance.getNotificationMessage(MapId, UserId, ConsumedFat);
    assertEquals(expResult, result);
  }
   
}










<|start_filename|>information-curation-layer/high-level-context-awareness/src/test/java/mm/hlca/HLCAMapperTest.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.hlca;

import static org.junit.Assert.*;
import java.util.Calendar;
import mm.icl.hlc.ContextOntologyManager.ContextOntologyManager;
import mm.icl.hlc.HLC.TimeUtil;
import mm.icl.hlc.HLCBuilder.ContextMapper; 
import org.apache.log4j.Logger;
import org.junit.Test;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.ModelFactory;

public class HLCAMapperTest {

	@Test
	public final void testMain() {
		// input parameter for all 3 variables
		final  Logger logger = Logger.getLogger(TestHLCAMapper.class);

		 final String directory ="E:\\ICL_LOG\\TDB"; 		                  	             
		 final String ontologyFile = "file:////E:/ICL_LOG/TDB/context-v2-5.owl";             
		 final String llcLabel = "Cake";     // Give the Low Level Contexts here as per Ontology
		 final String userId = "9735";

		 	OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);
			ontModel.read(ontologyFile);
			ContextOntologyManager mng = new ContextOntologyManager(directory, ontModel);
			TimeUtil util = new TimeUtil();
			
			try{
			if (mng.correctInitialization()) {
				ContextMapper mapper = new ContextMapper(mng.getContextOntology());

				  Calendar cal = util.parseString("2016 04 18 10:11:25"); 
				  mapper.mapLLC(llcLabel, userId, cal);                   
	}
			} catch (Exception e) {
				logger.error("[Context Mapper] LLC could not be mapped. " + llcLabel + " is not a valid label.");
				e.printStackTrace();
				fail("[Context Mapper] LLC could not be mapped. " + llcLabel + " is not a valid label."); // TODO
			}
	}

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/MMDataCurationRestfulService/src/main/java/org/uclab/mm/rs/supportinglayer/SupportingLayerResource.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.rs.supportinglayer;

import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.AbstractDataBridge;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.DatabaseStorage;
import org.uclab.mm.datamodel.sl.ActivityFeedback;
import org.uclab.mm.datamodel.sl.ExpertReview;
import org.uclab.mm.datamodel.sl.FactsFeedback;
import org.uclab.mm.datamodel.sl.RecommendationFeedback;
import org.uclab.mm.datamodel.sl.dataadapter.ActivityFeedbackAdapter;
import org.uclab.mm.datamodel.sl.dataadapter.ExpertReviewAdapter;
import org.uclab.mm.datamodel.sl.dataadapter.FactsFeedbackAdapter;
import org.uclab.mm.datamodel.sl.dataadapter.RecommendationFeedbackAdapter;
import org.uclab.mm.rs.datacuration.DataCurationResource;

/**
 * REST Web Service
 *
 * @author <NAME>
 */
@Path("SupportingLayer")
public class SupportingLayerResource {

    @Context
    private UriInfo context;

    /**
     * Creates a new instance of SupportingLayerResource
     */
    public SupportingLayerResource() {
    }

    private static final Logger logger = LoggerFactory.getLogger(DataCurationResource.class);
    
    /**
     * This function is using to Add Recommendation Feedback
     * @param objOuterRecommendationFeedback
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddRecommendationFeedback")
    public List<String> AddRecommendationFeedback(RecommendationFeedback objOuterRecommendationFeedback) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new RecommendationFeedbackAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveRecommendationFeedback(objOuterRecommendationFeedback);
            logger.info("Recommendation Feedback saved successfully, Recommendation Feedback Details="+objOuterRecommendationFeedback);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Recommendation Feedback");
        	response.add("Error in adding Recommendation Feedback");
        }
        return response;
    }
    
    /**
     * This function is using to Update Recommendation Feedback
     * @param objOuterRecommendationFeedback
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UpdateRecommendationFeedback")
    public List<String> UpdateRecommendationFeedback(RecommendationFeedback objOuterRecommendationFeedback) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new RecommendationFeedbackAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.UpdateRecommendationFeedback(objOuterRecommendationFeedback);
            logger.info("Recommendation Feedback updated successfully, Recommendation Feedback Details="+objOuterRecommendationFeedback);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating Recommendation Feedback");
        	response.add("Error in updating Recommendation Feedback");
        }
        return response;
    }
    
    /**
     * This function is using to Retrieves Recommendation Feedback by RecommendationID 
     * @param RecommendationID
     * @return an instance of list of RecommendationFeedback
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("RecommendationFeedback/{RecommendationID}")
    public List<RecommendationFeedback> RetrieveRecommendationFeedbackByRecommendationID(@PathParam ("RecommendationID") String RecommendationID) {
        RecommendationFeedback objOuterRecommendationFeedback = new RecommendationFeedback();
        List<RecommendationFeedback> objListRecommendationFeedback = new  ArrayList<RecommendationFeedback>();
        try
        {
            objOuterRecommendationFeedback.setRecommendationID(Long.parseLong(RecommendationID));
            objOuterRecommendationFeedback.setRequestType("ByRecommendationID");
            DataAccessInterface objDAInterface = new RecommendationFeedbackAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListRecommendationFeedback = objADBridge.RetriveRecommendationFeedback(objOuterRecommendationFeedback);
            logger.info("Recommendation Feedback loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Recommendation Feedback");
        }
        
        return objListRecommendationFeedback;
    }
    
    /**
     * This function is using to Retrieves Recommendation Feedback by UserID 
     * @param UserID
     * @return an instance of list of RecommendationFeedback
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("RecommendationFeedbackByUserID/{UserID}")
    public List<RecommendationFeedback> RetrieveRecommendationFeedbackByUserID(@PathParam ("UserID") String UserID) {
        RecommendationFeedback objOuterRecommendationFeedback = new RecommendationFeedback();
        List<RecommendationFeedback> objListRecommendationFeedback = new  ArrayList<RecommendationFeedback>();
        try
        {
            objOuterRecommendationFeedback.setUserID(Long.parseLong(UserID));
            objOuterRecommendationFeedback.setRequestType("ByUserID");
            DataAccessInterface objDAInterface = new RecommendationFeedbackAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListRecommendationFeedback = objADBridge.RetriveRecommendationFeedback(objOuterRecommendationFeedback);
            logger.info("Recommendation Feedback loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Recommendation Feedback");
        }
        
        return objListRecommendationFeedback;
    }
    
    /**
     * This function is using to Add Activity Feedback
     * @param objOuterActivityFeedback
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddActivityFeedback")
    public List<String> AddActivityFeedback(ActivityFeedback objOuterActivityFeedback) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new ActivityFeedbackAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveActivityFeedback(objOuterActivityFeedback);
            logger.info("Activity Feedback saved successfully, Activity Feedback Details="+objOuterActivityFeedback);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Activity Feedback");
        	response.add("Error in adding Activity Feedback");
        }
        return response;
    }
    
    /**
     * This function is using to Update Activity Feedback
     * @param objOuterActivityFeedback
     * @return a list of object string with "Error", "No Error" and updated ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UpdateActivityFeedback")
    public List<String> UpdateActivityFeedback(ActivityFeedback objOuterActivityFeedback) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new ActivityFeedbackAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.UpdateActivityFeedback(objOuterActivityFeedback);
            logger.info("Activity Feedback updated successfully, Activity Feedback Details="+objOuterActivityFeedback);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating Activity Feedback");
        	response.add("Error in updating Activity Feedback");
        }
        return response;
    }
    
    /**
     * This function is using to Retrieves Recommendation Feedback by Recognized Activity ID 
     * @param RecognizedActivityID
     * @return an instance of list of ActivityFeedback
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("ActivityFeedback/{RecognizedActivityID}")
    public List<ActivityFeedback> RetrieveActivityFeedbackByRecognizedActivityID(@PathParam ("RecognizedActivityID") String RecognizedActivityID) {
        ActivityFeedback objOuterActivityFeedback = new ActivityFeedback();
        List<ActivityFeedback> objListActivityFeedback = new  ArrayList<ActivityFeedback>();
        try
        {
            objOuterActivityFeedback.setRecognizedActivityID(Long.parseLong(RecognizedActivityID));
            objOuterActivityFeedback.setRequestType("ByRecognizedActivityID");
            DataAccessInterface objDAInterface = new ActivityFeedbackAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListActivityFeedback = objADBridge.RetriveActivityFeedback(objOuterActivityFeedback);
            logger.info("recommendation Feedback loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading recommendation Feedback");
        }
        
        return objListActivityFeedback;
    }
    
    /**
     * This function is using to Retrieves Recommendation Feedback by Recognized Activity ID 
     * @param UserID
     * @return an instance of list of ActivityFeedback
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("ActivityFeedbackByUserID/{UserID}")
    public List<ActivityFeedback> RetrieveActivityFeedbackByUserID(@PathParam ("UserID") String UserID) {
        ActivityFeedback objOuterActivityFeedback = new ActivityFeedback();
        List<ActivityFeedback> objListActivityFeedback = new  ArrayList<ActivityFeedback>();
        try
        {
            objOuterActivityFeedback.setUserID(Long.parseLong(UserID));
            objOuterActivityFeedback.setRequestType("ByUserID");
            DataAccessInterface objDAInterface = new ActivityFeedbackAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListActivityFeedback = objADBridge.RetriveActivityFeedback(objOuterActivityFeedback);
            logger.info("recommendation Feedback loaded successfully");
        }
        catch(Exception ex)
        { 
        	logger.info("Error in loading recommendation Feedback");
        }
        
        return objListActivityFeedback;
    }
    
    /**
     * This function is using to Add Expert Review
     * @param objOuterExpertReview
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddExpertReview")
    public List<String> AddExpertReview(ExpertReview objOuterExpertReview) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new ExpertReviewAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveExpertReview(objOuterExpertReview);
            logger.info("Expert Review saved successfully, Expert Review Details="+objOuterExpertReview);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Expert Review");
        	response.add("Error in adding Expert Review");
        }
        return response;
    }
    
    /**
     * This function is using to Update Expert Review
     * @param objOuterExpertReview
     * @return a list of object string with "Error", "No Error" and updated ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UpdateExpertReview")
    public List<String> UpdateExpertReview(ExpertReview objOuterExpertReview) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new ExpertReviewAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.UpdateExpertReview(objOuterExpertReview);
            logger.info("Expert Review updated successfully, Expert Review Details="+objOuterExpertReview);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating Expert Review");
        	response.add("Error in updating Expert Review");
        }
        return response;
    }
    
    /**
     * This function is using to Retrieves Expert Review by UserID 
     * @param UserID
     * @return an instance of list of ExpertReview
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("ExpertReview/{UserID}")
    public List<ExpertReview> RetrieveExpertReviewByUserID(@PathParam ("UserID") String UserID) {
        ExpertReview objOuterExpertReview = new ExpertReview();
        List<ExpertReview> objListExpertReview = new  ArrayList<ExpertReview>();
        objOuterExpertReview.setRequestType("ByUserID");
        try
        {
            objOuterExpertReview.setUserID(Long.parseLong(UserID));
            
            DataAccessInterface objDAInterface = new ExpertReviewAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListExpertReview = objADBridge.RetriveExpertReview(objOuterExpertReview);
            logger.info("Expert Review loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Expert Review");
        }
        
        return objListExpertReview;
    }
    
    /**
     * This function is using to Retrieves Expert review by userid, start time and end time
     * @param objOuterExpertReview
     * @return an instance of list of ExpertReview
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("GetExpertReviewByUserIDDateRange")
    public List<ExpertReview> GetFoodLogByUserIDDateRange(ExpertReview objOuterExpertReview) {
        
        List<ExpertReview> objListExpertReview = new ArrayList<ExpertReview>();
        String strResponse = "";
        objOuterExpertReview.setRequestType("ByUserAndDate");
        try
        {
            DataAccessInterface objDAInterface = new ExpertReviewAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListExpertReview = objADBridge.RetriveExpertReview(objOuterExpertReview);
            logger.info("Expert Review loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Expert Review");
        }
        
        return objListExpertReview;
    }
    
    /**
     * This function is using to Add Facts Feedback
     * @param objOuterFactsFeedback
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddFactsFeedback")
    public List<String> AddFactsFeedback(FactsFeedback objOuterFactsFeedback) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new FactsFeedbackAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveFactsFeedback(objOuterFactsFeedback);
            logger.info("Facts Feedback saved successfully, Facts Feedback Details="+objOuterFactsFeedback);
        }
        catch(Exception ex)
        {

        	logger.info("Error in adding Facts Feedback");
        	response.add("Error in adding Facts Feedback");
        }
        return response;
    }
    
    /**
     * This function is using to Update Facts Feedback
     * @param objOuterFactsFeedback
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UpdateFactsFeedback")
    public List<String> UpdateFactsFeedback(FactsFeedback objOuterFactsFeedback) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new FactsFeedbackAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.UpdateFactsFeedback(objOuterFactsFeedback);
            logger.info("Facts Feedback saved successfully, Facts Feedback Details="+objOuterFactsFeedback);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Facts Feedback");
        	response.add("Error in adding Facts Feedback");
        }
        return response;
    }
    
    /**
     * This function is using to Retrieves Facts Feedback by FactID 
     * @param FactID
     * @return an instance of list of FactsFeedback
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("FactsFeedback/{FactID}")
    public List<FactsFeedback> RetrieveFactsFeedbackByFactID(@PathParam ("FactID") String FactID) {
        FactsFeedback objOuterFactsFeedback = new FactsFeedback();
        List<FactsFeedback> objListFactsFeedback = new  ArrayList<FactsFeedback>();
        try
        {
            objOuterFactsFeedback.setFactID(Long.parseLong(FactID));
            objOuterFactsFeedback.setRequestType("ByFactID");
            DataAccessInterface objDAInterface = new FactsFeedbackAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListFactsFeedback = objADBridge.RetriveFactsFeedback(objOuterFactsFeedback);
            logger.info("Facts Feedback loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Facts Feedback");
        }
        
        return objListFactsFeedback;
    }
    /**
     * This function is using to Retrieves Facts Feedback by FactID 
     * @param UserID
     * @return an instance of list of FactsFeedback
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("FactsFeedbackByUserID/{UserID}")
    public List<FactsFeedback> RetrieveFactsFeedbackByUserID(@PathParam ("UserID") String UserID) {
        FactsFeedback objOuterFactsFeedback = new FactsFeedback();
        List<FactsFeedback> objListFactsFeedback = new  ArrayList<FactsFeedback>();
        try
        {
            objOuterFactsFeedback.setUserID(Long.parseLong(UserID));
            objOuterFactsFeedback.setRequestType("ByUserID");
            DataAccessInterface objDAInterface = new FactsFeedbackAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListFactsFeedback = objADBridge.RetriveFactsFeedback(objOuterFactsFeedback);
            logger.info("Facts Feedback loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Facts Feedback");
        }
        
        return objListFactsFeedback;
    }
    
}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/datamodel/SituationEvent.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.datamodel;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * 
 * @author Rizvi
 */
@XmlRootElement()
public class SituationEvent implements Serializable {
  private String SituationID;
  private Set<SituationConditions> ListSConditions = new HashSet<SituationConditions>();

  /**
   * @return the SituationID
   */
  public String getSituationID() {
    return SituationID;
  }

  /**
   * @param SituationID
   *          the SituationID to set
   */
  public void setSituationID(String SituationID) {
    this.SituationID = SituationID;
  }

  /**
   * @return the ListSConditions
   */
  public Set<SituationConditions> getListSConditions() {
    return ListSConditions;
  }

  /**
   * @param ListSConditions
   *          the ListSConditions to set
   */
  public void setListSConditions(Set<SituationConditions> ListSConditions) {
    this.ListSConditions = ListSConditions;
  }

  @Override
  public String toString() {
    String keyValue = "";

    for (SituationConditions sc : ListSConditions)
      keyValue += sc.toString() + ",\n";

    return keyValue;
  }

}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/AER/jh/ConvertAudioData.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Bang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.AER.jh;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.Vector;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;

/**
 * Convert the audio data between oInputStream to Byte
 * @author <NAME>
 *
 */
public class ConvertAudioData {

	/**
	 * convert byte to audioinputstream
	 * @param data
	 * @param audioFM
	 * @return
	 */
	public AudioInputStream convertAudioInputStream(byte[] data,
			AudioFormat audioFM) {
		AudioInputStream ais = null;
		if (data != null && audioFM != null) {
			InputStream is = convertInputStream(data);
			ais = new AudioInputStream(is, audioFM,
					(long) ((data.length) / audioFM.getFrameSize()));
		}
		return ais;
	}

	private InputStream convertInputStream(byte[] data) {
		InputStream is = null;
		if (data != null) {
			is = new ByteArrayInputStream(data);
		}
		return is;
	}

	/***
	 * convert audioinputstream to byte
	 * @param input
	 * @return
	 */
	public byte[] convertByteBuffer(AudioInputStream input) {
		byte[] temp = null;
		if (input != null) {
			temp = new byte[(int) (input.getFrameLength() * input
					.getFormat().getFrameSize())];
			try {
				input.read(temp);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return temp;
	}
	
	/**
	 * convert array byte to byte
	 * @param input
	 * @return
	 */
	public byte[] convertByteBuffer(Vector<byte[]> input){
		byte[] temp = new byte[input.size()*input.get(0).length];
		int cnt = 0;
		for(int i=0; i<input.size(); i++){
			for(int j=0; j<input.get(i).length; j++){
				temp[cnt++] = input.get(i)[j];
			}
		}
		return temp;
	}
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/dataadapter/ActivityRecommendationAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.sc.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.sc.ActivityPlan;
import org.uclab.mm.datamodel.sc.ActivityRecommendation;

/**
 * This is ActivityRecommendationAdapter class which implements the Data Access Interface for CRUD operations
 * @author Taqdir
 */
public class ActivityRecommendationAdapter implements DataAccessInterface {

    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(ActivityRecommendationAdapter.class);
    public ActivityRecommendationAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving ActivityRecommendation. 
     * @param objActivityRecommendation
     * @return List of String
     */
    @Override
    public List<String> Save(Object objActivityRecommendation) {
        ActivityRecommendation objInnerActivityRecommendation = new ActivityRecommendation();
        objInnerActivityRecommendation =  (ActivityRecommendation) objActivityRecommendation;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_ActivityRecommendation(?, ?, ?, ?)}");
            
            objCallableStatement.setLong("ActivityPlanID", objInnerActivityRecommendation.getActivityPlanId());
            objCallableStatement.setString("Description", objInnerActivityRecommendation.getDescription());
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
            Date dtTimestamp = sdf.parse(objInnerActivityRecommendation.getTimestamp());
            Timestamp tsTimestamp = new Timestamp(dtTimestamp.getYear(),dtTimestamp.getMonth(), dtTimestamp.getDate(), dtTimestamp.getHours(), dtTimestamp.getMinutes(), dtTimestamp.getSeconds(), 00);
            objCallableStatement.setTimestamp("Timestamp", tsTimestamp);
                                   
            objCallableStatement.registerOutParameter("ActivityRecommendationID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intActivityRecommendationID = objCallableStatement.getLong("ActivityRecommendationID");
            objDbResponse.add(String.valueOf(intActivityRecommendationID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Activity Recommendation saved successfully, Activity Recommendation Details="+objActivityRecommendation);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding Activity Recommendation");
        	objDbResponse.add("Error in adding Activity Recommendation");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for Update ActivityRecommendation. 
     * Not implemented
     */
    @Override
    public <T> List<String> Update(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet."); 
    }

    /**
     * This is implementation function for retrieving ActivityRecommendation. 
     * @param objActivityRecommendation
     * @return List of ActivityRecommendation
     */
    @Override
    public List<ActivityRecommendation> RetriveData(Object objActivityRecommendation) {
        ActivityRecommendation objOuterActivityRecommendation = new ActivityRecommendation();
        List<ActivityRecommendation> objListInnerActivityRecommendation = new ArrayList<ActivityRecommendation>();
        objOuterActivityRecommendation =  (ActivityRecommendation) objActivityRecommendation;
        
        try
        {
            CallableStatement objCallableStatement = null;
            if(objOuterActivityRecommendation.getRequestType() == "ByPlan")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_ActivityRecommendationByActivityPlanID(?)}");
                objCallableStatement.setLong("ActivityPlanID", objOuterActivityRecommendation.getActivityPlanId());
            }
            else if(objOuterActivityRecommendation.getRequestType() == "ByUserDate")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_ActivityRecommendationByUserDate(?, ?, ?)}");
                objCallableStatement.setLong("UserID", objOuterActivityRecommendation.getUserID());
                
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
            
                Date dtStartTimeStamp = sdf.parse(objOuterActivityRecommendation.getStartTimestamp());
                Timestamp tsStartTimeStamp = new Timestamp(dtStartTimeStamp.getYear(),dtStartTimeStamp.getMonth(), dtStartTimeStamp.getDate(), dtStartTimeStamp.getHours(), dtStartTimeStamp.getMinutes(), dtStartTimeStamp.getSeconds(), 00);
                objCallableStatement.setTimestamp("StartTimeStamp", tsStartTimeStamp);

                Date dtEndTimeStamp = sdf.parse(objOuterActivityRecommendation.getEndTimestamp());
                Timestamp tsEndTimeStamp = new Timestamp(dtEndTimeStamp.getYear(),dtEndTimeStamp.getMonth(), dtEndTimeStamp.getDate(), dtEndTimeStamp.getHours(), dtEndTimeStamp.getMinutes(), dtEndTimeStamp.getSeconds(), 00);
                objCallableStatement.setTimestamp("EndTimeStamp", tsEndTimeStamp);
                
            }
            
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                ActivityRecommendation objInnerActivityRecommendation = new ActivityRecommendation();
                objInnerActivityRecommendation.setActivityRecommendationId(objResultSet.getLong("ActivityRecommendationID"));
                objInnerActivityRecommendation.setActivityPlanId(objResultSet.getLong("ActivityPlanID"));
                objInnerActivityRecommendation.setDescription(objResultSet.getString("Description"));
                
                Timestamp tsTimestamp = objResultSet.getTimestamp("Timestamp"); //updated
                objInnerActivityRecommendation.setTimestamp(tsTimestamp.toString());
                objInnerActivityRecommendation.setPlanDescription(objResultSet.getString("PlanDescription"));
                
                objListInnerActivityRecommendation.add(objInnerActivityRecommendation);
            }
            objConn.close();
            logger.info("Activity Recommendation loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading Activity Recommendation");
        }   
        return objListInnerActivityRecommendation;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/hlca/TestHLCAMapper.java<|end_filename|>
/*
 * 
Copyright [2016] [name of copyright owner <-Put your name]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
package mm.hlca;
import java.util.Calendar;

import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.ModelFactory;

import mm.icl.hlc.ContextOntologyManager.ContextOntologyManager;
import mm.icl.hlc.HLC.TimeUtil;
import mm.icl.hlc.HLCBuilder.ContextMapper;
import mm.icl.hlc.HLCNotifier.HLCNotifier;


import org.apache.log4j.Logger;

public class TestHLCAMapper {
	final static Logger logger = Logger.getLogger(TestHLCAMapper.class);

	static final String directory ="E:\\ICL_LOG\\TDB"; 		                  	             
	static final String ontologyFile = "file:////E:/ICL_LOG/TDB/context-v3.owl";   //context-v2-5   context-v3-0             
	static final String llcLabel = "HypertensionStageII";   //NormalBG     
	static final String userId = "9735";

	public static void main(String[] args) {
		OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);
		ontModel.read(ontologyFile);
		ContextOntologyManager mng = new ContextOntologyManager(directory, ontModel);
		TimeUtil util = new TimeUtil();
		try{
		if (mng.correctInitialization()) {
			ContextMapper mapper = new ContextMapper(mng.getContextOntology());
			  Calendar cal = util.parseString("2016 04 18 10:11:59");           

		  mapper.mapLLC(llcLabel, userId, cal);
			  
				
			}
		
		} catch (Exception e) {
			logger.error("Error while Notifying HLC.  Message: " + e.getMessage());
			
			e.printStackTrace();
		}
	}
}

//
//long start = System.currentTimeMillis();
//datasetPath = cc.getBundleContext().getDataFile("Jena TDB Store").getAbsolutePath();
//dataset = TDBFactory.createDataset(datasetPath);
//long end = System.currentTimeMillis();
//logger.info("Dataset restored in " + (end - start) + " miliseconds");

















/*
 * package mm.hlca;
import java.util.Calendar;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import mm.icl.hlc.ContextOntologyManager.ContextOntologyManager;
import mm.icl.hlc.HLC.TimeUtil;
import mm.icl.hlc.HLCBuilder.ContextMapper;
public class TestHLCAMapper {
	static final String directory ="E:\\ICL_LOG\\TDB"; 		                  	             
	static final String ontologyFile = "file:////E:/ICL_LOG/TDB/context-v2-5.owl";             
	static final String llcLabel = "Salmon";                               //"Sitting";"Office" Boredom Office Happiness Mall
	static final String userId = "9735";
	//static final String startTime = "2015-08-10T11:25:50+09:00";
	public static void main(String[] args) {
		// READ THE CONTEXT ONTOLOGY FROM FILE
		OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);
		ontModel.read(ontologyFile);
		// CREATE THE CONTEXT ONTOLOGY MANAGER
		ContextOntologyManager mng = new ContextOntologyManager(directory, ontModel);
		TimeUtil util = new TimeUtil();
		if (mng.correctInitialization()) {
			// CREATE THE MAPPER
			ContextMapper mapper = new ContextMapper(mng.getContextOntology());
			// MAP LLC
			  Calendar cal = util.parseString("2016 04 18 10:11:25");                       //10:06:50  Calendar.getInstance();  //Asif (from DongUK)
			  mapper.mapLLC(llcLabel, userId, cal);                                         //Asif (from DongUK)
			//mapper.mapLLC(llcLabel, userId, startTime.);
		}
/*            ORignal
 * 
 *       	// CREATE THE MAPPER
			ContextMapper mapper = new ContextMapper(mng.getContextOntology());
			// MAP LLC
			//mapper.mapLLC(llcLabel, userId, startTime);
 * */
	

<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/Situation.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author <NAME>
 */
@Entity
public class Situation implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private long userID;
    private String situationCategoryDescription;
    private String situationDescription;
    private String situationDate;
    private Long situationID;
    private int situationCategoryID;
    private String requestType;
    private String startDate;
    private String endDate;
    private int timeInterval;
    

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Situation)) {
            return false;
        }
        Situation other = (Situation) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.sc.Situation[ id=" + id + " ]";
    }

    /**
     * @return the userID
     */
    public long getUserID() {
        return userID;
    }

    /**
     * @param userID the userID to set
     */
    public void setUserID(long userID) {
        this.userID = userID;
    }

    /**
     * @return the situationCategoryDescription
     */
    public String getSituationCategoryDescription() {
        return situationCategoryDescription;
    }

    /**
     * @param situationCategoryDescription the situationCategoryDescription to set
     */
    public void setSituationCategoryDescription(String situationCategoryDescription) {
        this.situationCategoryDescription = situationCategoryDescription;
    }

    /**
     * @return the situationDescription
     */
    public String getSituationDescription() {
        return situationDescription;
    }

    /**
     * @param situationDescription the situationDescription to set
     */
    public void setSituationDescription(String situationDescription) {
        this.situationDescription = situationDescription;
    }

    /**
     * @return the situationDate
     */
    public String getSituationDate() {
        return situationDate;
    }

    /**
     * @param situationDate the situationDate to set
     */
    public void setSituationDate(String situationDate) {
        this.situationDate = situationDate;
    }

    /**
     * @return the situationID
     */
    public Long getSituationID() {
        return situationID;
    }

    /**
     * @param situationID the situationID to set
     */
    public void setSituationID(Long situationID) {
        this.situationID = situationID;
    }

    /**
     * @return the situationCategoryID
     */
    public int getSituationCategoryID() {
        return situationCategoryID;
    }

    /**
     * @param situationCategoryID the situationCategoryID to set
     */
    public void setSituationCategoryID(int situationCategoryID) {
        this.situationCategoryID = situationCategoryID;
    }

    /**
     * @return the requestType
     */
    public String getRequestType() {
        return requestType;
    }

    /**
     * @param requestType the requestType to set
     */
    public void setRequestType(String requestType) {
        this.requestType = requestType;
    }

    /**
     * @return the startDate
     */
    public String getStartDate() {
        return startDate;
    }

    /**
     * @param startDate the startDate to set
     */
    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }

    /**
     * @return the endDate
     */
    public String getEndDate() {
        return endDate;
    }

    /**
     * @param endDate the endDate to set
     */
    public void setEndDate(String endDate) {
        this.endDate = endDate;
    }

    /**
     * @return the timeInterval
     */
    public int getTimeInterval() {
        return timeInterval;
    }

    /**
     * @param timeInterval the timeInterval to set
     */
    public void setTimeInterval(int timeInterval) {
        this.timeInterval = timeInterval;
    }
    
}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/framework/RecInterpreter/FoodRecInterpretations.java<|end_filename|>
/* Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.scl.framework.RecInterpreter;

import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.uclab.scl.interpreterdatamodel.Conclusion;
import org.uclab.scl.interpreterdatamodel.FiredRule;
import org.uclab.scl.interpreterdatamodel.InterpretationIngredients;
import org.uclab.scl.framework.AbstractInterpreterPacket;
import org.uclab.scl.framework.RecInterpreter.Explanation.AbstractRecExplanation;
import org.uclab.scl.framework.RecInterpreter.FoodItemRecommender.SNSTrendIdentifier;
import org.uclab.scl.outputModel.InterpretationModel.InterpretedRecommendations;

public class FoodRecInterpretations {
  private static Logger LOG = LogManager.getRootLogger();
  
	private AbstractRecExplanation recExplanation;
	
/**
 * This function receives a nutrition based recommendation given by [RB] and gets a recommended list of foods against the given nutrient type
 * from SNSTrendIdentifier function, processes the received list according to the preferences of the user
 * 
 * @param interpreterPacket
 * @throws Exception
 */
  public void getFoodRecommendation(AbstractInterpreterPacket interpreterPacket) throws Exception {
    InterpretationIngredients interpretationIngredients = (InterpretationIngredients) interpreterPacket.getRecommendationInput();
    List<FiredRule> firedrule = interpretationIngredients.getFiredRule();
    String userID = interpretationIngredients.getUserID();
    String nutrientLabel = "";
    String description = "";
    String uid = userID;
    String finalList = "";
    String key = "";
    String value = "";
    for (FiredRule f : firedrule) {
      description = f.getRuleConclusion();
      List<Conclusion> firedConclusionList = f.getConclusionList();
      for (Conclusion c : firedConclusionList) {
        key = c.getConclusionKey();
        if (key.equalsIgnoreCase("Food")) {
          value = c.getConclusionValue();
          nutrientLabel = value;
        }
      }
    }
    
    SNSTrendIdentifier identifyTrend = new SNSTrendIdentifier();
    try{
    	finalList = identifyTrend.processFoodRec(nutrientLabel, uid);    	
    }
    catch (Exception e) {
        e.printStackTrace();
        LOG.debug("Problems encountered in Identifying Trends");
      }  
    
    LOG.debug("Final List for " + nutrientLabel + ": " + finalList);
    ComposeRec rec = new ComposeRec(finalList, description, uid);
    LOG.debug("Test Uid: " + rec.getUserid());
    LOG.debug("Test Fooditems: " + rec.getRecFooditems());

    List<InterpretedRecommendations> lstInterpretedRecs = new ArrayList<InterpretedRecommendations>();
    InterpretedRecommendations interpretedRec = new InterpretedRecommendations();
    interpretedRec.setFoodItemList(finalList);
    interpretedRec.setRecDescription(description);
    lstInterpretedRecs.add(interpretedRec);
    interpreterPacket.setRecommendationOutput(lstInterpretedRecs);
  }
  public AbstractRecExplanation getRecExplanation() {
	return recExplanation;
  }
  public void setRecExplanation(AbstractRecExplanation recExplanation) {
	this.recExplanation = recExplanation;
  } 
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sl/dataadapter/ActiveSessionAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.sl.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.dc.Users;
import org.uclab.mm.datamodel.sl.ActiveSession;

/**
 * This is ActiveSessionAdapter class which implements the Data Access Interface for CRUD operations
 * @author Taqdir
 */
public class ActiveSessionAdapter implements DataAccessInterface{

     private Connection objConn;
     private static final Logger logger = LoggerFactory.getLogger(ActiveSessionAdapter.class);
    public ActiveSessionAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving ActiveSession. 
     * @param objActiveSession
     * @return List of String
     */
     @Override
    public List<String> Save(Object objActiveSession) {
        
        ActiveSession objInnerActiveSession = new ActiveSession();
        objInnerActiveSession =  (ActiveSession) objActiveSession;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_ActiveSession(?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserID", objInnerActiveSession.getUserID());
            objCallableStatement.setString("HashCode", objInnerActiveSession.getHashCode());
            objCallableStatement.setInt("Status", objInnerActiveSession.getStatus());
                       
            
            objCallableStatement.registerOutParameter("ActiveSessionID", Types.BIGINT);
            objCallableStatement.execute();
            
            int intActiveSessionID = objCallableStatement.getInt("ActiveSessionID");
            objConn.close();
            logger.info("Active Session saved successfully.");
        }
        catch (Exception e)
        {
        	logger.info("Error in adding Active Session");
        }   
        
        return objDbResponse;
    }

     /**
      * This is implementation function for Update ActiveSession. 
      * Not Implemented
      */
    @Override
    public <T> List<String> Update(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for retrieve ActiveSession. 
     * Not Implemented
     */
    @Override
    public <T> List<T> RetriveData(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/LLCManager/LLCUnifier.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Kang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.LLCManager;

import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicReference;

import org.uclab.mm.icl.llc.config.ContextType;
import org.uclab.mm.icl.llc.config.RecognizerType;


/**
 * This abstract class is the parent class of unifiers used in ICL unifying process.
 * @author Nailbrainz
 *
 */
public abstract class LLCUnifier {
	
	long userID;
	ArrayList<AtomicReference<String> > curLabels;
	
	/**
	 * Unique constructor of LLC unifier
	 * @param userID corresponding user ID
	 */
	public LLCUnifier(long userID, ArrayList<AtomicReference<String> > curLabels){
		this.userID = userID;
		this.curLabels = curLabels;
	}
	
	/**
	 * Method to remove all the inner contexts
	 */
	public abstract void clear();
	
	/**
     * Push the llc context into unifier
     * @param obj object(llcContext) to push
     * @param rec corresponding recognizer type
     */
	public abstract void push(Object obj, RecognizerType rec);
	
	
	/**
	 * Unifying function. Exact methodology of unification is dependent on each child class
	 * @param startTime start time of window
	 * @param ct contextType which unification will be happen
	 * @return unified result
	 */
	abstract ContextLabel unify(String startTime, ContextType ct);
	
	
}


<|start_filename|>knowledge-curation-layer/i-kat/src/main/webapp/index.jsp<|end_filename|>
<!--
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

-->	
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html >
<head>  
    <title>Add Row dynamically</title>  
    
    <script src="https://code.jquery.com/jquery-1.9.1.min.js" type="text/javascript"></script>
    <script src="https://code.jquery.com/ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
    
    <link href="resources/css/bootstrap.css" rel="stylesheet" type="text/css" />
    <link href="resources/css/jquery-ui.css" rel="stylesheet" type="text/css" />
    
  	<style>
  	table{width:100%}

.deleterow{cursor:pointer}
  	</style>
	
	
	
 
    <script type="text/javascript">  
    $(document).ready(function (){
    	
    function test(){
	    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( ".abc" ).addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" ).autocomplete({
            delay: 0,
            minLength: 0,
      source: availableTags
    });

} 

test();

function testRemove(){
    $(".deleterow").on("click", function(){
    var $killrow = $(this).parent('tr');
        $killrow.addClass("danger");
    $killrow.fadeOut(0, function(){
        $(this).remove();
    });});
}
testRemove();

var counter=0;
$(".addnewrow").on("click", function(){
$('table tr:last').after("<tr><td><input class='abc' type='text' id='one"+ counter +"'/></td>    <td><input type='text' class='abc' id=two"+ counter +"'/></td>    <td><input type='text' class='abc' id=three"+ counter +"'/></td><td class='deleterow'><div class='glyphicon glyphicon-remove'></div></td></tr>");
    
     test();
    testRemove();
    counter++;
});


    });
                      
    </script>  
    <body >  
  
     <div class="container">
    <h2>Table Management</h2>
    <div class="table-responsive">
    <table border="1" class="table table-striped table-hover  table-bordered">
<tr>
    <td><input type="text" class="abc" id="one" /></td>    <td><input type="text" class="abc" id="two" /></td>    <td><input type="text" class="abc" id="three" /></td><td class='deleterow'><div class='glyphicon glyphicon-remove'></div></td>
    </tr>
    </table>
</div></div>

<hr>
    <button class='btn btn-lg btn-primary addnewrow pull-right'>Add New <span class="glyphicon glyphicon-plus"></span></button>
   	</body>
</html>


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/framework/RecInterpreter/PARecommender/MultiRecPreferenceTesting.java<|end_filename|>
/* Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.scl.framework.RecInterpreter.PARecommender;

//import static content_interpreter_v1.TestContent.mapPrefer_rec;

import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;
import org.uclab.scl.datamodel.contextMapper.PreferenceMapper;

public class MultiRecPreferenceTesting {
  static HashMap<String, String> mapPreferRec = new HashMap<>();

  @SuppressWarnings("unchecked")
public static int[] mrecPreferenceTest(String userid, String currentContext)
      throws Exception {
    // Check Context with Preference
    PreferenceMapper preferenceMapper = new PreferenceMapper();

    mapPreferRec = preferenceMapper.preferMapper();

    String[] prefer1 = mapPreferRec.get(userid).split(",");
    int[] prefer = new int[prefer1.length];

    for (int i = 0; i < prefer1.length; i++) {
      String numberAsString = prefer1[i];
      prefer[i] = Integer.parseInt(numberAsString);
    }

    int receive[] = MultiRecContentTesting.multiRecContextTest(currentContext);
    int[] result = new int[receive.length];

    for (int i = 0; i < receive.length; i++)
      if ((receive[i] == 1) && (prefer[i] == 1)) {
        result[i] = 1;
      } else {
        result[i] = 0;
      }
    return (result);
  }

}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/datamodel/RiskFactors.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.datamodel;

import java.io.Serializable;

/**
 * @version MM v2.5
 * @author Afzal
 *
 */
public class RiskFactors implements Serializable{

  private long id;
  private String requestType;
  private int riskFactorId;
  private int statusId;
  private long userId;

  public long getUserId() {
    return userId;
  }

  public void setUserId(long userId) {
    this.userId = userId;
  }

  public int getUserRiskFactorId() {
    return userRiskFactorId;
  }

  public void setUserRiskFactorId(int userRiskFactorId) {
    this.userRiskFactorId = userRiskFactorId;
  }

  private int userRiskFactorId;

  /**
   * @return the riskFactorId
   */
  public int getRiskFactorId() {
    return riskFactorId;
  }

  /**
   * @param riskFactorId
   *          the riskFactorId to set
   */
  public void setRiskFactorId(int riskFactorId) {
    this.riskFactorId = riskFactorId;
  }

  /**
   * @return the statusId
   */
  public int getStatusId() {
    return statusId;
  }

  /**
   * @param statusId
   *          the statusId to set
   */
  public void setStatusId(int statusId) {
    this.statusId = statusId;
  }

  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public String getRequestType() {
    return requestType;
  }

  public void setRequestType(String requestType) {
    this.requestType = requestType;
  }

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sl/dataadapter/ActivityFeedbackAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sl.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.sc.Recommendation;
import org.uclab.mm.datamodel.sl.ActivityFeedback;

/**
 * This is ActivityFeedbackAdapter class which implements the Data Access Interface for CRUD operations
 * @author <NAME>
 */
public class ActivityFeedbackAdapter implements DataAccessInterface {

    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(ActivityFeedbackAdapter.class);
    public ActivityFeedbackAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving ActivityFeedback. 
     * @param objActivityFeedback
     * @return List of String
     */
    @Override
    public List<String> Save(Object objActivityFeedback) {
        ActivityFeedback objInnerActivityFeedback = new ActivityFeedback();
        objInnerActivityFeedback =  (ActivityFeedback) objActivityFeedback;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_ActivityFeedback(?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("RecognizedActivityID", objInnerActivityFeedback.getRecognizedActivityID());
            objCallableStatement.setLong("UserID", objInnerActivityFeedback.getUserID());
            objCallableStatement.setInt("Rate", objInnerActivityFeedback.getRate());
            objCallableStatement.setString("Reason", objInnerActivityFeedback.getReason());
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
            Date dtDate = sdf.parse(objInnerActivityFeedback.getFeedbackDate());
            
            Timestamp tsDate = new Timestamp(dtDate.getYear(),dtDate.getMonth(), dtDate.getDate(), dtDate.getHours(), dtDate.getMinutes(), dtDate.getSeconds(), 00);
            objCallableStatement.setTimestamp("FeedbackDate", tsDate);
            
                        
            objCallableStatement.registerOutParameter("ActivityFeedbackID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intActivityFeedbackID = objCallableStatement.getLong("ActivityFeedbackID");
            objDbResponse.add(String.valueOf(intActivityFeedbackID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Activity Feedback saved successfully, Activity Feedback Details="+objActivityFeedback);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding Activity Feedback");
        	objDbResponse.add("Error in adding Activity Feedback");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for updating ActivityFeedback. 
     * @param objActivityFeedback
     * @return List of String
     */
    @Override
    public List<String> Update(Object objActivityFeedback) {
        ActivityFeedback objInnerActivityFeedback = new ActivityFeedback();
        objInnerActivityFeedback =  (ActivityFeedback) objActivityFeedback;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_ActivityFeedback(?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("ActivityFeedbackID", objInnerActivityFeedback.getActivityFeedbackID());
            objCallableStatement.setLong("RecognizedActivityID", objInnerActivityFeedback.getRecognizedActivityID());
            objCallableStatement.setLong("UserID", objInnerActivityFeedback.getUserID());
            objCallableStatement.setInt("Rate", objInnerActivityFeedback.getRate());
            objCallableStatement.setString("Reason", objInnerActivityFeedback.getReason());
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
            Date dtDate = sdf.parse(objInnerActivityFeedback.getFeedbackDate());
            
            Timestamp tsDate = new Timestamp(dtDate.getYear(),dtDate.getMonth(), dtDate.getDate(), dtDate.getHours(), dtDate.getMinutes(), dtDate.getSeconds(), 00);
            objCallableStatement.setTimestamp("FeedbackDate", tsDate);
                        
            objCallableStatement.execute();
            
            Long intActivityFeedbackID = objInnerActivityFeedback.getActivityFeedbackID();
            objDbResponse.add(String.valueOf(intActivityFeedbackID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Activity Feedback updated successfully, Activity Feedback Details="+objActivityFeedback);
        }
        catch (Exception e)
        {
        	logger.info("Error in updating Activity Feedback");
        	objDbResponse.add("Error in updating Activity Feedback");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for retrieving ActivityFeedback. 
     * @param objActivityFeedback
     * @return List of ActivityFeedback
     */
    @Override
    public List<ActivityFeedback> RetriveData(Object objActivityFeedback) {
        ActivityFeedback objOuterActivityFeedback = new ActivityFeedback();
        List<ActivityFeedback> objListInnerActivityFeedback = new ArrayList<ActivityFeedback>();
        objOuterActivityFeedback =  (ActivityFeedback) objActivityFeedback;
        
        try
        {
            CallableStatement objCallableStatement = null;
            if(objOuterActivityFeedback.getRequestType() == "ByRecognizedActivityID")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_ActivityFeedbackByRecognizedActivityID(?)}");
                objCallableStatement.setLong("RecognizedActivityID", objOuterActivityFeedback.getRecognizedActivityID());
            }
            else if(objOuterActivityFeedback.getRequestType() == "ByUserID")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_ActivityFeedbackByUserID(?)}");
                objCallableStatement.setLong("UserID", objOuterActivityFeedback.getUserID());
            }
                
            
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                ActivityFeedback objInnerActivityFeedback = new ActivityFeedback();
                
                objInnerActivityFeedback.setActivityFeedbackID(objResultSet.getLong("ActivityFeedbackID"));
                objInnerActivityFeedback.setRecognizedActivityID(objResultSet.getLong("RecognizedActivityID"));
                objInnerActivityFeedback.setUserID(objResultSet.getLong("UserID"));
                objInnerActivityFeedback.setRate(objResultSet.getInt("Rate"));
                objInnerActivityFeedback.setReason(objResultSet.getString("Reason"));
                
                 if(objResultSet.getTimestamp("FeedbackDate") != null)
                {
                    Timestamp tsFeedbackDate = objResultSet.getTimestamp("FeedbackDate");
                    objInnerActivityFeedback.setFeedbackDate(tsFeedbackDate.toString());
                }
                objInnerActivityFeedback.setSituationCategoryID(objResultSet.getInt("RecognizedActivityID"));
                objInnerActivityFeedback.setSituationCategoryDescription(objResultSet.getString("ActivityDescription"));
                 
                objListInnerActivityFeedback.add(objInnerActivityFeedback);
            }
            objConn.close();
            logger.info("recommendation Feedback loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading recommendation Feedback");
        }   
        return objListInnerActivityFeedback;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>knowledge-curation-layer/i-kat/src/main/java/org/uclab/mm/kcl/edkat/service/UserServiceImpl.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.kcl.edkat.service;

import java.util.List;

import org.springframework.transaction.annotation.Transactional;
import org.uclab.mm.kcl.edkat.dao.UserDAO;
import org.uclab.mm.kcl.edkat.datamodel.User;

/**
* This is service implementation for the user it provides service implementation to 
* create, update, retrieve of user
 * @author  <NAME>
 * @version 1.0
 * @since   2015-08-16
 * */
public class UserServiceImpl implements UserService {

	private UserDAO userDAO;
	
	
	public UserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	/**
	 * This function is for add new user
	 * @param objUser
	 * @return Object of User
	*/
	@Transactional
	public User addUser(User objUser) {
		return this.userDAO.addUser(objUser);
	}

	/**
	 *  This function is for update the existing user
	 * @param objUser
	 * @return Object of User
	*/
	@Transactional
	public User updateUser(User objUser) {
		return this.userDAO.updateUser(objUser);
	}

	/**
	 * This function get all user in form of list
	 * @return List of User
	*/
	public List<User> listUser() {
		return this.userDAO.listUser();
	}

	/**
	 * This function get a specific user by user id (primary key)
	 * @param id
	 * @return Object of User
	*/
	public User getUserById(int id) {
		return this.userDAO.getUserById(id);
	}

	/**
	 * This function delete a specific user by user id (primary key)
	 * @param id
	*/
	public void removeUser(int id) {
		this.userDAO.removeUser(id);
	}

	 /**
	 * This function validate a specific user by user id and password
	 * @param objUser
	 * @return Object of User
	*/
	public User validateUser(User objUser) {
		return this.userDAO.validateUser(objUser);
	}

}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/framework/RecInterpreter/PARecommender/MultipleRecEvaluator.java<|end_filename|>
/* Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.scl.framework.RecInterpreter.PARecommender;

import static org.uclab.scl.framework.RecInterpreter.PARecommender.MultiRecAlternativeRecEval.recFiltrationAlternative;

import java.io.FileNotFoundException;
import java.util.HashMap;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.uclab.scl.datamodel.contextMapper.RecommendationMapper;
import org.uclab.scl.framework.RecInterpreter.AbstractRecEvaluator;

public class MultipleRecEvaluator extends AbstractRecEvaluator {
	private static Logger LOG = LogManager.getRootLogger();

  static HashMap<String, String> mapWeatherRec = new HashMap<>();
  static HashMap<String, String> mapDisableRec = new HashMap<>();
  static HashMap<String, String> mapRec = new HashMap<>();
  
  @SuppressWarnings("unchecked")
  private static int[] evalRecommendations(String rec, String userid, String context) throws Exception {
    return null;
  }
  
/**
 * Main purpose of this function is to evaluate user's preferences against the applicable recommendations in the given context
 * 
 * @param AR
 * @param userid
 * @param context_string
 * @return
 * @throws Exception
 */
  private static int[] multiRecPreference(int[] AR, String userid, String context_string) throws Exception {
    int[] ARP = PreferenceTesting.mainPrefTest (AR, userid, context_string);
    int[] prefAggregate = new int[AR.length];
    for (int i = 0; i < AR.length; i++) {
      if ((AR[i] == 1) && (ARP[i] == 1))
        prefAggregate[i] = 1;
      else
        prefAggregate[i] = 0;
    }
    return (prefAggregate);
  }
/**
 * Returns evaluations for the multi-recommendation case
 * <p>
 * 
 * @param rec
 * @param userid
 * @param context
 * @return evaluations
 */
  @SuppressWarnings("unchecked")
  @Override
  public int[] evaluate(String rec, String userid, String context){
    RecommendationMapper recommendationMapper = new RecommendationMapper();
    LOG.debug("Context String: " + context);
    int[] contentResult = null;
    try {
      contentResult = MultiRecContentTesting.multiRecContextTest(context); //IMP
    } catch (Exception e) {
      e.printStackTrace();
    }
    LOG.debug("Received Rec_List contains: " + rec);
    String[] temp = rec.split(",");
    try {
      mapRec = recommendationMapper.recMapper();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    int[] alternativeRecList = new int[mapRec.size() - 1];
    int[] finalRec = new int[mapRec.size() - 1];
    java.util.Arrays.fill(alternativeRecList, 0);
    LOG.debug("Content Result vector after ANDing Contextual Matrix");
    for (int i = 0; i < contentResult.length; i++)
      LOG.debug(contentResult[i] + " ");
    LOG.debug(" ");
    for (int i = 0; i < temp.length; i++) {
      String temp1 = mapRec.containsKey(temp[i]) ? mapRec.get(temp[i]) : mapRec.get(null);
     	LOG.debug(temp1);
      int index = 0;
      if (temp1 != null)
        index = Integer.parseInt(temp1);
      else {
        LOG.debug("Recommendation NOT FOUND in the repository");
        LOG.debug("Default case applied");
        index = Integer.parseInt(mapRec.get("D"));
        LOG.debug("index value " + index);
      }
      if (contentResult[index] == 1)
        alternativeRecList[index] = 1;
    }
    LOG.debug("AR_list after Context Checking with Recommendation(s)");
    for (int i = 0; i < alternativeRecList.length; i++)
      LOG.debug(alternativeRecList[i] + " ");
    LOG.debug(" ");
    int sum = 0;
    int prefSum = 0;
    for (int i = 0; i < alternativeRecList.length; i++)
      sum += alternativeRecList[i];
    if (sum != 0)
    {
      LOG.debug("AR_LIST IS NOT EMPTY");
      if (sum == 1)
      {
        LOG.debug("AR LIST COINTAINS ONLY ONE REC :");
        System.arraycopy(alternativeRecList, 0, finalRec, 0, alternativeRecList.length);
      } else { 
        LOG.debug("AR LIST CONTAINS MULTIPLE RECs");
        int[] ARP=null;
        try {
          ARP = multiRecPreference(alternativeRecList, userid, context); //IMP
        } catch (Exception e) {
          e.printStackTrace();
        }
        for (int i = 0; i < ARP.length; i++) {
          LOG.debug(ARP[i] + " ");
          prefSum += ARP[i];
        }
        if (prefSum == 0) {
          LOG.debug("ARP is Empty so back to AR_List");
          System.arraycopy(alternativeRecList, 0, finalRec, 0, alternativeRecList.length);
        } else {
          LOG.debug("Forwarding ARP list");
          System.arraycopy(ARP, 0, finalRec, 0, ARP.length);
        }
      }
    } else {
      LOG.debug("AR list is Empty");
      String R1 = temp[0];
      try {
        finalRec = recFiltrationAlternative(R1, context, userid); //IMP
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    int[] tempArr = new int[mapRec.size() - 1];
    boolean flag = true;
    for (int i = 0; i < finalRec.length; i++) {
      if ((finalRec[i] == 1) && (flag == true)) {
        tempArr[i] = 1;
        flag = false;
      } else
        tempArr[i] = 0;
    }
    return (tempArr);
  }
}


<|start_filename|>knowledge-curation-layer/i-kat/src/main/webapp/resources/css/combo.css<|end_filename|>
* {
    font-family: Arial;
}

h1 {
    color: #333333;
}

#collegesCombo .stc-input {
    width: 300px;
}

.stc-box {
    top: 5px;
}

label {
    font-weight: bold;
    font-family: Arial;
    font-size: .8em;
}

#statesCombo .stc-table {
    border-radius: 2px;
}

#statesCombo .stc-button {
    background-color: #99ccff;
    width: 25px;
}

#statesCombo .stc-input {
    font-size: 1.3em;
    padding: 3px 0 3px 5px;
}

#statesCombo .stc-box {
    top: 0;
}

#statesLabel {
    display: block;
    font-size: 1.1em;
    font-family: Arial;
    color: #333333;
}

#statesCombo .stc-text {
    font-size: 1.1em;
    color: #333333;
}

.stc-lrow {
    cursor: pointer;
}

<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/communication/CommunicationManager.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.communication;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.uclab.scl.interpreterdatamodel.CurrentContext;

import org.uclab.scl.interpreterdatamodel.FoodLog;
import org.uclab.scl.interpreterdatamodel.LifeLogData;


import org.uclab.scl.interpreterdatamodel.SNSTrends;


import org.uclab.scl.outputModel.InterpretationModel.PhyActivityExplaination;

/**
 * This class holds all the client methods for external layer communication in order to get, store, and update data from/to the databases.
 * @version MM v2.5
 * @author Afzal
 *
 */
public class CommunicationManager {
  private static Logger LOG = LogManager.getRootLogger();
  
  private String LIFELOG_DCL_SERVER1 = "http://127.0.0.1:8080/MMDataCurationRestfulService/webresources/DataCuration";
  private String LIFELOG_DCL_SERVER2 = "http://127.0.0.1:8081/MMDataCurationRestfulService/webresources/InformationCuration";
  private String LIFELOG_ICL_SERVER = "http://127.0.0.1:8082/MMDataCurationRestfulService/webresources/InformationCuration";
  private String LIFELOG_SCL_SERVER = "http://127.0.0.1:8083/MMDataCurationRestfulService/webresources/ServiceCuration";
  private String LIFELOG_SL_SERVER = "http://127.0.0.1/MMv2.5/snsservice.php?";
  
  private CommunicationManager() {
    if(!loadConfiguration()){
      LOG.error("Cannot load configuration file <Application.properties>");
    }
  }
  private boolean loadConfiguration(){
    try{
      Properties prop = new Properties();
      InputStream propInstream = new FileInputStream(getClass().getClassLoader().getResource("Application.properties").getFile());
      prop.load(propInstream);
      propInstream.close();
      LIFELOG_DCL_SERVER1 = prop.getProperty("LIFELOG_DCL_SERVER1");
      LIFELOG_DCL_SERVER2 = prop.getProperty("LIFELOG_DCL_SERVER2");
      LIFELOG_ICL_SERVER = prop.getProperty("LIFELOG_ICL_SERVER");
      LIFELOG_SCL_SERVER = prop.getProperty("LIFELOG_SCL_SERVER");
      LIFELOG_SL_SERVER = prop.getProperty("LIFELOG_SL_SERVER");
      
    }catch(IOException e){
      return false;
    }
    return true;
  }
  
  /**
   * This method gets food category (carbohydrates, fat, etc.) as input and returns social trends of individual food item in that category in terms of frequency as output. 
   * <p>
   * @param foodCatagory
   * @return trends
   */
  public SNSTrends getSNSTrendsFromSLforFoods(String foodCatagory) {
    AbstractRestClient<SNSTrends, String> snsFoodTrendsWS = new SLSNSTrendsWSClient(LIFELOG_SL_SERVER);
    String resourceUser_GETURI = "type=" + foodCatagory;
    SNSTrends snsFoodTrends = snsFoodTrendsWS.GetData(resourceUser_GETURI);

    return snsFoodTrends;
  }
  /**
   * This method takes user identifier and returns the whole record of that user stored in the database.
   * <p>
   * @param userID
   * @return user
   */
//  public User getUser(long userID) {
//    AbstractRestClient<User, String> userWSClient = new DCUserWSClient(LIFELOG_DCL_SERVER1);
//    String resourceUser_GETURI = "/User/" + String.valueOf(userID);
//    User user = userWSClient.GetData(resourceUser_GETURI);
//    return user;
//
//  }
  /**
   * Takes foodLog object by setting the mandatory parameter (user identifier) and returns the list of foodLog objects
   * <p>
   * @param foodLog
   * @return food list
   */
  public List<FoodLog> getFoodLog(FoodLog foodLog) {

    AbstractRestClient<List<FoodLog>, List<FoodLog>> foodLogClient = new DCFoodLogWSClient(LIFELOG_DCL_SERVER2);
    String resourceFoodLog = "/GetFoodLogByUserIDDateRange";
    List<FoodLog> foodLogList = new ArrayList<>();
    foodLogList.add(foodLog);
    List<FoodLog> userFoodLogDetails = foodLogClient.PostData(resourceFoodLog, foodLogList);
    return userFoodLogDetails;
  }
 
  /**
   * Based on user identifier, the object of Current Context (location, high level context, etc.) is returned
   * <p>
   * @param userID
   * @return user context
   */
  public CurrentContext getCurrentContext(long userID) {
    AbstractRestClient<CurrentContext, String> currentContextWSClient = new DCCurrentContextWSClient(LIFELOG_SCL_SERVER);
    String resourceCurrentContext_GETURI = "/UserCurrentContext/" + String.valueOf(userID);
    CurrentContext currentContexts = currentContextWSClient.GetData(resourceCurrentContext_GETURI);
    return currentContexts;
  }
  

  /**
   * This method is used to save the explanation of recommendation in the Lifelog database.
   * <p>
   * @param pAExplanation
   * @return List<String>
   */
  public List<String> persistPAExplanations(List<PhyActivityExplaination> pAExplanation) {
    AbstractRestClient<List<PhyActivityExplaination>, List<String>> pAExplanationWSClient = new PhysicalActivityExplanationWSClient(LIFELOG_SCL_SERVER);
    String resourcePhyActRecURI = "/AddRecommendationExplanation";
    List<String> explanationResult = pAExplanationWSClient.PostData(resourcePhyActRecURI, pAExplanation);
    return explanationResult;
  }
  
  /**
   * This method returns the list of lifeLogData objects for a particular user set in lifeLogData object.
   * <p>
   * @param lifeLogData
   * @return LifeLogData List
   */
  public List<LifeLogData> getLifeLogData(LifeLogData lifeLogData) {
    AbstractRestClient<List<LifeLogData>, List<LifeLogData>> lifeLogDataClient = new DCLifeLogDataWSClient(LIFELOG_ICL_SERVER);
    String resourceLifelogData_GETURI = "/GetUserRecognizedActivityAccumulateByUserAndDate";
    List<LifeLogData> usrLifeLogDataRequest = new ArrayList<>();
    usrLifeLogDataRequest.add(lifeLogData);
    List<LifeLogData> listLifeLogData = lifeLogDataClient.PostData(resourceLifelogData_GETURI, usrLifeLogDataRequest);
    return listLifeLogData;
  }
  
  /**
   * Singleton pattern: making sure one instance of DataCurationCommunicationManager
   * <p>
   * @return Communication Manager
   */
  public static CommunicationManager getCommunicationManager() {
    return CommunicationManagerHolder.INSTANCE;
  }

  private static class CommunicationManagerHolder {
    private static final CommunicationManager INSTANCE = new CommunicationManager();
  }
}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/framework/recbuilder/RecResultGenerator.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.framework.recbuilder;

import java.io.IOException;
import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;
import org.uclab.scl.datamodel.FiredRule;

public class RecResultGenerator {

  private List<FiredRule> firedRules;
  
  /**
   * instantiates Recommendation Result Generator
   * 
   */
  public RecResultGenerator() {
  }
  
  /**
   * instantiates Recommendation Result Generator
   * 
   * @param firedRules
   */
  public RecResultGenerator(List<FiredRule> firedRules) {
    this.firedRules = firedRules;
  }
  
  /**
   * builds complex json object
   * <p>
   * 
   * @return JSON
   */
  public String generateResults() {
    String jsonResult = null;
    try {
      jsonResult = new ObjectMapper().writeValueAsString(firedRules);
    } catch (IOException ex) {
      ex.printStackTrace();
    }
    return jsonResult;
  }
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/ic/dataadapter/UserRecognizedEmotionAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.ic.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.ic.UserRecognizedEmotion;

/**
 * This is UserRecognizedEmotionAdapter class which implements the Data Access Interface for CRUD operations
 * @author Taqdir
 */
public class UserRecognizedEmotionAdapter implements DataAccessInterface {

    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(UserRecognizedEmotionAdapter.class);
    public UserRecognizedEmotionAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving UserRecognizedEmotion. 
     * @param objUserRecognizedEmotion
     * @return List of String
     */
    @Override
    public List<String> Save(Object objUserRecognizedEmotion) {
        UserRecognizedEmotion objInnerUserRecognizedEmotion = new UserRecognizedEmotion();
        objInnerUserRecognizedEmotion =  (UserRecognizedEmotion) objUserRecognizedEmotion;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_UserRecognizedEmotion(?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserID", objInnerUserRecognizedEmotion.getUserId());
            objCallableStatement.setString("EmotionLabel", objInnerUserRecognizedEmotion.getEmotionLabel());
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
             Date dtStartDate = sdf.parse(objInnerUserRecognizedEmotion.getStartTime());
            Timestamp tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);
            
            objCallableStatement.setTimestamp("StartTime", tsStartDate);
                                             
            objCallableStatement.registerOutParameter("UserRecognizedEmotionID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intUserRecognizedEmotionID = objCallableStatement.getLong("UserRecognizedEmotionID");
            objDbResponse.add(String.valueOf(intUserRecognizedEmotionID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("User Recognized Emotion saved successfully, User Recognized Emotion Details="+objUserRecognizedEmotion);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding User Recognized Emotion");
        	objDbResponse.add("Error in adding User Recognized Emotion");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for updating UserRecognizedEmotion. 
     * Not implemented
     */
    @Override
    public <T> List<String> Update(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet."); 
    }

    /**
     * This is implementation function for retrieving UserRecognizedEmotion.
     * @param objUserRecognizedEmotion
     * @return List of RetriveUserRecognizedEmotion 
     */
    @Override
    public List<UserRecognizedEmotion> RetriveData(Object objUserRecognizedEmotion) {
         UserRecognizedEmotion objOuterUserRecognizedEmotion = new UserRecognizedEmotion();
        List<UserRecognizedEmotion> objListInnerUserRecognizedEmotion = new ArrayList<UserRecognizedEmotion>();
        objOuterUserRecognizedEmotion =  (UserRecognizedEmotion) objUserRecognizedEmotion;
        
        try
        {
            CallableStatement objCallableStatement = null;
            Timestamp tsStartDate = null;
            Timestamp tsEndDate = null;
            if(objOuterUserRecognizedEmotion.getRequestType() == "LatestByUser")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_CurrentUserRecognizedEmotionByUserID(?)}");
                objCallableStatement.setLong("UserID", objOuterUserRecognizedEmotion.getUserId());
            }
            else if(objOuterUserRecognizedEmotion.getRequestType() == "UserDateRange")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UserRecognizedEmotionByUserID(?, ?, ?)}");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
                Date dtStartDate = sdf.parse(objOuterUserRecognizedEmotion.getStartTime());
                tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);

                Date dtEndDate = sdf.parse(objOuterUserRecognizedEmotion.getEndTime());
                tsEndDate = new Timestamp(dtEndDate.getYear(),dtEndDate.getMonth(), dtEndDate.getDate(), dtEndDate.getHours(), dtEndDate.getMinutes(),dtEndDate.getSeconds(),0);

                objCallableStatement.setLong("UserID", objOuterUserRecognizedEmotion.getUserId());
                objCallableStatement.setTimestamp("StartTime", tsStartDate);
                objCallableStatement.setTimestamp("EndTime", tsEndDate);
            }
            
            
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                UserRecognizedEmotion objInnerUserRecognizedEmotion = new UserRecognizedEmotion();
                objInnerUserRecognizedEmotion.setUserRecognizedEmotionId(objResultSet.getLong("UserRecognizedEmotionID"));
                objInnerUserRecognizedEmotion.setUserId(objResultSet.getLong("UserID"));
                objInnerUserRecognizedEmotion.setEmotionLabel(objResultSet.getString("EmotionLabel"));
                
                if(objResultSet.getTimestamp("StartTime") != null)
                {
                    tsStartDate = objResultSet.getTimestamp("StartTime");// updated
                    objInnerUserRecognizedEmotion.setStartTime( tsStartDate.toString());
                }
                
                if(objResultSet.getTimestamp("EndTime") != null)
                {
                    tsEndDate = objResultSet.getTimestamp("EndTime");// updated
                    objInnerUserRecognizedEmotion.setEndTime( tsEndDate.toString());
                }
                
                objInnerUserRecognizedEmotion.setDuration(objResultSet.getLong("Duration"));
                
                objListInnerUserRecognizedEmotion.add(objInnerUserRecognizedEmotion);
            }
            objConn.close();
            logger.info("User Recognized emotion are loaded successfully.");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading User Recognized emotion");
        }   
        return objListInnerUserRecognizedEmotion;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/MachineLearningTools/ExtClassification.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Bang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.MachineLearningTools;

import java.io.BufferedReader;

import java.io.File;
import java.io.FileReader;

import org.uclab.mm.icl.llc.LLCManager.ContextLabel;
import org.uclab.mm.icl.llc.MachineLearningTools.classification.Classification;

import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.core.Attribute;
import weka.core.FastVector;
import weka.core.Instance;
import weka.core.Instances;

/**
 * This Class build the predictive model by all of classifier from weka library
 * @author <NAME>
 *
 */

public class ExtClassification extends Classification {

	int FEATURES_NUM;
	int RECOGNIZE_IND;
	FastVector allAttributes;
	Instances learningDataset;
	Classifier predictiveModel;
	Attribute[] m;
	String[] label;
	/**
	 * classify class
	 * @param data
	 * @return int
	 */

	public int classify(double[] data) {
		int result = 0;
		try {
			result = getClassifiedInformation(learningDataset, predictiveModel, data);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * set training data path, features information, labels and classifier
	 * @param filename
	 * @param FEATURES_NUM
	 * @param label
	 * @param classifier
	 */

	public ExtClassification(String filename, int FEATURES_NUM, String[] label,
			Classifier classifier) {
		try {
			this.FEATURES_NUM = FEATURES_NUM;
			this.RECOGNIZE_IND = FEATURES_NUM + 1;
			this.m = new Attribute[FEATURES_NUM];
			this.label = label;
			allAttributes = createAttributes();
			learningDataset = createLearningDataSet(allAttributes, filename);
			predictiveModel = learnPredictiveModel(learningDataset, classifier);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * create attribute by weka
	 * @return FastVector
	 */

	private FastVector createAttributes() {

		for (int i = 0; i < FEATURES_NUM; i++) {
			m[i] = new Attribute("m" + i);
		}

		FastVector labelValues = new FastVector(label.length);
		for (int i = 0; i < label.length; i++) {
			labelValues.addElement(label[i]);
		}

		// emotionValues.addElement("fear");
		Attribute classlabel = new Attribute("CLASS", labelValues);
		FastVector allAttributes = new FastVector(FEATURES_NUM);
		for (int i = 0; i < FEATURES_NUM; i++) {
			allAttributes.addElement(m[i]);
		}
		allAttributes.addElement(classlabel);
		return allAttributes;
	}
	
	/**
	 * Create Learning Data Set, It process based on some format
	 * @param allAttributes
	 * @param filename
	 * @return
	 */

	private Instances createLearningDataSet(FastVector allAttributes,
			String filename) {

		Instances trainingDataSet = new Instances("wekaClassifier",
				allAttributes, 10000);
		trainingDataSet.setClassIndex(FEATURES_NUM);
		File file = new File(filename);
		int count = 0;
		String record = "";
		String[] dataset = new String[FEATURES_NUM + 1];
		double[] mfccmean = new double[FEATURES_NUM];
		String emotion = null;
		try {
			BufferedReader in = new BufferedReader(new FileReader(file),
					(int) file.length());

			while ((record = in.readLine()) != null) {

				dataset = record.split("\t");
				for (int i = 0; i < FEATURES_NUM; i++) {
					mfccmean[i] = Double.valueOf(dataset[i]);
				}
				String[] predictEmotion = dataset[FEATURES_NUM].split("'");
				emotion = predictEmotion[1];
				count++;
				addInstance(trainingDataSet, mfccmean, emotion);
			}

			in.close();

		} catch (Exception e) {

		}
		return trainingDataSet;
	}
	
	/**
	 * Add Instance by weka
	 * @param trainingDataSet
	 * @param mfccmean
	 * @param emotion
	 */

	private void addInstance(Instances trainingDataSet, double[] mfccmean,
			String emotion) {
		Instance instance = createInstance(trainingDataSet, mfccmean, emotion);
		trainingDataSet.add(instance);
	}
	/**
	 * Create Instance by weka
	 * @param associatedDataSet
	 * @param mfccmean
	 * @param Emotion
	 * @return
	 */

	private Instance createInstance(Instances associatedDataSet,
			double[] mfccmean, String Emotion) {
		Instance instance = new Instance(FEATURES_NUM + 1);
		instance.setDataset(associatedDataSet);
		for (int i = 0; i < FEATURES_NUM; i++) {
			instance.setValue(i, mfccmean[i]);
		}
		instance.setValue(FEATURES_NUM, Emotion);
		return instance;
	}

	/**
	 * Learn Predictive Model by Weka
	 * @param learningDataSet
	 * @param classifier
	 * @return Classifier
	 * @throws Exception
	 */
	private Classifier learnPredictiveModel(Instances learningDataSet,
			Classifier classifier) throws Exception {
		classifier.buildClassifier(learningDataSet);
		return classifier;
	}
	
	/**
	 * Make Predictive Mdoel for Evaluation by Weka
	 * @param classifier
	 * @param learningDataset
	 * @return Evaluation
	 * @throws Exception
	 */

	public Evaluation evaluatePredictiveModel(Classifier classifier,
			Instances learningDataset) throws Exception {
		Evaluation learningSetEvaluation = new Evaluation(learningDataset);
		learningSetEvaluation.evaluateModel(classifier, learningDataset);
		return learningSetEvaluation;
	}

	/**
	 * get Classification Information
	 * @param learningDataset
	 * @param predictiveModel
	 * @param features
	 * @return int
	 * @throws Exception
	 */
	
	private int getClassifiedInformation(Instances learningDataset,
			Classifier predictiveModel, double[] features) throws Exception {
		Instance predictemotion = createInstance(learningDataset, features,
				label[0]);

		int emotionPrediction = (int) predictiveModel
				.classifyInstance(predictemotion);
		return emotionPrediction;
	}
	
	/**
	 * No Define
	 */

	@Override
	public String Classify(Object data) {
		// TODO Auto-generated method stub
		return null;
	}
}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/communication/PhysicalActivityFactsWSClient.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.communication;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.uclab.scl.outputModel.RecModel.PhyActivityFacts;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
/**
 * @version MM v2.5
 * @author Afzal
 *
 */
public class PhysicalActivityFactsWSClient extends AbstractRestClient<List<PhyActivityFacts>, List<String>> {
  public PhysicalActivityFactsWSClient(String baseURI) {
    super(baseURI);
  }

  @Override
  public List<PhyActivityFacts> GetData(String GET_ResourceURI) {
    ClientConfig config = new DefaultClientConfig();
    config.getClasses().add(JacksonJsonProvider.class);
    Client client = Client.create(config);
    WebResource service = client.resource(UriBuilder.fromUri(baseURI).build());
    List<PhyActivityFacts> facts = service.path(GET_ResourceURI).accept(MediaType.APPLICATION_JSON).get(new GenericType<List<PhyActivityFacts>>() {});
    if (facts.size() > 0)
      return facts;
    else
      return null;
  }
  @Override
  public List<String> PostData(String POST_ResourceURI, List<PhyActivityFacts> postedResource) {
    Iterator<PhyActivityFacts> paFacts = postedResource.iterator();
    List<String> phyActExpResult = new ArrayList<>();
    while (paFacts.hasNext()) {

      PhyActivityFacts fact = paFacts.next();
      ClientConfig config = new DefaultClientConfig();
      config.getClasses().add(JacksonJsonProvider.class);
      Client client = Client.create(config);
      WebResource service = client.resource(UriBuilder.fromUri(baseURI).build());
      ClientResponse response = service.path(POST_ResourceURI).type(MediaType.APPLICATION_JSON).post(ClientResponse.class, fact);
      phyActExpResult.add(response.getEntity(new GenericType<List<String>>() {}).get(0));
    }
    return phyActExpResult;
  }
}


<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/monitoring/NotifyService.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */
package org.uclab.mm.dcl.llm.monitoring;

/**
 * The abstract class for notification management services are defined to give flexibility
 * for communication way.
 * @author Rizvi
 */
public abstract class NotifyService{

  protected ServiceNotificationChannel objServiceNotification;

  /**
   * Constructor for NotifyService class which initialize the communication channel
   * @param objServiceNotification 
   */
  protected NotifyService(ServiceNotificationChannel objServiceNotification){
    this.objServiceNotification = objServiceNotification;
  }
/**
 * The abstract method used to send notification.
 */
  public abstract void sendNotification();
}


<|start_filename|>supporting-layer/descriptive-analytics/src/assets/js/dailyactivites.js<|end_filename|>
AmCharts.makeChart("dailychartdiv",
				{
					"type": "serial",
					"pathToImages": "http://cdn.amcharts.com/lib/3/images/",
					"categoryField": "date",
					"dataDateFormat": "YYYY-MM-DD HH",
					"categoryAxis": {
						"minPeriod": "hh",
						"parseDates": true
					},
					"chartCursor": {
						"categoryBalloonDateFormat": "JJ:NN"
					},
					"chartScrollbar": {},
					
					"graphs": [
						{
							"fillAlphas": 1,
							"fixedColumnWidth": 20,
							"id": "Walking",
							"negativeBase": -5,
							"periodSpan": -5,
							"precision": -1,
							"title": "Walking",
							"type": "column",
							"valueField": "Walking"
						},
						{
							"fillAlphas": 1,
							"fixedColumnWidth": 20,
							"id": "Running",
							"title": "Running",
							"type": "column",
							"valueField": "Running"
						},
						{
							"fillAlphas": 1,
							"fixedColumnWidth": 20,
							"fontSize": -1,
							"id": "Standing",
							"title": "Standing",
							"type": "column",
							"valueField": "Standing"
						}
					],
					"guides": [],
					"valueAxes": [
						{
							"id": "durations",
							"title": "Minutes"
						}
					],
					"allLabels": [],
					"balloon": {},
					"legend": {
						"periodValueText": "Total: [[value.sum]]",
						"useGraphSettings": true,
						"valueAlign": "left"
					},
					
					"dataProvider": [
						{
							"date": "2014-03-01 08",
							"Walking": 8,
							"Running": 5,
							"Standing": 2
						},
						{
							"date": "2014-03-01 09",
							"Walking": 6,
							"Running": 7,
							"Standing": 3
						},
						{
							"date": "2014-03-01 10",
							"Walking": 2,
							"Running": 3,
							"Standing": 1
						},
						{
							"date": "2014-03-01 11",
							"Walking": 1,
							"Running": 3,
							"Standing": 2
						},
						{
							"date": "2014-03-01 12",
							"Walking": 2,
							"Running": 1,
							"Standing": 1
						},
						{
							"date": "2014-03-01 13",
							"Walking": 3,
							"Running": 2,
							"Standing": 9
						},
						{
							"date": "2014-03-01 14",
							"Walking": 6,
							"Running": 8,
							"Standing": 1
						}
					]
				}
			);

<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/LLCManager/ContextLabel.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Kang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.LLCManager;

import org.uclab.mm.icl.llc.config.ContextType;
import org.uclab.mm.icl.llc.config.RecognizerType;


/**
 * Unique instantiable data class for the low level contexts
 * @author Nailbrainz
 * 
 */

public class ContextLabel {
  
   /** 
    * @return representation of your dataType as String
    */
   @Override
    public String toString(){
	   return Label;
   };
    String timeStamp;
    String Label;
    long userID;
    ContextType ct;
    
    /**
     * 
     * @param userID id of user 
     * @param Label label of the low level context
     * @param timeStamp timestamp in MM format
     * @param ct contextType of the ContextLabel
     */
    public ContextLabel(long userID, String Label, String timeStamp, ContextType ct){
    	this.userID = userID;
    	this.Label = Label;
    	this.timeStamp = timeStamp;
    }
    
    
    /**
     * 
     * @return timestamp of corresponding context, in MM format
     */
	public String getTimeStamp() {
		return timeStamp;
	}
	
	/**
	 * forcefully sets the timestamp to target context 
	 * @param timeStamp timestamp to set. must be in MM format
	 */
	public void setTimeStamp(String timeStamp) {
		this.timeStamp = timeStamp;
	}
	
	/**
	 * This function returns the label stored in the low level context
	 * @return label of the context
	 */
	public String getLabel() {
		return Label;
	}
	
	
	/**
	 * forcefully sets the label to target context 
	 * @param label label to set
	 */
	public void setLabel(String label) {
		Label = label;
	}
	
	/**
	 * This function returns the user id stored in the low level context
	 * @return user id of corresponding context
	 */
	public long getUserID() {
		return userID;
	}
	
	
	/**
	 * forcefully sets the id to target context 
	 * @param userID user id to set
	 */
	public void setUserID(long userID) {
		this.userID = userID;
	}

}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/HLC/HLC.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.HLC;
/**
 *
 * @author Nailbrainz
 */
public class HLC {
}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/interpreterdatamodel/CurrentLocation.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.interpreterdatamodel;

import java.io.Serializable;
import org.codehaus.jackson.annotate.JsonIgnore;

/**
 * 
 * @author User
 */
public class CurrentLocation implements Serializable {

  private Long duration;
  private String locationLabel;
  private String startTime;
  private String endTime;
  private Long userId;
  private Long userDetectedLocationId;

  /**
   * @return the duration
   */
  // @JsonIgnore
  public Long getDuration() {
    return duration;
  }

  /**
   * @param duration
   *          the duration to set
   */
  public void setDuration(Long duration) {
    this.duration = duration;
  }

  /**
   * @return the locationLabel
   */
  public String getLocationLabel() {
    return locationLabel;
  }

  /**
   * @param locationLabel
   *          the locationLabel to set
   */
  public void setLocationLabel(String locationLabel) {
    this.locationLabel = locationLabel;
  }

  /**
   * @return the startTime
   */
  public String getStartTime() {
    return startTime;
  }

  /**
   * @param startTime
   *          the startTime to set
   */
  public void setStartTime(String startTime) {
    this.startTime = startTime;
  }

  /**
   * @return the endTime
   */
  // @JsonIgnore
  public String getEndTime() {
    return endTime;
  }

  /**
   * @param endTime
   *          the endTime to set
   */
  public void setEndTime(String endTime) {
    this.endTime = endTime;
  }

  /**
   * @return the userId
   */
  public Long getUserId() {
    return userId;
  }

  /**
   * @param userId
   *          the userId to set
   */
  public void setUserId(Long userId) {
    this.userId = userId;
  }

  /**
   * @return the userDetectedLocationId
   */
  public Long getUserDetectedLocationId() {
    return userDetectedLocationId;
  }

  /**
   * @param userDetectedLocationId
   *          the userDetectedLocationId to set
   */
  public void setUserDetectedLocationId(Long userDetectedLocationId) {
    this.userDetectedLocationId = userDetectedLocationId;
  }
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/MachineLearningTools/featureextraction/KincetARFeatureExtraction2.java<|end_filename|>
/*
Copyright [2016] [Thien]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.MachineLearningTools.featureextraction;


public class KincetARFeatureExtraction2 extends FeatureExtraction {
	double [] currentData;
	double [] previousData;
	double [] x2,y2,z2;
	double [] x1,y1,z1;
	
	// current frame index
	int[] siDinter = {2,2,2,2,2,2,3,3,3,3,3,3,3,7,7,10,11,11,20,21,21,21,22,23,23,24,24,0,0,1,1,2,2,2,2,2,3,3,4,4,4,6,6,6,7,8,8,8,8,9,10,10,10,11,11,13,13,16,16,17,17,17,17,17,17,17,20,20,20,20,20,20,20,20,20,20,22,22,23,23,23,24,24,0,0,0,0,0,0,1,1,1,1,1,2,2,2,2,2,2};
	// previous frame index
	int[] sjDinter = {7,11,16,21,23,24,7,10,11,21,22,23,24,2,3,3,2,3,21,2,3,20,3,2,3,2,3,2,20,10,17,0,6,10,17,22,6,17,10,13,23,2,3,20,20,11,17,23,24,17,1,2,20,8,20,4,17,2,20,1,2,3,8,9,13,20,0,6,7,10,11,16,17,22,23,24,2,20,4,8,20,8,20,1,3,4,5,6,21,0,13,14,18,19,4,8,12,13,14,15};
	// current frame index
	int[] siAinter = {2,2,2,3,3,3,3,5,5,5,8,14,14,14,15,15,15,15,17,17,18,18,18,19,19,19,19,19,20,20,0,0,0,0,0,0,0,1,1,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,3,3,3,3,4,5,5,6,6,6,6,7,10,10,11,11,11,11,12,12,12,12,12,12,12,13,13,13,14,14,14,14,14,15,15,15,15,16,16,16,16,16,16,17,17,17};
	// previous frame index
	int[] sjAinter = {12,14,15,0,5,12,15,3,17,18,18,2,3,4,2,3,4,20,2,8,1,4,8,1,2,8,9,20,12,15,1,2,3,8,13,20,23,0,2,11,14,20,23,24,0,1,17,18,19,4,6,11,14,16,17,18,19,24,1,11,13,3,17,18,23,3,0,12,0,3,12,16,1,2,3,8,13,20,23,2,8,9,1,8,9,13,20,5,8,9,13,2,3,9,13,20,23,1,3,9};
	
	
	public void setInputData(double[] previousData, double[] currentData){
		this.previousData = previousData;
		this.currentData = currentData;
		separateData();
	}
	private void separateData(){
		x1 = new double[25];
		y1 = new double[25];
		z1 = new double[25];
		
		x2 = new double[25];
		y2 = new double[25];
		z2 = new double[25];
		
		for (int i = 0;  i < 25; i++){
			x1[i]=previousData[i*3];
			y1[i]=previousData[i*3+1];
			z1[i]=previousData[i*3+2];
			
			x2[i]=currentData[i*3];
			y2[i]=currentData[i*3+1];
			z2[i]=currentData[i*3+2];
		}
		
		/*
		System.out.print("X = ");
		for (int i = 0;  i < 25; i++){
			System.out.print(x[i] + "  ");
		}
		System.out.println("");
		
		System.out.print("Y = ");
		for (int i = 0;  i < 25; i++){
			System.out.print(y[i] + "  ");
		}
		System.out.println("");
		
		System.out.print("Z = ");
		for (int i = 0;  i < 25; i++){
			System.out.print(z[i] + "  ");
		}
		System.out.println("");*/
	} 
	private double distance3dintra(int i, int j){
		double d= 0;
		try{
			d=Math.sqrt(Math.pow(x2[i]-x2[j],2)+Math.pow(y2[i]-y2[j],2)+Math.pow(z2[i]-z2[j],2));
			
		}catch(Exception e){
			//System.out.println("i = "+i + ", j = " +j);
		}
		return d;
	}
	
	private double distance3dinter(int i, int j){
		double d= 0;
		try{
			d=Math.sqrt(Math.pow(x2[i]-x1[j],2)+Math.pow(y2[i]-y1[j],2)+Math.pow(z2[i]-z1[j],2));
			
		}catch(Exception e){
			//System.out.println("i = "+i + ", j = " +j);
		}
		return d;
	}
	
	private double angle3dintra(int i,int j){
		double deltax=x2[j]-x2[i];
        double deltay=y2[j]-y2[i];
        double a = Math.atan(deltay/deltax);
        if (deltay == 0)
                        a=0;
        else if (deltay > 0 && deltax > 0)
                        a=a/(2*Math.PI);
        else if (deltay > 0 && deltax < 0)
                        a=(a+Math.PI)/(2*Math.PI);
        else if (deltay <0 && deltax < 0)
                        a=(a+Math.PI)/(2*Math.PI);
        else if (deltay <0 && deltax > 0)
                        a=(a+2*Math.PI)/(2*Math.PI);
        return a;
	}
	
	private double angle3dinter(int i,int j){
		double deltax=x2[j]-x1[i];
        double deltay=y2[j]-y1[i];
        double a = Math.atan(deltay/deltax);
        if (deltay == 0)
                        a=0;
        else if (deltay > 0 && deltax > 0)
                        a=a/(2*Math.PI);
        else if (deltay > 0 && deltax < 0)
                        a=(a+Math.PI)/(2*Math.PI);
        else if (deltay <0 && deltax < 0)
                        a=(a+Math.PI)/(2*Math.PI);
        else if (deltay <0 && deltax > 0)
                        a=(a+2*Math.PI)/(2*Math.PI);
        return a;
	}
	
	 public double[] extractDistanceFeatureInter(){
		 int numFeatures = siDinter.length;
		 double[] features = new double[numFeatures];
		 for (int i = 0; i < numFeatures; i++){
			 features[i]=distance3dinter(siDinter[i],sjDinter[i]);
		 }
		 return features;
	 }
	 
	 public double[] extractAngleFeatureInter(){
		 int numFeatures = siAinter.length;
		 double[] features = new double[numFeatures];
		 for (int i = 0; i < numFeatures; i++){
			 features[i]=angle3dinter(siAinter[i],sjAinter[i]);
		 }
		 return features;
	 }
	 
	@Override
	public Object extractFeature(Object input) {
		// TODO Auto-generated method stub
		
		return null;
	}
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/ic/FoodLog.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.ic;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author Taqdir
 */
@Entity
public class FoodLog implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private Long foodLogID;
    private Long userId;
    private String foodName;
    //private GregorianCalendar startTime;
   // private GregorianCalendar endTime;
    private String eatingTime;
   
    private String startTime;
    private String endTime;

    private Long TotalFoodItem; 
    private Long TotalFat;
    private Long TotalProtein;
    private Long TotalCarbohydrate;
   
    private String requestType;
    
    private byte[] byteImage;
    
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof FoodLog)) {
            return false;
        }
        FoodLog other = (FoodLog) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.ic.FoodLog[ id=" + id + " ]";
    }

    /**
     * @return the foodLogID
     */
    public Long getFoodLogID() {
        return foodLogID;
    }

    /**
     * @param foodLogID the foodLogID to set
     */
    public void setFoodLogID(Long foodLogID) {
        this.foodLogID = foodLogID;
    }

    /**
     * @return the userId
     */
    public Long getUserId() {
        return userId;
    }

    /**
     * @param userId the userId to set
     */
    public void setUserId(Long userId) {
        this.userId = userId;
    }

    /**
     * @return the foodName
     */
    public String getFoodName() {
        return foodName;
    }

    /**
     * @param foodName the foodName to set
     */
    public void setFoodName(String foodName) {
        this.foodName = foodName;
    }

    /**
     * @return the eatingTime
     */
    public String getEatingTime() {
        return eatingTime;
    }

    /**
     * @param eatingTime the eatingTime to set
     */
    public void setEatingTime(String eatingTime) {
        this.eatingTime = eatingTime;
    }

    /**
     * @return the startTime
     */
    public String getStartTime() {
        return startTime;
    }

    /**
     * @param startTime the startTime to set
     */
    public void setStartTime(String startTime) {
        this.startTime = startTime;
    }

    /**
     * @return the endTime
     */
    public String getEndTime() {
        return endTime;
    }

    /**
     * @param endTime the endTime to set
     */
    public void setEndTime(String endTime) {
        this.endTime = endTime;
    }

    /**
     * @return the requestType
     */
    public String getRequestType() {
        return requestType;
    }

    /**
     * @param requestType the requestType to set
     */
    public void setRequestType(String requestType) {
        this.requestType = requestType;
    }

    /**
     * @return the TotalFoodItem
     */
    public Long getTotalFoodItem() {
        return TotalFoodItem;
    }

    /**
     * @param TotalFoodItem the TotalFoodItem to set
     */
    public void setTotalFoodItem(Long TotalFoodItem) {
        this.TotalFoodItem = TotalFoodItem;
    }

    /**
     * @return the TotalFat
     */
    public Long getTotalFat() {
        return TotalFat;
    }

    /**
     * @param TotalFat the TotalFat to set
     */
    public void setTotalFat(Long TotalFat) {
        this.TotalFat = TotalFat;
    }

    /**
     * @return the TotalProtein
     */
    public Long getTotalProtein() {
        return TotalProtein;
    }

    /**
     * @param TotalProtein the TotalProtein to set
     */
    public void setTotalProtein(Long TotalProtein) {
        this.TotalProtein = TotalProtein;
    }

    /**
     * @return the TotalCarbohydrate
     */
    public Long getTotalCarbohydrate() {
        return TotalCarbohydrate;
    }

    /**
     * @param TotalCarbohydrate the TotalCarbohydrate to set
     */
    public void setTotalCarbohydrate(Long TotalCarbohydrate) {
        this.TotalCarbohydrate = TotalCarbohydrate;
    }

    /**
     * @return the byteImage
     */
    public byte[] getByteImage() {
        return byteImage;
    }

    /**
     * @param byteImage the byteImage to set
     */
    public void setByteImage(byte[] byteImage) {
        this.byteImage = byteImage;
    }
    
}


<|start_filename|>data-curation-layer/data-persistence/sendHDFS.js<|end_filename|>

/**
 * @author <NAME>
 * @since 2016.11.21
 * @version 0.1

 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at

 *   http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


/**
 * @description Send the data to HDFS using by HTTP.
 * @description "webhdfs-client.js" file has information about HDFS(host, user, port...).
 * @module sendHDFS
 * @param {number} - metadata for HDFS file name.
 */

var config = require('./config.json');
var localFilePath = config.filePath_local;
var HDFSFilePath = config.filePath_HDFS;

exports.wc = function(cnt){

var hdfs = require('../webhdfs-client');
var fs = require('fs');

var filepath =  + cnt;
var localFileStream = fs.createReadStream('./temp.txt');
var remoteFileStream = hdfs.createWriteStream('/kjh/'+cnt);
console.log("File write in " + filepath);

// Pipe data to HDFS
localFileStream.pipe(remoteFileStream);

// Handle errors
remoteFileStream.on('error', function onError (err) {
});
console.log("data is stored in HDFS");

};



<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/Utilities/ComputationUtilityMethods.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.Utilities;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

/**
 * 
 * @author Afzal
 */
public class ComputationUtilityMethods {
  private static Logger LOG = LogManager.getRootLogger();
  
  private ComputationUtilityMethods() {
  }

  public static ComputationUtilityMethods getComputationUtilityMethods() {
    return ComputationUtilityMethodsHolder.INSTANCE;
  }

  private AgeGroupEnum ageGroup;
  private String recGenerationDate;

  public AgeGroupEnum getAgeGroup(Date dob) {

    Date today = new Date(); // current date
    int age = today.getYear() - dob.getYear();// .get(Calendar.YEAR);

    if (today.getMonth() < dob.getMonth()) {
      age--;
    } else if (today.getMonth() == dob.getMonth()
        && (today.getDate() < dob.getDate())) {
      age--;
    }

    if (age >= 19 && age <= 45)
      ageGroup = AgeGroupEnum.Adult;
    else if (age > 45)
      ageGroup = AgeGroupEnum.Older_Adult;
    else if (age < 20)
      ageGroup = AgeGroupEnum.Young_Adult;

    return ageGroup;
  }

  /**
   * @param ageGroup
   *          the ageGroup to set
   */
  public void setAgeGroup(AgeGroupEnum ageGroup) {
    this.ageGroup = ageGroup;
  }

  /**
   * @return the recGenerationDate
   */
  public String getCurrentDate() {

    Date today = new Date();
    DateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
    // Converting date to XMLGregorianCalendar in Java
    XMLGregorianCalendar startTime = toXMLGregorianCalendar(today);

    GregorianCalendar gc = startTime.toGregorianCalendar();
    recGenerationDate = (String) sdf.format(gc.getTime());
    return recGenerationDate;
  }

  public List<String> getStartandEndTimes() {
    List<String> startEndTime = new ArrayList<String>();

    Date today = new Date();

    DateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss");

    // Converting date to XMLGregorianCalendar in Java
    XMLGregorianCalendar startTime = toXMLGregorianCalendar(today);

    startTime.setHour(00);
    startTime.setMinute(00);
    startTime.setSecond(00);

    XMLGregorianCalendar endTime = toXMLGregorianCalendar(today);

    GregorianCalendar gc;
    // Start Time coversion to String
    gc = startTime.toGregorianCalendar();
    String sTime = (String) sdf.format(gc.getTime());
    startEndTime.add(sTime);

    gc = endTime.toGregorianCalendar();
    String eTime = (String) sdf.format(gc.getTime());
    startEndTime.add(eTime);

    return startEndTime;
  }

  // utility method for date conversion
  private XMLGregorianCalendar toXMLGregorianCalendar(Date date) {

    GregorianCalendar gCalendar = new GregorianCalendar();

    gCalendar.setTime(date);

    XMLGregorianCalendar xmlCalendar = null;

    try {
      xmlCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(
          gCalendar);
    } catch (DatatypeConfigurationException ex) {
      ex.printStackTrace();
    }

    return xmlCalendar;

  }

  private static class ComputationUtilityMethodsHolder {

    private static final ComputationUtilityMethods INSTANCE = new ComputationUtilityMethods();
  }

  public String GenderConversion(int gender) {
    if (gender == 1)
      return "Male";
    else if (gender == 2)
      return "Female";
    else
      return "Unknown";
  }
  
  /**
   * Converts stringJson to map and list rules from it.
   * 
   * @param stringRules
   * @return List rules
   */
  public static Map<String, Object> getMap(String json) {
    Map<String, Object> map = new HashMap<String, Object>();
    ObjectMapper mapper = new ObjectMapper();
    try {
      map = mapper.readValue(json, new TypeReference<HashMap<String, Object>>() {});
    } catch (Exception e) {
      e.printStackTrace();
    }
    return map;
  }
  
  /**
   * converts String time to seconds and returns
   * 
   * @param time
   * @return seconds
   */
  public int timeToSec(String time) {
    time = time.replaceAll(" ", "").toLowerCase();
    if (time.length() < 2) {
      LOG.error("Invalid Time Format: " + time);
      return 0;
    }
    String[] timeParts = time.split(":");
    int seconds = 0;
    for (String part : timeParts) {
      if (part == null || part.length() == 1) {
        continue;
      }
      seconds += getSeconds(part);
    }
    return seconds;
  }
  
  /**
   * converts String part of time to seconds and returns
   * <p>
   * 
   * @param timePart
   * @return seconds
   */
  public int getSeconds(String timePart) {
    int secs = 0;
    if (timePart.contains("h")) {
      timePart = timePart.replace("h", "");
      if (timePart.length() < 1) {
        LOG.error("Invalid hours: " + timePart);
        return 0;
      }
      int hour = Integer.parseInt(timePart);
      secs = hour * 3600;
    } else if (timePart.contains("m")) {
      timePart = timePart.replace("m", "");
      if (timePart.length() < 1) {
        LOG.error("Invalid minutes: " + timePart);
        return 0;
      }
      int minute = Integer.parseInt(timePart);
      secs = minute * 60;
    } else {
      if (timePart.contains("s")) {
        timePart = timePart.replace("s", "");
        if (timePart.length() < 1) {
          LOG.error("Invalid seconds: " + timePart);
          return 0;
        }
        secs = Integer.parseInt(timePart);
      }
    }
    return secs;
  }
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/ContextOntologyManager/ContextQueryManager.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.ContextOntologyManager;
/**
 * Context Query Manager : Component of Context Ontology Manager which provides 
 * the sup-parts and functionalities to design SPARQL Queries
 * and interect with Context Query Generator.
 *
 * @author <NAME>
 * @version 2.5
 * @since 2016-10-28
 */
public class ContextQueryManager {
}


<|start_filename|>data-curation-layer/active-data-reader/src/test/java/org/uclab/mm/dcl/adr/test/HiveTest.java<|end_filename|>
/*
 * Copyright (C) 2016 <NAME>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License....
 */

package org.uclab.mm.dcl.adr.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class HiveTest {
	
	private static String driverName = "org.apache.hive.jdbc.HiveDriver";
	 
	  /**
	   * @param args
	   * @throws SQLException
	   */
	  public static void main(String[] args) throws SQLException {
	      try {
	      Class.forName(driverName);
	    } catch (ClassNotFoundException e) {
	      // TODO Auto-generated catch block
	      e.printStackTrace();
	      System.exit(1);
	    }
	    //replace "hive" here with the name of the user the queries should run as
	    Connection con = DriverManager.getConnection("jdbc:hive2://192.168.3.11:10000/test1", "hive", "hive");
	    Statement stmt = con.createStatement();
	    String tableName = "testHiveDriverTable";
	   
	    // Testing >> show tables
	    String sql = "show tables '" + tableName + "'";
	    System.out.println("Running: " + sql);
	    ResultSet res = stmt.executeQuery(sql);
	    if (res.next()) {
	      System.out.println(res.getString(1));
	    }
	       // Testing >> describe table
	    sql = "describe " + tableName;
	    System.out.println("Running: " + sql);
	    res = stmt.executeQuery(sql);
	    while (res.next()) {
	      System.out.println(res.getString(1) + "\t" + res.getString(2));
	    }
	 
	  	 
	    // Testing Query  >> select * query
	    sql = "select * from " + tableName;
	    System.out.println("Running: " + sql);
	    res = stmt.executeQuery(sql);
	    while (res.next()) {
	      System.out.println(String.valueOf(res.getInt(1)) + "\t" + res.getString(2));
	    }
	 
	    // Testing Regular Query  >> select * query regular hive query
	    sql = "select count(1) from " + tableName;
	    System.out.println("Running: " + sql);
	    res = stmt.executeQuery(sql);
	    while (res.next()) {
	      System.out.println(res.getString(1));
	    }
	  }
}


<|start_filename|>data-curation-layer/passive-data-reader/src/main/java/com/uclab/dcl/Schemasl.java<|end_filename|>
package com.uclab.dcl;
import java.util.ArrayList;
/**
 * this module is test module
 * you can test the schema of table using this module
 * @author CSHSC
 *
 */
public class Schemasl {

	private final String schema_id;
	private final String schema_name;
	private final ArrayList<Object> schema_tables;

	public Schemasl(String schema_id, String schema_name, ArrayList<Object> schema_tables) {
		this.schema_id = schema_id;
		this.schema_name = schema_name;
		this.schema_tables = schema_tables;
	}

	public String getSchema_id() {
		return schema_id;
	}

	public String getSchema_name() {
		return schema_name;
	}

	public ArrayList<Object> getSchema_tables() {
		return schema_tables;
	}

}

<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/test/TestRetrieveHLC.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.test;

import java.util.Iterator;

import mm.icl.hlc.ContextOntologyManager.ContextHandler;
import mm.icl.hlc.ContextOntologyManager.ContextOntologyManager;
import mm.icl.hlc.OntologyTools.Context;

public class TestRetrieveHLC {
	
	static final String directory ="E:\\ICL_LOG\\TDB";         
	
	static final String sparqlQueryHlc = 
			"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> "
			+ "PREFIX owl: <http://www.w3.org/2002/07/owl#> "
			+ "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> "
			+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "
			+ "PREFIX icl2: <http://www.miningminds.re.kr/icl/context/context-v2-5.owl#> "
			+ "SELECT ?hlc " //count(?hlc) As ?cnt "//?hlc "
			+ "WHERE { "
			+ "?hlc rdf:type icl2:PhysicalActivityContext. " //PhysicalActivityContext NutritionContext
			+ "} ";
//			+ "Group by ?hlc";
		
		
	public static void main(String[] args) {
	

		ContextOntologyManager mng = new ContextOntologyManager(directory);
		
		if(mng.correctInitialization()) {
			Iterator<Context> it = ContextHandler.retrieveContextInstancesMatchingSparqlQuery(sparqlQueryHlc).iterator();
			while(it.hasNext()) {
				//your code that maeks async errors
				    try{
				    	System.out.println("------------------------");
				
				    	Context inst = it.next();
				    	inst.getCtxModel().write(System.out, "RDF/XML");
//						inst.getCtxModel().write(System.out, "Turtle");
				    	Thread.sleep(1);      ///////////////////////////// if want to add delay for visibility 5000
				    
				}
			catch(InterruptedException e){}
			}
		}
		else  {
			System.out.println("No HLC because there are no LLC _________");
		}
	}
}

<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/HLCBuilder/ContextInstantiator.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.HLCBuilder;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import com.hp.hpl.jena.ontology.AllValuesFromRestriction;
import com.hp.hpl.jena.ontology.ComplementClass;
import com.hp.hpl.jena.ontology.DatatypeProperty;
import com.hp.hpl.jena.ontology.EnumeratedClass;
import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.ontology.ObjectProperty;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.ontology.SomeValuesFromRestriction;
import com.hp.hpl.jena.rdf.model.ModelFactory;

import mm.icl.hlc.OntologyTools.ContextOntology;
import mm.icl.hlc.OntologyTools.HLCA;
import mm.icl.hlc.OntologyTools.LowLevelContext;
import mm.icl.hlc.OntologyTools.NutritionContext;
import mm.icl.hlc.OntologyTools.ClinicalContext;
import mm.icl.hlc.OntologyTools.PhysicalActivityContext;
/**
 * Context Instantiator. Subcomponent of the HLC Builder which generates
 * unclassified HLC instances from concurrent LLC instances.
 * 
 * @author <NAME> & <NAME>
 * @version 2.5
 * @since 2015-11-06
 */
public class ContextInstantiator {
	/**
	 * Context Ontology which represents the Mining Minds Context Model.
	 */
	private ContextOntology ont;
	/**
	 * Identifier of the Context Instantiator.
	 */
	private int instantiatiorId;
	/**
	 * Counter of the number HLC instances generated by the Context
	 * Instantiator.
	 */
	private long hlcInstNum;
	/**
	 * Constructor of a new Context Instantiator.
	 * 
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 */
	public ContextInstantiator(ContextOntology ont) {
		this.ont = ont;
		Random rand = new Random();
		this.instantiatiorId = rand.nextInt(Integer.MAX_VALUE);
		this.hlcInstNum = 0;
	}
	/**
	 * Method to generate a new HLC Instance due to the start of a LLC.
	 * 
	 * @param llc
	 *            Low Level Context which start is the trigger for the
	 *            generation of the new HLC.
	 * @param listLlcConc
	 *            List of Low Level Context Instances which are concurrent at
	 *            the start time of llc.
	 * @return PhysicalActivity and Nutrition Context are composed of the llc and the listLlcConc, and
	 *         which starts at the start of llc.
	 */
	public PhysicalActivityContext instantiateNewHlcDueToLlcStart(LowLevelContext llc, List<LowLevelContext> listLlcConc) {
		OntModel hlcModel = createHlcModel();
		Individual hlcIndiv = createHlcIndiv(hlcModel);
		setUserForHlc(hlcIndiv, llc);
		setStartTimeForHlcDueToLlcStart(hlcIndiv, llc);
		boolean act = false;
		boolean loc = false;
		boolean emo = false;
		boolean foo = false;
		boolean bg = false;
		boolean bp = false;
		boolean wi = false;
		switch (llc.getLlcCategoryName()) {
		case HLCA.activityClassName:
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getActivityProp());
			act = true;
			break;
		case HLCA.locationClassName:
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getLocationProp());
			loc = true;
			break;
		case HLCA.emotionClassName:
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getEmotionProp());
			emo = true;
			break;
		case HLCA.BloodGlucoseClassName:
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getBloodGlucoseProp());
			bg = true;
			break;
		case HLCA.BloodPressureClassName:
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getBloodPressureProp());
			bp= true;
			break;
		case HLCA.WaterIntakeClassName:
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getWaterIntakeProp());
			wi = true;
			break;
		case HLCA.eggClassName:      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.fruitClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.grainClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.legumesClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.meatClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.milkdairyClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.nutsClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.seafoodClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.snacksClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.vegClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		}
		Iterator<LowLevelContext> itConc = listLlcConc.iterator();
		while (itConc.hasNext()) {
			LowLevelContext llcConc = itConc.next();
			switch (llcConc.getLlcCategoryName()) {
			case HLCA.activityClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getActivityProp());
				act = true;
				break;
			case HLCA.locationClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getLocationProp());
				loc = true;
				break;
			case HLCA.emotionClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getEmotionProp());
				emo = true;
				break;
			case HLCA.BloodGlucoseClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getBloodGlucoseProp());
				bg = true;
				break;
			case HLCA.BloodPressureClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getBloodPressureProp());
				bp = true;
				break;
			case HLCA.WaterIntakeClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getWaterIntakeProp());
				wi = true;
				break;
			case HLCA.eggClassName:      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.fruitClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.grainClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.legumesClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.meatClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.milkdairyClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.nutsClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.seafoodClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.snacksClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.vegClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			}
		}
		if (!act)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.activityClassName),
					ont.getActivityProp());
		if (!loc)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.locationClassName),
					ont.getLocationProp());
		if (!emo)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.emotionClassName),
					ont.getEmotionProp());
		if (!bg)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.BloodGlucoseClassName),
					ont.getBloodGlucoseProp());
		if (!bp)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.BloodPressureClassName),
					ont.getBloodPressureProp());
		if (!wi)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.WaterIntakeClassName),
					ont.getWaterIntakeProp());
		if (!foo)   //Asif
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.foodClassName),
					ont.getFoodProp());
		this.hlcInstNum++;
		return new PhysicalActivityContext(hlcModel);
	}
	/**
	 * Method to generate a new HLC Instance due to the start of a LLC.
	 * 
	 * @param llc
	 *            Low Level Context which start is the trigger for the
	 *            generation of the new HLC.
	 * @param listLlcConc
	 *            List of Low Level Context Instances which are concurrent at
	 *            the start time of llc.
	 * @return PhysicalActivity and Nutrition Context composed of the llc and the listLlcConc, and
	 *         which starts at the start of llc.
	 */
	public NutritionContext instantiateNewNutHlcDueToLlcStart(LowLevelContext llc, List<LowLevelContext> listLlcConc) {
		OntModel hlcModel = createHlcModel();
		Individual hlcIndiv = createNutHlcIndiv(hlcModel);
		setUserForHlc(hlcIndiv, llc);
		setStartTimeForHlcDueToLlcStart(hlcIndiv, llc);
		boolean act = false;
		boolean loc = false;
		boolean emo = false;
		boolean foo = false;
		boolean bg = false;
		boolean bp = false;
		boolean wi  = false;
		switch (llc.getLlcCategoryName()) {
		case HLCA.activityClassName:
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getActivityProp());
			act = true;
			break;
		case HLCA.locationClassName:
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getLocationProp());
			loc = true;
			break;
		case HLCA.emotionClassName:
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getEmotionProp());
			emo = true;
			break;
		case HLCA.BloodGlucoseClassName:
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getBloodGlucoseProp());
			bg = true;
			break;
		case HLCA.BloodPressureClassName:
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getBloodPressureProp());
			bp= true;
			break;
		case HLCA.WaterIntakeClassName:
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getWaterIntakeProp());
			wi = true;
			break;
		case HLCA.eggClassName:      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.fruitClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.grainClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.legumesClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.meatClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.milkdairyClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.nutsClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.seafoodClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.snacksClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.vegClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		}
		Iterator<LowLevelContext> itConc = listLlcConc.iterator();
		while (itConc.hasNext()) {
			LowLevelContext llcConc = itConc.next();
			switch (llcConc.getLlcCategoryName()) {
			case HLCA.activityClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getActivityProp());
				act = true;
				break;
			case HLCA.locationClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getLocationProp());
				loc = true;
				break;
			case HLCA.emotionClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getEmotionProp());
				emo = true;
				break;
			case HLCA.BloodGlucoseClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getBloodGlucoseProp());
				bg = true;
				break;
			case HLCA.BloodPressureClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getBloodPressureProp());
				bp = true;
				break;
			case HLCA.WaterIntakeClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getWaterIntakeProp());
				wi = true;
				break;
			case HLCA.eggClassName:      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.fruitClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.grainClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.legumesClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.meatClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.milkdairyClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.nutsClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.seafoodClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.snacksClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.vegClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			}
		}
		if (!act)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.activityClassName),
					ont.getActivityProp());
		if (!loc)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.locationClassName),
					ont.getLocationProp());
		if (!emo)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.emotionClassName),
					ont.getEmotionProp());
		if (!bg)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.BloodGlucoseClassName),
					ont.getBloodGlucoseProp());
		if (!bp)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.BloodPressureClassName),
					ont.getBloodPressureProp());
		if (!wi)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.WaterIntakeClassName),
					ont.getWaterIntakeProp());
		if (!foo)   //Asif
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.foodClassName),
					ont.getFoodProp());
		this.hlcInstNum++;
		return new NutritionContext(hlcModel);
	}
	/*
	 * Method to generate a new HLC Instance due to the start of a LLC.
	 * 
	 * @param llc
	 *            Low Level Context which start is the trigger for the
	 *            generation of the new HLC.
	 * @param listLlcConc
	 *            List of Low Level Context Instances which are concurrent at
	 *            the start time of llc.
	 * @return PhysicalActivity and Nutrition Context composed of the llc and the listLlcConc, and
	 *         which starts at the start of llc.
	 */
	public ClinicalContext instantiateNewCliHlcDueToLlcStart(LowLevelContext llc, List<LowLevelContext> listLlcConc) {
		OntModel hlcModel = createHlcModel();
		Individual hlcIndiv = createCliHlcIndiv(hlcModel);
		setUserForHlc(hlcIndiv, llc);
		setStartTimeForHlcDueToLlcStart(hlcIndiv, llc);
		boolean act = false;
		boolean loc = false;
		boolean emo = false;
		boolean foo = false;
		boolean bg = false;
		boolean bp = false;
		boolean wi  = false;
		switch (llc.getLlcCategoryName()) {
		case HLCA.activityClassName:
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getActivityProp());
			act = true;
			break;
		case HLCA.locationClassName:
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getLocationProp());
			loc = true;
			break;
		case HLCA.emotionClassName:
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getEmotionProp());
			emo = true;
			break;
		case HLCA.BloodGlucoseClassName:
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getBloodGlucoseProp());
			bg = true;
			break;
		case HLCA.BloodPressureClassName:
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getBloodPressureProp());
			bp= true;
			break;
		case HLCA.WaterIntakeClassName:
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getWaterIntakeProp());
			wi = true;
			break;
		case HLCA.eggClassName:      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.fruitClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.grainClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.legumesClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.meatClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.milkdairyClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.nutsClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.seafoodClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.snacksClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		case HLCA.vegClassName :      
			setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llc, ont.getFoodProp());
			foo = true;
			break;
		}
		Iterator<LowLevelContext> itConc = listLlcConc.iterator();
		while (itConc.hasNext()) {
			LowLevelContext llcConc = itConc.next();
			switch (llcConc.getLlcCategoryName()) {
			case HLCA.activityClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getActivityProp());
				act = true;
				break;
			case HLCA.locationClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getLocationProp());
				loc = true;
				break;
			case HLCA.emotionClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getEmotionProp());
				emo = true;
				break;
			case HLCA.BloodGlucoseClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getBloodGlucoseProp());
				bg = true;
				break;
			case HLCA.BloodPressureClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getBloodPressureProp());
				bp = true;
				break;
			case HLCA.WaterIntakeClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getWaterIntakeProp());
				wi = true;
				break;
			case HLCA.eggClassName:      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.fruitClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.grainClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.legumesClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.meatClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.milkdairyClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.nutsClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.seafoodClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.snacksClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.vegClassName :      
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			}
		}
		if (!act)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.activityClassName),
					ont.getActivityProp());
		if (!loc)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.locationClassName),
					ont.getLocationProp());
		if (!emo)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.emotionClassName),
					ont.getEmotionProp());
		if (!bg)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.BloodGlucoseClassName),
					ont.getBloodGlucoseProp());
		if (!bp)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.BloodPressureClassName),
					ont.getBloodPressureProp());
		if (!wi)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.WaterIntakeClassName),
					ont.getWaterIntakeProp());
		if (!foo)   //Asif
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.foodClassName),
					ont.getFoodProp());
		this.hlcInstNum++;
		return new ClinicalContext(hlcModel);
	}
	/**
	 * Method to generate a new HLC Instance due to the end of a LLC.
	 * 
	 * @param llc
	 *            Low Level Context which end is the trigger for the generation
	 *            of the new HLC.
	 * @param listLlcConc
	 *            List of Low Level Context Instances which are concurrent at
	 *            the end time of llc.
	 * @return PhysicalActivity and Nutrition Context composed of the listLlcConc and which starts
	 *         at the end of llc.
	 */
	public PhysicalActivityContext instantiateNewHlcDueToLlcEnd(LowLevelContext llc, List<LowLevelContext> listLlcConc) {
		OntModel hlcModel = createHlcModel();
		Individual hlcIndiv = createHlcIndiv(hlcModel);
		setUserForHlc(hlcIndiv, llc);
		setStartTimeForHlcDueToLlcEnd(hlcIndiv, llc);
		boolean act = false;
		boolean loc = false;
		boolean emo = false;
		boolean foo = false;
		boolean bg = false; 
		boolean bp = false; 
		boolean wi = false; 
		Iterator<LowLevelContext> itConc = listLlcConc.iterator();
		while (itConc.hasNext()) {
			LowLevelContext llcConc = itConc.next();
			switch (llcConc.getLlcCategoryName()) {
			case HLCA.activityClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getActivityProp());
				act = true;
				break;
			case HLCA.locationClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getLocationProp());
				loc = true;
				break;
			case HLCA.emotionClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getEmotionProp());
				emo = true;
				break;
			case HLCA.foodClassName: 
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.BloodGlucoseClassName: 
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getBloodGlucoseProp());
				bg= true;
				break;
			case HLCA.BloodPressureClassName: 
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getBloodPressureProp());
				bp= true;
				break;
			case HLCA.WaterIntakeClassName: 
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getWaterIntakeProp());
				wi = true;
				break;

			}
		}
		if (!act)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.activityClassName),
					ont.getActivityProp());
		if (!loc)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.locationClassName),
					ont.getLocationProp());
		if (!emo)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.emotionClassName),
					ont.getEmotionProp());
		if (!foo)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.foodClassName),
					ont.getFoodProp());
		if (!bg)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.BloodGlucoseClassName),
					ont.getBloodGlucoseProp());
		if (!bp)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.BloodPressureClassName),
					ont.getBloodPressureProp());
		if (!wi)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.WaterIntakeClassName),
					ont.getWaterIntakeProp());
		this.hlcInstNum++;
		return new PhysicalActivityContext(hlcModel);
	}
	/**
	 * Method to generate a new HLC Instance due to the end of a LLC.
	 * 
	 * @param llc
	 *            Low Level Context which end is the trigger for the generation
	 *            of the new HLC.
	 * @param listLlcConc
	 *            List of Low Level Context Instances which are concurrent at
	 *            the end time of llc.
	 * @return PhysicalActivity and Nutrition Context composed of the listLlcConc and which starts
	 *         at the end of llc.
	 */
	public NutritionContext instantiateNewNutHlcDueToLlcEnd(LowLevelContext llc, List<LowLevelContext> listLlcConc) {
		OntModel hlcModel = createHlcModel();
		Individual hlcIndiv = createNutHlcIndiv(hlcModel);
		setUserForHlc(hlcIndiv, llc);
		setStartTimeForHlcDueToLlcEnd(hlcIndiv, llc);
		boolean act = false;
		boolean loc = false;
		boolean emo = false;
		boolean foo = false; 
		boolean bg = false; 
		boolean bp = false; 
		boolean wi = false; 
		Iterator<LowLevelContext> itConc = listLlcConc.iterator();
		while (itConc.hasNext()) {
			LowLevelContext llcConc = itConc.next();
			switch (llcConc.getLlcCategoryName()) {
			case HLCA.activityClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getActivityProp());
				act = true;
				break;
			case HLCA.locationClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getLocationProp());
				loc = true;
				break;
			case HLCA.emotionClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getEmotionProp());
				emo = true;
				break;
			case HLCA.foodClassName: 
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.BloodGlucoseClassName: 
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getBloodGlucoseProp());
				bg= true;
				break;
			case HLCA.BloodPressureClassName: 
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getBloodPressureProp());
				bp= true;
				break;
			case HLCA.WaterIntakeClassName: 
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getWaterIntakeProp());
				wi = true;
				break;				
			}
		}
		if (!act)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.activityClassName),
					ont.getActivityProp());
		if (!loc)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.locationClassName),
					ont.getLocationProp());
		if (!emo)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.emotionClassName),
					ont.getEmotionProp());
		if (!foo)  //Asif
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.foodClassName),
					ont.getFoodProp());
		if (!bg)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.BloodGlucoseClassName),
					ont.getBloodGlucoseProp());
		if (!bp)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.BloodPressureClassName),
					ont.getBloodPressureProp());
		if (!wi)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.WaterIntakeClassName),
					ont.getWaterIntakeProp());
		this.hlcInstNum++;
		return new NutritionContext(hlcModel);
	}
	/**
	 * Method to generate a new HLC Instance due to the end of a LLC.
	 * 
	 * @param llc
	 *            Low Level Context which end is the trigger for the generation
	 *            of the new HLC.
	 * @param listLlcConc
	 *            List of Low Level Context Instances which are concurrent at
	 *            the end time of llc.
	 * @return PhysicalActivity and Nutrition Context composed of the listLlcConc and which starts
	 *         at the end of llc.
	 */
	public ClinicalContext instantiateNewCliHlcDueToLlcEnd(LowLevelContext llc, List<LowLevelContext> listLlcConc) {
		OntModel hlcModel = createHlcModel();
		Individual hlcIndiv = createNutHlcIndiv(hlcModel);
		setUserForHlc(hlcIndiv, llc);
		setStartTimeForHlcDueToLlcEnd(hlcIndiv, llc);
		boolean act = false;
		boolean loc = false;
		boolean emo = false;
		boolean foo = false; 
		boolean bg = false; 
		boolean bp = false; 
		boolean wi = false; 
		Iterator<LowLevelContext> itConc = listLlcConc.iterator();
		while (itConc.hasNext()) {
			LowLevelContext llcConc = itConc.next();
			switch (llcConc.getLlcCategoryName()) {
			case HLCA.activityClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getActivityProp());
				act = true;
				break;
			case HLCA.locationClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getLocationProp());
				loc = true;
				break;
			case HLCA.emotionClassName:
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getEmotionProp());
				emo = true;
				break;
			case HLCA.foodClassName: 
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getFoodProp());
				foo = true;
				break;
			case HLCA.BloodGlucoseClassName: 
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getBloodGlucoseProp());
				bg= true;
				break;
			case HLCA.BloodPressureClassName: 
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getBloodPressureProp());
				bp= true;
				break;
			case HLCA.WaterIntakeClassName: 
				setLlcBeingPartOfHlc(hlcModel, hlcIndiv, llcConc, ont.getWaterIntakeProp());
				wi = true;
				break;				
			}
		}
		if (!act)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.activityClassName),
					ont.getActivityProp());
		if (!loc)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.locationClassName),
					ont.getLocationProp());
		if (!emo)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.emotionClassName),
					ont.getEmotionProp());
		if (!foo)  //Asif
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.foodClassName),
					ont.getFoodProp());
		if (!bg)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.BloodGlucoseClassName),
					ont.getBloodGlucoseProp());
		if (!bp)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.BloodPressureClassName),
					ont.getBloodPressureProp());
		if (!wi)
			setNoLlcBeingPartOfHlc(hlcModel, hlcIndiv, ont.getLlcCategoryClass(HLCA.WaterIntakeClassName),
					ont.getWaterIntakeProp());
		this.hlcInstNum++;
		return new ClinicalContext(hlcModel);
	}
	
	/**
	 * Method to create the OntModel associated to a new HLC.
	 * 
	 * @return OntModel associated to a new HLC.
	 */
	private OntModel createHlcModel() {
		OntModel hlcModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);
		hlcModel.setNsPrefix(HLCA.nsPrefix, HLCA.ns);
		return hlcModel;
	}
	/**
	 * Method to create an individual of the HLC class which represents the new
	 * HLC instance.
	 * 
	 * @param hlcModel
	 *            OntModel associated to the new HLC in which the individual
	 *            will be created.
	 * @return Individual representing the HLC instance.
	 */
	private Individual createHlcIndiv(OntModel hlcModel) {
		return hlcModel.createIndividual(HLCA.ns + "hlc_" + String.format("%010d", this.instantiatiorId) + "_"
				+ String.format("%019d", this.hlcInstNum), ont.getHlcClass());
	}
	/**
	 * Method to create an individual of the HLC class which represents the new
	 * HLC instance.
	 * 
	 * @param hlcModel
	 *            OntModel associated to the new HLC in which the individual
	 *            will be created.
	 * @return Individual representing the HLC instance.
	 */
	private Individual createNutHlcIndiv(OntModel hlcModel) {
		return hlcModel.createIndividual(HLCA.ns + "hlc_" + String.format("%010d", this.instantiatiorId) + "_"
				+ String.format("%019d", this.hlcInstNum), ont.getNutHlcClass());
	}
	/**
	 * Method to create an individual of the HLC class which represents the new
	 * HLC instance.
	 * 
	 * @param hlcModel
	 *            OntModel associated to the new HLC in which the individual
	 *            will be created.
	 * @return Individual representing the HLC instance.
	 */
	private Individual createCliHlcIndiv(OntModel hlcModel) {
		return hlcModel.createIndividual(HLCA.ns + "hlc_" + String.format("%010d", this.instantiatiorId) + "_"
				+ String.format("%019d", this.hlcInstNum), ont.getClinicalHlcClass());
	}
	/**
	 * Method to set the User in the HLC instance, i.e., to assert the value of
	 * the property which links the PhysicalActivity and Nutrition Context to the User it belongs
	 * to.
	 * 
	 * @param hlcIndiv
	 *            Individual representing the HLC instance.
	 * @param llc
	 *            Low Level Context which triggered the creation of the HLC and
	 *            from which the User should be obtained.
	 */
	private void setUserForHlc(Individual hlcIndiv, LowLevelContext llc) {
		ObjectProperty ctxOfProp = ont.getContextOfProp();
		hlcIndiv.addProperty(ctxOfProp, llc.getObjectPropertyValue(ctxOfProp));
	}
	/**
	 * Method to set the start time of the HLC instance, i.e., to assert the
	 * value of the property which links the PhysicalActivity and Nutrition Context to its start
	 * time.
	 * 
	 * @param hlcIndiv
	 *            Individual representing the HLC instance.
	 * @param llc
	 *            Low Level Context which start triggered the creation of the
	 *            HLC and from which the start time should be obtained.
	 */
	private void setStartTimeForHlcDueToLlcStart(Individual hlcIndiv, LowLevelContext llc) {
		DatatypeProperty startTimeProp = ont.getStartTimeProp();
		hlcIndiv.addProperty(startTimeProp, llc.getDataPropertyValue(startTimeProp));
	}
	/**
	 * Method to set the start time of the HLC instance, i.e., to assert the
	 * value of the property which links the PhysicalActivity and Nutrition Context to its start
	 * time.
	 * 
	 * @param hlcIndiv
	 *            Individual representing the HLC instance.
	 * @param llc
	 *            Low Level Context which end triggered the creation of the HLC
	 *            and from which the start time should be obtained.
	 */
	private void setStartTimeForHlcDueToLlcEnd(Individual hlcIndiv, LowLevelContext llc) {
		hlcIndiv.addProperty(ont.getStartTimeProp(), llc.getDataPropertyValue(ont.getEndTimeProp()));
	}
	/**
	 * Method to set in a HLC instance the LLC instance which is part of it.
	 * This means asserting the value of the property which links the High Level
	 * Context to the Low Level Context and asserting the class which states
	 * that this LLC instance is the only value that the property can take. The
	 * type assertion is necessary in order to overcome the Open World
	 * Assumption of OWL.
	 * 
	 * @param hlcModel
	 *            OntModel associated to the HLC instance.
	 * @param hlcIndiv
	 *            Individual representing the HLC instance.
	 * @param llc
	 *            Low Level Context which should be set as part of the HLC.
	 * @param llcProp
	 *            ObjectProperty linking the HLC to the LLC which is part of it.
	 */
	private void setLlcBeingPartOfHlc(OntModel hlcModel, Individual hlcIndiv, LowLevelContext llc,
			ObjectProperty llcProp) {
		Individual llcIndiv = llc.getCtxIndiv();
		hlcIndiv.addProperty(llcProp, llcIndiv);
		EnumeratedClass llcEnumClass = hlcModel.createEnumeratedClass(null, null);
		llcEnumClass.addOneOf(llcIndiv);
		AllValuesFromRestriction llcRestr = hlcModel.createAllValuesFromRestriction(null, llcProp, llcEnumClass);
		hlcIndiv.addOntClass(llcRestr);
		hlcModel.add(llc.getCtxModel());
	}
	/**
	 * Method to set in a HLC instance that there is no LLC instance of a given
	 * category, e.g., Activity, Location, food or Emotion) being part of it. This
	 * type assertion is necessary in order to overcome the Open World
	 * Assumption of OWL.
	 * 
	 * @param hlcModel
	 *            OntModel associated to the HLC instance.
	 * @param hlcIndiv
	 *            Individual representing the HLC instance.
	 * @param llcCategoryClass
	 *            OntClass representing the LLC Category for which there is no
	 *            LLC instance.
	 * @param llcProp
	 *            ObjectProperty linking the HLC to the LLC Category for which
	 *            there is no LLC instance.
	 */
	private void setNoLlcBeingPartOfHlc(OntModel hlcModel, Individual hlcIndiv, OntClass llcCategoryClass,
			ObjectProperty llcProp) {
		SomeValuesFromRestriction llcRestr = hlcModel.createSomeValuesFromRestriction(null, llcProp, llcCategoryClass);
		ComplementClass llcCompl = hlcModel.createComplementClass(null, llcRestr);
		hlcIndiv.addOntClass(llcCompl);
	}
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/dc/UserRiskFactors.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.dc;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author Taqdir
 */
@Entity
public class UserRiskFactors implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private  Long userRiskFactorId;
    private Long userId;
    private int riskFactorId;
    private int statusId;
    
    
    
    
    

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof UserRiskFactors)) {
            return false;
        }
        UserRiskFactors other = (UserRiskFactors) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.dc.UserRiskFactors[ id=" + id + " ]";
    }

    /**
     * @return the userRiskFactorId
     */
    public Long getUserRiskFactorId() {
        return userRiskFactorId;
    }

    /**
     * @param userRiskFactorId the userRiskFactorId to set
     */
    public void setUserRiskFactorId(Long userRiskFactorId) {
        this.userRiskFactorId = userRiskFactorId;
    }

    /**
     * @return the userId
     */
    public Long getUserId() {
        return userId;
    }

    /**
     * @param userId the userId to set
     */
    public void setUserId(Long userId) {
        this.userId = userId;
    }

    /**
     * @return the riskFactorId
     */
    public int getRiskFactorId() {
        return riskFactorId;
    }

    /**
     * @param riskFactorId the riskFactorId to set
     */
    public void setRiskFactorId(int riskFactorId) {
        this.riskFactorId = riskFactorId;
    }

    /**
     * @return the statusId
     */
    public int getStatusId() {
        return statusId;
    }

    /**
     * @param statusId the statusId to set
     */
    public void setStatusId(int statusId) {
        this.statusId = statusId;
    }
    
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/AER/vui/OutputAdapter.java<|end_filename|>
/*
Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.AER.vui;

public class OutputAdapter {
	private String userId;
	private String deviceId;
	private String timestamp;
	private String label;
	private String processedData;
	
	public void setUserId(String userId) {
		this.userId = userId;
	}
	
	public void setDeviceId(String deviceId) {
		this.deviceId = deviceId;
	}
	
	public void setTimestamp(String timestamp) {
		this.timestamp = timestamp;
	}
	
	public void setLabel(String label) {
		this.label = label;
	}
	
	public String getProcessedData() {
		return processedData;
	}
	
	public void attachMetadata() {
		processedData = String.format("{\"user_id\":\"%s\",\"device_id\":\"%s\",\"timestamp\":\"%s\",\"label\":\"%s\"}", userId, deviceId, timestamp, label);
	}
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/utils/FileUtil.java<|end_filename|>
/**
* 
** Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileUtil {
	public static void WriteHLCLog(String str){
		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(new File("E:/ICL_LOG/hlcLog.txt"), true));
			bw.write(str);
			bw.newLine();
			bw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void WriteLLCLog(String str){
		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(new File("E:/ICL_LOG/hlcLog.txt"), true));
			bw.write(str);
			bw.newLine();
			bw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/config/ICLConfig.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Kang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.mm.icl.llc.config;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.json.JSONObject;
import org.uclab.mm.icl.ConfigJsonGenerator;
import org.uclab.mm.icl.utils.FileUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


/**
 * ICL configuration class. Gets the input from external configuration file, iclconfig.json
 * @author Nailbrainz
 *
 */
public class ICLConfig {
	
	public static final ArrayList<Integer> contextWindowSize = new ArrayList<Integer>();
	public static final ArrayList<Boolean> isRecogOn = new ArrayList<Boolean>();
	
	public static AtomicInteger delay = new AtomicInteger(9);
	public static final String DCLAddress;
	public static final String LLCAddress;
	public static final String HLCAddress;
	
	public static final int HLCDelay;
	
	
	public static void reInitialize(){
		
	}
	
	//The window size will be initialized when 
	static{
		File configFile = new File(FileUtil.getRootPath()+"/iclconfig.json");
		Scanner scan;
		String content = "";
		try {
			scan = new Scanner(configFile);
			scan.useDelimiter("\\Z");  
			content = scan.next(); 
			scan.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			try {
				ConfigJsonGenerator.configGenerator(configFile);
				scan = new Scanner(configFile);
				scan.useDelimiter("\\Z");  
				content = scan.next(); 
				scan.close();
			} catch (FileNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}  
		
		JSONObject configJson = new JSONObject(content);
		if(configJson.has("WindowConfig")){
			JSONObject recogWindow = configJson.getJSONObject("WindowConfig");
			for(ContextType ct : ContextType.values()){
				if(recogWindow.has(ct.name()))contextWindowSize.add(recogWindow.getInt(ct.name()));
				else contextWindowSize.add( ct.getDefaultWindowSize());
			}
		}
		DCLAddress = configJson.getString("DCLAddress");
		LLCAddress = configJson.getString("LLCAddress");
		HLCAddress = configJson.getString("HLCAddress");
		
		if(configJson.has("ActiveRecognizers")){
			JSONObject activeRecogs = configJson.getJSONObject("ActiveRecognizers");
			for(RecognizerType ct : RecognizerType.values()){
				if(activeRecogs.has(ct.name()))isRecogOn.add(activeRecogs.getBoolean(ct.name()));
				else isRecogOn.add(true);
			}
		}
		HLCDelay = configJson.getInt("HLCDelay");
	}
	
	
}


<|start_filename|>knowledge-curation-layer/DDKAT/src/main/java/org/uclab/mm/kcl/ddkat/productionmodel/Rule.java<|end_filename|>
/**
 * Copyright [2017] [<NAME>, <NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.mm.kcl.ddkat.productionmodel;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

//TODO: Auto-generated Javadoc
/**
* This class defines the model/structure of the rules.
*/
public class Rule implements Serializable {

	private static final long serialVersionUID = 1L;
	
	/** The rule id. */
	private int RuleID;
	
	/** The conditions list. */	
    private List<Condition> conditionList = new ArrayList<Condition>();
	
    /** The conclusion list. */
    private List<Conclusion> conclusionList = new ArrayList<Conclusion>();

	public Rule(){}
	
	public int getRuleID(){
    	return RuleID;
    }
	
	public void setRuleID(int ruleID) {
		RuleID = ruleID;
	} 

	public List<Condition> getConditionList() {
		return conditionList;
	}

	public void setConditionList(List<Condition> conditionList) {
		this.conditionList = conditionList;
	}
	
	public List<Conclusion> getConclusionList() {
		return conclusionList;
	}

	public void setConclusionList(List<Conclusion> conclusionList) {
		this.conclusionList = conclusionList;
	}
		
}


<|start_filename|>knowledge-curation-layer/DDKAT/src/main/java/org/uclab/mm/kcl/ddkat/controllers/RuleSharingController.java<|end_filename|>
/**
* Copyright [2017] [<NAME>, <NAME>]
* 
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.uclab.mm.kcl.ddkat.controllers;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.uclab.mm.kcl.ddkat.productionmodel.Rule;
import org.uclab.mm.kcl.ddkat.services.IClassificationModelTranslator;

//TODO: Auto-generated Javadoc
/**
* This class controls the translation tasks of the classification model.
*/
@Controller
public class RuleSharingController {
	
	/** The translation interface */	
	private IClassificationModelTranslator iClassificationModelTranslator;
    
	/** The Constant log. */
	private static final Logger logger = LoggerFactory.getLogger(RuleSharingController.class);
    
	
	 /**
		 * Method to configure/set the model translation interface
		 */	
    @Autowired(required=true)
    @Qualifier(value="iClassificationModelTranslator")
    public void setIClassificationModelTranslator(IClassificationModelTranslator iClassificationModelTranslator){
        this.iClassificationModelTranslator = iClassificationModelTranslator;
    }	    
   
    
    /**
	 * Method to communicate the request/response of Web interface with iClassificationModelTranslator interface.
	 *
	 * @return the rules list
	 * @throws Exception the exception
	 */	
	// generates the rules
    @RequestMapping(value = "/shareRules", method = RequestMethod.GET)
    public @ResponseBody List<Rule> extractRules() {
    	List<Rule> rulesList = iClassificationModelTranslator.translateModel();
    	return rulesList;
    }

	public static Logger getLogger() {
		return logger;
	}
}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/framework/recbuilder/TypeComparator.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.framework.recbuilder;

public class TypeComparator {
  
  /**
   * Compares v1 and v2 based on the operator defined e.g. op and returns TRUE on success and FALSE on failure
   * <p>
   * 
   * @param v1
   * @param v2
   * @param op
   * @return boolean
   */
  public static boolean compare(String v1, String v2, String op) {
    boolean matched = false;

    if (op.equals("=")) {
      matched = v1.equalsIgnoreCase(v2);
    } else if (op.equals("!=")) {
      matched = !v1.equalsIgnoreCase(v2);
    }

    return matched;
  }
  
  /**
   * Compares v1 and v2 based on the operator defined e.g. op and returns TRUE on success and FALSE on failure
   * <p>
   * 
   * @param v1
   * @param v2
   * @param op
   * @return boolean
   */
  public static boolean compare(int v1, int v2, String op) {
    boolean matched = false;

    switch (op) {

    case "=":
      matched = v1 == v2;
      break;
    case "!=":
      matched = v1 != v2;
      break;
    case "<":
      matched = v1 < v2;
      break;
    case ">":
      matched = v1 > v2;
      break;
    case "<=":
      matched = v1 <= v2;
      break;
    case ">=":
      matched = v1 >= v2;
    }

    return matched;
  }
  
  /**
   * Compares v1 and v2 based on the operator defined e.g. op and returns TRUE on success and FALSE on failure
   * <p>
   * 
   * @param v1
   * @param v2
   * @param op
   * @return boolean
   */
  public static boolean compare(boolean v1, boolean v2, String op) {
    boolean matched = false;

    if (op.equals("=")) {
      matched = v1 == v2;
    } else if (op.equals("!=")) {
      matched = v1 != v2;
    }

    return matched;
  }
}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/communication/PhysicalActivityRecommenationWSClient.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.communication;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.uclab.scl.outputModel.RecModel.PhyActivityRecommendations;
/**
 * @version MM v2.5
 * @author Afzal
 *
 */
public class PhysicalActivityRecommenationWSClient extends AbstractRestClient<List<PhyActivityRecommendations>, List<String>> {
  public PhysicalActivityRecommenationWSClient(String baseURI) {
    super(baseURI);
  }

  @Override
  public List<PhyActivityRecommendations> GetData(String GET_ResourceURI) {
    ClientConfig config = new DefaultClientConfig();
    config.getClasses().add(JacksonJsonProvider.class);
    Client client = Client.create(config);
    WebResource service = client.resource(UriBuilder.fromUri(baseURI).build());
    List<PhyActivityRecommendations> recommendations = service.path(GET_ResourceURI).accept(MediaType.APPLICATION_JSON).get(new GenericType<List<PhyActivityRecommendations>>() {});
    if (recommendations.size() > 0)
      return recommendations;
    else
      return null;
  }

  @Override
  public List<String> PostData(String POST_ResourceURI, List<PhyActivityRecommendations> postedResource) {
    Iterator<PhyActivityRecommendations> paRecommendations = postedResource.iterator();
    List<String> phyActRecResult = new ArrayList<>();
    while (paRecommendations.hasNext()) {
      PhyActivityRecommendations phyActRec = paRecommendations.next();
      ClientConfig config = new DefaultClientConfig();
      config.getClasses().add(JacksonJsonProvider.class);
      Client client = Client.create(config);
      WebResource service = client.resource(UriBuilder.fromUri(baseURI).build());
      ClientResponse response = service.path(POST_ResourceURI).type(MediaType.APPLICATION_JSON).post(ClientResponse.class, phyActRec);
      phyActRecResult.add(response.getEntity(new GenericType<List<String>>() {}).get(0));
    }
    return phyActRecResult;
  }

}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/ConfigJsonGenerator.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Kang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.mm.icl;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import org.json.JSONObject;
import org.uclab.mm.icl.llc.config.ContextType;
import org.uclab.mm.icl.llc.config.RecognizerType;

public class ConfigJsonGenerator {
	public static void configGenerator(File f) throws FileNotFoundException{

		JSONObject configJson = new JSONObject();
		JSONObject recogWindow = new JSONObject();
		recogWindow.put(ContextType.Activity.name(), 6);
		recogWindow.put(ContextType.Emotion.name(), 9);
		recogWindow.put(ContextType.Location.name(), 12);
		configJson.put("WindowConfig", recogWindow);
		
		configJson.put("DCLAddress", "http://172.16.31.10:8080/MMDataCurationRestfulService/webresources/InformationCuration/");
		//configJson.put("LLCAddress", "http://172.16.31.10:8080/icl_whole/icl/llc/");
		//configJson.put("HLCAddress", "http://172.16.31.10:8080/icl_whole/icl/llc/");
		configJson.put("LLCAddress", "http://localhost:8080/icl_whole/icl/llc/");
		configJson.put("HLCAddress", "http://localhost:8080/icl_whole/icl/llc/");
		
		JSONObject activeRecogs = new JSONObject();
		activeRecogs.put(RecognizerType.IAR.name(), true);
		activeRecogs.put(RecognizerType.VAR.name(), true);
		activeRecogs.put(RecognizerType.ER.name(), true);
		activeRecogs.put(RecognizerType.SER.name(), true);
		activeRecogs.put(RecognizerType.LR.name(), true);
		//activeRecogs.put("Food", true);
		configJson.put("ActiveRecognizers", activeRecogs);
		
		configJson.put("HLCDelay", 20);
		
		try {
			f.createNewFile();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		PrintWriter pw = new PrintWriter(f);
		pw.write(configJson.toString());
		pw.close();
	}
	
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		
		JSONObject configJson = new JSONObject();
		JSONObject recogWindow = new JSONObject();
		recogWindow.put(ContextType.Activity.name(), 6);
		recogWindow.put(ContextType.Emotion.name(), 9);
		recogWindow.put(ContextType.Location.name(), 12);
		configJson.put("WindowConfig", recogWindow);
		
		configJson.put("DCLAddress", "http://172.16.31.10:8080/MMDataCurationRestfulService/webresources/InformationCuration/");
		//configJson.put("LLCAddress", "http://172.16.31.10:8080/icl_whole/icl/llc/");
		//configJson.put("HLCAddress", "http://172.16.31.10:8080/icl_whole/icl/llc/");
		configJson.put("LLCAddress", "http://localhost:8080/icl_whole/icl/llc/");
		configJson.put("HLCAddress", "http://localhost:8080/icl_whole/icl/llc/");
		
		JSONObject activeRecogs = new JSONObject();
		activeRecogs.put(RecognizerType.IAR.name(), true);
		activeRecogs.put(RecognizerType.VAR.name(), true);
		activeRecogs.put(RecognizerType.ER.name(), true);
		activeRecogs.put(RecognizerType.SER.name(), true);
		activeRecogs.put(RecognizerType.LR.name(), true);
		//activeRecogs.put("Food", true);
		configJson.put("ActiveRecognizers", activeRecogs);
		
		configJson.put("HLCDelay", 20);
		
		
		PrintWriter pw = new PrintWriter(new File("D:/mm2.0/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/icl_whole/WEB-INF/classes/iclconfig.json"));
		pw.write(configJson.toString());
		pw.close();
		pw = new PrintWriter(new File("D:/GIT_ICL/glassfish-4.1.1.zip/icl_whole/GIT_ICL_WHOLE/FILES/iclconfig.json"));
		pw.write(configJson.toString());
		pw.close();
		
		/*
		long userID = 35;
		
		//ExtClassification ext = new ExtClassification(null, 0, args, null);
		
		VideoActivityRecognizer vr = new VideoActivityRecognizer(userID);
		GPSLocationRecognizer gr = new GPSLocationRecognizer(userID);
		AudioEmotionRecognizer emr = new AudioEmotionRecognizer(ext, null, userID);
		
		vr.recognize(input, userID, timeStamp);
		gr.recognize(input, userID, timeStamp)
		emr.recognize(segmented, userID, timeStamp)
		
		
		
		
		
		
		
		
		for (int i=0;i<10;i++) {
			// 媛곴컖�쓽 �젅踰⑥뿉 留욎떠 濡쒓렇瑜� �궓源�
			LLogger.logger.debug("debug 濡쒓렇");
			LLogger.logger.info("info 濡쒓렇");
			LLogger.logger.warn("warn 濡쒓렇");
			LLogger.logger.error("error 濡쒓렇");
			LLogger.logger.fatal("fatal 濡쒓렇");
		}
		/*
		Scanner scan = new Scanner(new File("D:/EmoJHLog.txt"));
		String str = scan.nextLine();
		
		long summ = 0;
		long lines = 0;
		while(scan.hasNext()){
			Long time = scan.nextLong();
			summ += time;
			lines++;
		}
		
		 scan = new Scanner(new File("D:/EmoVuiLog.txt"));
		 str = scan.nextLine();
		
		while(scan.hasNext()){
			Long time = scan.nextLong();
			summ += time;
			lines++;
		}
		
		System.out.println("Time = " + summ/lines);
		/*System.out.println(str);
		JSONArray ary = new JSONArray(str);
		JSONObject obj = ary.getJSONObject(0);
		System.out.println(obj.getString("locationLabel"));
		
		FoodItem df = new FoodItem(35, "Chicken", "2016 05 12 00:00:00", null);
		System.out.println(RestClients.AddFoodLog(df));*/
		/*
		KincetARFeatureExtraction4 fr = new KincetARFeatureExtraction4();
		double[][] ary = new double[30][75];
		Scanner scan = new Scanner(new File("D:\\eating_testing.txt"));
		scan.useDelimiter(",|\r\n");
		
		for(int i = 0; i<30; i++){
			for(int j = 0; j<75; j++)ary[i][j] = scan.nextDouble();
			System.out.println(scan.nextLine());
			for(int j = 0; j<75; j++)scan.nextDouble();
			scan.nextLine();
			for(int j = 0; j<75; j++)scan.nextDouble();
			scan.nextLine();
		}
		
		for(int j = 0; j<75; j++)System.out.print(ary[29][j] + " ");
		System.out.println();
		fr.setInputData(ary);
		fr.calcFeatures();
		double[] rlt = fr.extractFeatures();
		for(int i = 0; i<rlt.length; i++)System.out.print(rlt[i] + " ");
		KinectARClassification ar = new KinectARClassification();
		System.out.println(ar.Classify(rlt));
		*/
	}

}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/AER/vui/AER_Server.java<|end_filename|>
/*
Copyright [2016] [Vui]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.AER.vui;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import org.uclab.mm.icl.data.SmartphoneData;
import org.uclab.mm.icl.llc.LLCManager.ContextLabel;

public class AER_Server {
	/*
	public static void main(String[] args) throws IOException {
		int n = 0;
		ServerSocket listener = new ServerSocket(9090);
        try {
        	System.out.println("Server is running.");
        	
            while (true) {
                Socket s = listener.accept();
                try {
                	DataInputStream in = new DataInputStream(s.getInputStream());
                	int len = in.readInt();
                	System.out.println("Data length: " + len);
                	double[] samples = new double[len];
                	for(int i = 0; i < len; i++)
                		samples[i] = in.readDouble();
                	n++;
                	AERThread thread = new AERThread("Thread " + n, samples);
                	thread.start();
                } finally {
                    s.close();
                }
            }
        }
        finally {
            listener.close();
        }
	}
	
	static class AERThread implements Runnable {
		private Thread t;
		private String threadName;
		private double[] samples;
		   
		public AERThread(String name, double[] samples) {
			this.samples = samples;
		    this.threadName = name;
		}
		   
		public void run() {
			System.out.println("Running " +  threadName );
			try {
				long startTime = System.nanoTime();
				
				SmartphoneData sd = new SmartphoneData();
				AudioEmotionRecognizerV aer = new AudioEmotionRecognizerV(35l);
				ContextLabel emo = aer.recognize(sd, sd.getTimeStamp());
				System.out.println("Classified label: " + emo.toString());
				
				long estimatedTime = System.nanoTime() - startTime;
				System.out.println("Elapsed Time - " + estimatedTime / 1000000 + " ms");
			}catch (Exception ex) {
				ex.printStackTrace();
			}
			System.out.println("Thread " +  threadName + " exiting.");
			System.out.println("----------------------------------------");
		}
		   
		public void start() {
			if (t == null) {
				t = new Thread(this, threadName);
				t.start();
			}
		}
	}
	*/
}


<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/exception/MultipleValuesException.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */
package org.uclab.mm.dcl.llm.exception;

/**
 * User defined exception for multiple values.
 * @author Rizvi
 */
public class MultipleValuesException extends Exception{
 MultipleValuesException(String s){
  super(s);
 }
 /**
  * The method return appropriate exception message.
  * @return 
  */
 public String toString()
 {
  return "Database is notreachable, kindly try little later";
 }
} 


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/MachineLearningTools/classification/Classification.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Bang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.MachineLearningTools.classification;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import org.uclab.mm.icl.llc.LLCManager.ContextLabel;

import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.core.Attribute;
import weka.core.FastVector;
import weka.core.Instance;
import weka.core.Instances;

/**
 *
 * @author Nailbrainz
 * @param <InputType> Datatype which will be used for classification 
 */
public abstract class Classification<InputType> {
    
    /**
     * 
     * @param data data to classify
     * @return classified result
     */
    abstract public String Classify(InputType data);
    
   
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/test/java/org/uclab/mm/datamodel/ic/dataadapter/testcases/UserRecognizedActivityAdapterTest.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.ic.dataadapter.testcases;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.uclab.mm.datamodel.AbstractDataBridge;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.DatabaseStorage;
import org.uclab.mm.datamodel.ic.UserRecognizedActivity;
import org.uclab.mm.datamodel.ic.dataadapter.UserRecognizedActivityAdapter;


/**
 * This is a class for testing the insertion, fetching, and update of UserRecognizedActivity
 * @author <NAME>
 *
 */
public class UserRecognizedActivityAdapterTest {

	/**
	 * This is function for testing the insertion, fetching, and update of UserRecognizedActivity 
	 */
	@Test
	public void test() {
		/* Preparing input object for insertion*/
		UserRecognizedActivity objOuterUserRecognizedActivity = new UserRecognizedActivity();
		UserRecognizedActivity objInnerUserRecognizedActivity = new UserRecognizedActivity();
		List<UserRecognizedActivity> objListUserRecognizedActivity = new  ArrayList<UserRecognizedActivity>();
		
		objOuterUserRecognizedActivity.setUserId(2L);
		objOuterUserRecognizedActivity.setActivityId(4);
		objOuterUserRecognizedActivity.setStartTime("2016 12 12 19:16:01");
	
		/* Testing of insertion function*/
		 DataAccessInterface objDAInterface = new UserRecognizedActivityAdapter();
         AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
         List<String> lstResponse = objADBridge.SaveUserRecognizedActivity(objOuterUserRecognizedActivity);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerUserRecognizedActivity.setUserId(2L);
        	 objInnerUserRecognizedActivity.setRequestType("LatestByUser");
        	 DataAccessInterface objDAInterfaceRetrieval = new UserRecognizedActivityAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListUserRecognizedActivity = objADBridgeRetrieval.RetriveUserRecognizedActivity(objInnerUserRecognizedActivity);
        	 objInnerUserRecognizedActivity = objListUserRecognizedActivity.get(0);
         }
         
         assertEquals(objOuterUserRecognizedActivity.getActivityId(), objInnerUserRecognizedActivity.getActivityId());
	}

}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/framework/RecInterpreter/Explanation/ExplanationBuilder.java<|end_filename|>
/* Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.uclab.scl.framework.RecInterpreter.Explanation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.uclab.scl.outputModel.InterpretationModel.InterpretedRecommendations;

public class ExplanationBuilder extends AbstractRecExplanation{
  private static Logger LOG = LogManager.getRootLogger();
  
  static HashMap<String, String> mapRecExp = new HashMap<>();
  static HashMap<String, String> mapExpURL = new HashMap<>();
  static HashMap<String, String> mapPostProcess = new HashMap<>();

  /**
   * Receives an input vector and provides corresponding recommendation 
   */
  public String parseAggregateVec(int[] aggregateVec) throws Exception {
    String interpRec = null;
    if (aggregateVec[0] == 1)
      interpRec = "Walking";
    else if (aggregateVec[1] == 1)
      interpRec = "Running";
    else if (aggregateVec[2] == 1)
      interpRec = "Stretching";
    else if (aggregateVec[3] == 1)
      interpRec = "Cycling";
    else if (aggregateVec[4] == 1)
      interpRec = "Sitting";
    else
      interpRec = "Default";
    
    return interpRec;
    
  }
  
  public String buildUrl(String recValue ) throws Exception{
	  return (new URLBuilder().recURLBuilder(recValue));
  }
  
  /**
   * Generates explanatory statement for the received recommendation in case the received recommendation is not accompanied with 
   * an explanatory statement moreover, post processing adds contextual information to the statement for special contexts
   * 
   * @author Imran
   * @version 2.5
   * @since September 2015
   * 
   */
  @SuppressWarnings("unchecked")
  public InterpretedRecommendations handleExplanation(int[] interpRec, String duration, String context, String description) throws Exception {
	LOG.debug("Explanation Builder");
    RecExpMapper recExpMap = new RecExpMapper();
    InterpretedRecommendations interpretedRec = new InterpretedRecommendations();
    List<String> explanationArr = new ArrayList<String>();
    String rec = this.parseAggregateVec(interpRec);
    
    LOG.debug("Recommended Activity: " + rec);
    explanationArr.add(rec);
    interpretedRec.setRecActivity(rec);
    interpretedRec.setCurrentContext(context);

    LOG.debug("Duration (mins): " + duration);
    explanationArr.add(duration);
    interpretedRec.setActDuration(duration);

    mapRecExp = recExpMap.recExpMapper();
    String recExplanationLists;
    recExplanationLists = mapRecExp.containsKey(rec) ? mapRecExp.get(rec) : mapRecExp.get(null);
 
    String[] selectExplanation = null;
    String selectedExplanation = null;

    if (recExplanationLists == null){
      LOG.debug("Recommendation NOT FOUND in the Explanation repository");
    }
    else {
      selectExplanation = recExplanationLists.split(",");
      selectedExplanation = selectExplanation[(ThreadLocalRandom.current().nextInt(0, selectExplanation.length))];
      selectedExplanation = this.explanationSentenceTemplate(rec, duration, selectedExplanation, context);
      if (description == null || description == "") {
        explanationArr.add(selectedExplanation);
        interpretedRec.setRecDescription(selectedExplanation);
      }
      else {
        explanationArr.add(description);
        interpretedRec.setRecDescription(description);
      }
    }

    return interpretedRec;
  }

  @SuppressWarnings("unchecked")
  public String explanationSentenceTemplate(String rec, String duration, String sentence, String context) throws Exception {
    PostProcessingMapper mapPostProcessing = new PostProcessingMapper();
    String template = null;
    
    mapPostProcess = mapPostProcessing.expPreprocessMapper();
    String[] contextArray = context.split(",");
    String cweatherCondition = contextArray[2];
    String cemotionCondition = contextArray[3];
    String currentWeather = null;
    String currentEmotion = null;
    
    if (cweatherCondition.equals("Rainy"))
      currentWeather = mapPostProcess.containsKey(cweatherCondition) ? mapPostProcess.get(cweatherCondition) : mapPostProcess.get(null);
    else if (cweatherCondition.equals("Sunny"))
      currentWeather = mapPostProcess.containsKey(cweatherCondition) ? mapPostProcess.get(cweatherCondition) : mapPostProcess.get(null);
    else
      currentWeather = "";
    template = sentence + " " + rec + " for "+ duration + "" + " " + currentWeather;

    if (cemotionCondition.equals("Anger"))
      currentEmotion = mapPostProcess.containsKey(cemotionCondition) ? mapPostProcess.get(cemotionCondition) : mapPostProcess.get(null);
    else if (cemotionCondition.equals("Sadness"))
      currentEmotion = mapPostProcess.containsKey(cemotionCondition) ? mapPostProcess.get(cemotionCondition) : mapPostProcess.get(null);
    else
      currentEmotion = "";
    
    template = template + " " + currentEmotion;
    return template;
  }
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/AR/var/KinectARFeatureExtraction.java<|end_filename|>
/*
Copyright [2016] [Thien]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.AR.var;

import java.util.ArrayList;

public class KinectARFeatureExtraction {
	double [] inputData;
	double [] x,y,z;
	
	int[] siD = {2,3,3,2,2,2,2,3,3,3,3,3,4,8,10,13,17,18,2,2,2,2,2,3,4,4,7,8,8,8,9,11,14,20,20,0,0,0,0,0,0,0,1,1,1,1,1,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5};
	int[] sjD = {17,10,17,10,13,14,18,11,13,14,18,23,13,17,20,20,20,20,7,11,21,23,24,24,11,17,20,10,18,23,18,20,20,23,24,1,2,3,4,8,18,20,2,3,14,18,20,6,16,19,20,6,7,12,15,16,21,22,6,7,10,14,16,18,20,21,23,24,13,14};
	int[] siA = {16,0,0,1,1,1,5,11,11,12,0,0,0,1,2,3,5,5,5,6,6,6,7,8,9,9,9,10,10,10,11,12,12,12,14,15,16,16,16,19,20,22,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4};
	int[] sjA = {23,11,23,11,23,24,10,12,16,23,13,21,24,10,12,17,11,23,24,11,23,24,23,11,10,11,23,12,16,23,23,13,21,24,16,16,20,21,24,20,23,23,1,2,3,4,7,10,15,20,22,2,14,15,20,5,14,15,18,11,12,13,14,15,16,18,19,11,23,24};
	
	// 	Call the function of data reconstruction
	public void setInputData(double[] inputData) {
		this.inputData = inputData;
		separateData();
	}
	
	public void setIndex(ArrayList<ArrayList<Integer>> listIndex) {
		for (int i = 0; i < 70; i++) {
			siD[i] = listIndex.get(0).get(i);
			sjD[i] = listIndex.get(1).get(i);
			siA[i] = listIndex.get(2).get(i);
			sjA[i] = listIndex.get(3).get(i);
		}
	}
	
	// Get the size of angle feature
	public int getAngleFeatureSize(){
		return siA.length;
	}
	
	// 	Get the size of angle feature
	public int getDistanceFeatureSize(){
		return siD.length;
	}
	/** Re-construct the data from DCL for processing
	 *	One vector data with 75 values of x,y, and z to three vectors with 25 values
	 *	25 values corresponding to 25 joints of each complete skeleton
	 */
	private void separateData(){
		x = new double[25];
		y = new double[25];
		z = new double[25];
		for (int i = 0;  i < 25; i++){
			x[i]=inputData[i*3];
			y[i]=inputData[i*3+1];
			z[i]=inputData[i*3+2];
		}
	} 
	
	/** Calculating a distance feature between joint i and j
	 *	This is the Euclidean distance
	 */
	private double distance3d(int i, int j){
		double d= 0;
		try{
			d=Math.sqrt(Math.pow(x[i]-x[j],2)+Math.pow(y[i]-y[j],2)+Math.pow(z[i]-z[j],2));			
		}catch(Exception e){
		}
		return d;
	}
	
	/**	Calculating an angle feature between joint i and j
	 *	This is the angle between vector ij and horizontal axis on the plane z=0
	 */
	private double angle3d(int i,int j){
		double deltax=x[j]-x[i];
        double deltay=y[j]-y[i];
        double a = Math.atan(deltay/deltax);
		//	Normalizing angle from degree to gradian
        if (deltay == 0)
                        a=0;
        else if (deltay > 0 && deltax > 0)
                        a=a/(2*Math.PI);
        else if (deltay > 0 && deltax < 0)
                        a=(a+Math.PI)/(2*Math.PI);
        else if (deltay <0 && deltax < 0)
                        a=(a+Math.PI)/(2*Math.PI);
        else if (deltay <0 && deltax > 0)
                        a=(a+2*Math.PI)/(2*Math.PI);
        return a;
	}
	
	/**	Calculating all distance features between 70 pre-identified joints
	 *	These joints are pre-identified based on the feature selection technique to only
	 *	calculate the most important features
	 */
	 public double[] extractDistanceFeature(){
		 int numFeatures = siD.length;
		 double[] features = new double[numFeatures];
		 for (int i = 0; i < numFeatures; i++){
			 features[i]=distance3d(siD[i],sjD[i]);
		 }
		 return features;
	 }
	/**Calculating all angle features between 70 pre-identified joints
	 *	These joints are pre-identified based on the feature selection technique to only
	 *	calculate the most important features
	 */
	 public double[] extractAngleFeature(){
		 int numFeatures = siA.length;
		 double[] features = new double[numFeatures];
		 for (int i = 0; i < numFeatures; i++){
			 features[i]=angle3d(siA[i],sjA[i]);
		 }
		 return features;
	 }

}

<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/monitoring/LifeLogMonitoring.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */
package org.uclab.mm.dcl.llm.monitoring;


import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.uclab.mm.dcl.llm.dataaccess.DBConnection;
import org.uclab.mm.dcl.llm.exception.DatabaseConnectionProblem;

/**
 * This is the main class to start the physical activity monitoring. 
 * Physical activities are monitored after every 3 seconds.
 * 
 * @author Rizvi
 */
public class LifeLogMonitoring implements Runnable{

  private static Connection conn = null;
  static org.apache.log4j.Logger log = Logger.getLogger(NutritionMonitor.class.getName());
  /**
   * @param args the command line arguments
   */
  static MonitoringContext objMonitoringContext = null;
/**
 * The main method is used to start the process of physical activities monitoring.
 * Monitoring is performed after every 3 seconds.
 * Time taken by each 
 * @param args
 * @throws SQLException
 * @throws IOException 
 */
 /* public static void main(String[] args) throws SQLException, IOException{
    args = new String[]{"3"};
    try{
      BasicConfigurator.configure();

      log.info("..........welcome for testing.........");
      conn = DBConnection.getDBConnection().getConnection();
      if (conn == null){
        throw new DatabaseConnectionProblem("cant open database.");
      }
      objMonitoringContext = new MonitoringContext(new PhysicalActivityMonitor());
      if (args.length == 0){
        log.info(" plz enter the number of second duration");
        System.exit(0);
      }
      int timelimit = Integer.parseInt(args[0]);
      for (int i = 0; i > -1; i++){
        log.info(" timer : " + i * timelimit + "Sec");
        long startTime = System.currentTimeMillis();
        objMonitoringContext.executeStrategy(conn, "3");
        long endTime = System.currentTimeMillis();
        log.info("That took " + (endTime - startTime) + " milliseconds");
        log.info("-------------------------------");
        Thread.sleep(timelimit * 1000);
      }
    } catch (DatabaseConnectionProblem | SQLException | InterruptedException exp){
      log.error("error exception in database connectivity", exp);
    }

  }*/
	public void startMonitoring(String[] args) throws SQLException, IOException {
		args = new String[] { "3" };
		try {
			BasicConfigurator.configure();
			
			log.info("..........welcome for testing.........");
		      conn = DBConnection.getDBConnection().getConnection();
		      if (conn == null){
		        throw new DatabaseConnectionProblem("cant open database.");
		      }
		      objMonitoringContext = new MonitoringContext(new PhysicalActivityMonitor());
		      if (args.length == 0){
		        log.info(" plz enter the number of second duration");
		        System.exit(0);
		      }
		      int timelimit = Integer.parseInt(args[0]);
		      for (int i = 0; i > -1; i++){
		        log.info(" timer : " + i * timelimit + "Sec");
		        long startTime = System.currentTimeMillis();
		        objMonitoringContext.executeStrategy(conn, "3");
		        long endTime = System.currentTimeMillis();
		        log.info("That took " + (endTime - startTime) + " milliseconds");
		        log.info("-------------------------------");
		        Thread.sleep(timelimit * 1000);
		      }
		    } catch (DatabaseConnectionProblem | SQLException | InterruptedException exp){
		      log.error("error exception in database connectivity", exp);
		    }
	}
  
  @Override
	public synchronized void run() {
		try {
			this.startMonitoring(null);
		} catch (SQLException ex) {
			java.util.logging.Logger.getLogger(
					LifeLogMonitoring.class.getName()).log(Level.SEVERE, null, ex);
		} catch (IOException ex) {
			java.util.logging.Logger.getLogger(
					LifeLogMonitoring.class.getName()).log(Level.SEVERE, null,
					ex);
		} catch (IllegalThreadStateException ex) {
			java.util.logging.Logger.getLogger(
					LifeLogMonitoring.class.getName()).log(Level.SEVERE, null,
					ex);
		}
	}

}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/LLCServer.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Kang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.uclab.mm.icl.data.SmartphoneData;
import org.uclab.mm.icl.llc.LLCManager.SensoryDataRouter;
import org.uclab.mm.icl.llc.LLCManager.User;
import org.uclab.mm.icl.llc.config.DeviceType;
import org.uclab.mm.icl.utils.TimeUtil;

import com.hp.hpl.jena.ontology.OntModel;
import com.sun.jersey.core.util.Base64;

/**
 * LLC server instance
 * @author <NAME>, Kang
 *
 */
public class LLCServer {
	private final static Logger logger = Logger.getLogger(LLCServer.class);
	OntModel ontModel;
	ServerSocket server;
	Socket socket;
	ICLServerThread thread;
	TimeUtil util = new TimeUtil();
	final static ExecutorService es = Executors.newCachedThreadPool();  //we have to share users among all different LLCServer
	
	
	/**
	 * returns the server thread
	 * 
	 * @return current server thread instance
	 */
	public ICLServerThread getST() {
		return thread;
	}

	/**
	 * returns the instance of corresponding user. When it cannot find any,
	 * instantiate the user and returns the new one
	 * 
	 * @param userID
	 *            user ID to get/generate instance
	 * @return user instance corresponding to user id
	 */
	public User getUser(long userID) {
		if (MainServlet.getUserMap().get(userID) == null) {
			logger.info("User null, creating new user");
			User user =new User(userID, es);
			MainServlet.getUserMap().put(userID, user);
		}
		return MainServlet.getUserMap().get(userID);
	}

	public User getUserDemo(long userID) {
		return MainServlet.getUserMap().get(userID);
	}

	
	
	/**
	 * Routes the sensory data from smartphone to user
	 * 
	 * @param sd
	 *            sensory data to route
	 */
	public void RouteData(DeviceType it, Object data) {
		//call the router with input data
		es.execute(new SensoryDataRouter(it, data, this));
	}

	
	/**
	 * Initiate ICL server with socket
	 * 
	 * @param port port number to assign socket server
	 */
	public LLCServer(int port) {
		final LLCServer thisServ = this;
		es.execute(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					server = new ServerSocket(port);
					logger.info("ICL Server started at " + port);
					while (true) {
						socket = server.accept();
						thread = new ICLServerThread(server, socket, thisServ);
						thread.start();
					}
				} catch (IOException ioe) {
					logger.error("Exception occured at accepting socket from smartphone");
					logger.error(ioe);
				}
			}
		});

	}

}


<|start_filename|>data-curation-layer/active-data-reader/src/main/java/org/uclab/mm/dcl/adr/model/DetectedLocation.java<|end_filename|>
/*
 * Copyright (C) 2016 <NAME>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.mm.dcl.adr.model;

public class DetectedLocation {

	private int userdetectedlocationid;
	private int userid;
	private String locationlabel;
	private String starttime;
	private String endtime;
	private int duration;

	/**
	 * @return the userdetectedlocationid
	 */
	public int getUserdetectedlocationid() {
		return userdetectedlocationid;
	}

	/**
	 * @param userdetectedlocationid
	 *            the userdetectedlocationid to set
	 */
	public void setUserdetectedlocationid(int userdetectedlocationid) {
		this.userdetectedlocationid = userdetectedlocationid;
	}

	/**
	 * @return the userid
	 */
	public int getUserid() {
		return userid;
	}

	/**
	 * @param userid
	 *            the userid to set
	 */
	public void setUserid(int userid) {
		this.userid = userid;
	}

	/**
	 * @return the locationlabel
	 */
	public String getLocationlabel() {
		return locationlabel;
	}

	/**
	 * @param locationlabel
	 *            the locationlabel to set
	 */
	public void setLocationlabel(String locationlabel) {
		this.locationlabel = locationlabel;
	}

	/**
	 * @return the starttime
	 */
	public String getStarttime() {
		return starttime;
	}

	/**
	 * @param starttime
	 *            the starttime to set
	 */
	public void setStarttime(String starttime) {
		this.starttime = starttime;
	}

	/**
	 * @return the endtime
	 */
	public String getEndtime() {
		return endtime;
	}

	/**
	 * @param endtime
	 *            the endtime to set
	 */
	public void setEndtime(String endtime) {
		this.endtime = endtime;
	}

	/**
	 * @return the duration
	 */
	public int getDuration() {
		return duration;
	}

	/**
	 * @param duration
	 *            the duration to set
	 */
	public void setDuration(int duration) {
		this.duration = duration;
	}

	/**
	 * @param userdetectedlocationid
	 * @param userid
	 * @param locationlabel
	 * @param starttime
	 * @param endtime
	 * @param duration
	 */
	public DetectedLocation(int userdetectedlocationid, int userid, String locationlabel, String starttime,
			String endtime, int duration) {
		super();
		this.userdetectedlocationid = userdetectedlocationid;
		this.userid = userid;
		this.locationlabel = locationlabel;
		this.starttime = starttime;
		this.endtime = endtime;
		this.duration = duration;
	}

	/**
	 * Generate the constructor.
	 */
	public DetectedLocation() {
		super();
		// TODO Auto-generated constructor stub
	}

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/test/java/org/uclab/mm/datamodel/dc/dataadapter/testcases/UserDisabilitiesAdapterTest.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.dc.dataadapter.testcases;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.uclab.mm.datamodel.AbstractDataBridge;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.DatabaseStorage;
import org.uclab.mm.datamodel.dc.UserDisabilities;
import org.uclab.mm.datamodel.dc.dataadapter.UserDisabilitiesAdapter;
/**
 * This is a class for testing the insertion, fetching, and update of UserDisabilities
 * @author <NAME>
 *
 */
public class UserDisabilitiesAdapterTest {

	/**
	 * This is function for testing the insertion, fetching, and update of UserDisabilities 
	 */
	@Test
	public void test() {
		/* Preparing input object for insertion*/
		UserDisabilities objOuterUserDisabilities = new UserDisabilities();
		UserDisabilities objInnerUserDisabilities = new UserDisabilities();
		List<UserDisabilities> objListUserDisabilities = new  ArrayList<UserDisabilities>();
		
		objOuterUserDisabilities.setUserID(2L);
		objOuterUserDisabilities.setDisabilityID(1);
		objOuterUserDisabilities.setStatusID(1);
	
		/* Testing of insertion function*/
		 DataAccessInterface objDAInterface = new UserDisabilitiesAdapter();
         AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
         List<String> lstResponse = objADBridge.SaveUserDisabilities(objOuterUserDisabilities);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerUserDisabilities.setUserID(2L);
        	 DataAccessInterface objDAInterfaceRetrieval = new UserDisabilitiesAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListUserDisabilities = objADBridgeRetrieval.RetriveUserDisabilities(objInnerUserDisabilities);
        	 objInnerUserDisabilities = objListUserDisabilities.get(0);
         }
         
         assertEquals(objOuterUserDisabilities.getDisabilityID(), objInnerUserDisabilities.getDisabilityID());
         
         /* Testing of Update function*/
         objInnerUserDisabilities.setDisabilityID(2);
         DataAccessInterface objDAInterfaceUpdate = new UserDisabilitiesAdapter();
         AbstractDataBridge objADBridgeUpdate = new DatabaseStorage(objDAInterfaceUpdate);
         lstResponse = objADBridgeUpdate.UpdateUserDisabilities(objInnerUserDisabilities);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerUserDisabilities.setUserID(2L);
        	 DataAccessInterface objDAInterfaceRetrieval = new UserDisabilitiesAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListUserDisabilities = objADBridgeRetrieval.RetriveUserDisabilities(objInnerUserDisabilities);
        	 objInnerUserDisabilities = objListUserDisabilities.get(0);
         }
         
         assertEquals(objInnerUserDisabilities.getDisabilityID(), 2);
	}

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/dc/dataadapter/UserScheduleAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.dc.dataadapter;


import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.dc.UserSchedule;
/**
 * This is UserScheduleAdapter class which implements the Data Access Interface for CRUD operations
 * @author <NAME>
 */
public class UserScheduleAdapter implements DataAccessInterface {

    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(UserScheduleAdapter.class);
    public UserScheduleAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving UserSchedule. 
     * @param objUserSchedule
     * @return List of String
     */
    @Override
    public List<String> Save(Object objUserSchedule) {
        UserSchedule objInnerUserSchedule = new UserSchedule();
        objInnerUserSchedule =  (UserSchedule) objUserSchedule;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_UserSchedule(?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserID", objInnerUserSchedule.getUserID());
            objCallableStatement.setString("ScheduledTask", objInnerUserSchedule.getScheduledTask());
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
            if(objInnerUserSchedule.getStartTime() != null )
            {
                 Date dtStartDate = sdf.parse(objInnerUserSchedule.getStartTime());
                 Timestamp tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);
                 objCallableStatement.setTimestamp("StartTime", tsStartDate);
            }
            else
            { objCallableStatement.setTimestamp("StartTime", null); }
            if(objInnerUserSchedule.getEndTime()!= null)
            {
                Date dtEndDate = sdf.parse(objInnerUserSchedule.getEndTime());
                Timestamp tsEndDate = new Timestamp(dtEndDate.getYear(),dtEndDate.getMonth(), dtEndDate.getDate(), dtEndDate.getHours(), dtEndDate.getMinutes(),dtEndDate.getSeconds(),0);
                objCallableStatement.setTimestamp("EndTime", tsEndDate);
            }
            else
            { objCallableStatement.setTimestamp("EndTime", null); }
                
            if(objInnerUserSchedule.getExtra()!= null)
            {
                objCallableStatement.setString("Extra", objInnerUserSchedule.getExtra());
            }
            else
            { objCallableStatement.setString("Extra", objInnerUserSchedule.getExtra()); }
            
            objCallableStatement.registerOutParameter("UserScheduleID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intUserScheduleID = objCallableStatement.getLong("UserScheduleID");
            objDbResponse.add(String.valueOf(intUserScheduleID));
            objDbResponse.add("No Error");
            objConn.close();
            logger.info(" User Schedule saved successfully, User Details="+objUserSchedule);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding User Schedule");
        	objDbResponse.add("Error in adding User Schedule");
        }   
        
        return objDbResponse;
    }

    /**
     * This is implementation function for updating UserSchedule. 
     * @param objUserSchedule
     * @return List of String
     */
    @Override
    public List<String> Update(Object objUserSchedule) {
        UserSchedule objInnerUserSchedule = new UserSchedule();
        objInnerUserSchedule =  (UserSchedule) objUserSchedule;
        List<String> objDbResponse = new ArrayList<>();
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_UserSchedule(?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserScheduleID", objInnerUserSchedule.getUserScheduleID());
            objCallableStatement.setLong("UserID", objInnerUserSchedule.getUserID());
            objCallableStatement.setString("ScheduledTask", objInnerUserSchedule.getScheduledTask());
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
            if(objInnerUserSchedule.getStartTime() != null )
            {
                 Date dtStartDate = sdf.parse(objInnerUserSchedule.getStartTime());
                 Timestamp tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);
                 objCallableStatement.setTimestamp("StartTime", tsStartDate);
            }
            else
            { objCallableStatement.setTimestamp("StartTime", null); }
            if(objInnerUserSchedule.getEndTime()!= null)
            {
                Date dtEndDate = sdf.parse(objInnerUserSchedule.getEndTime());
                Timestamp tsEndDate = new Timestamp(dtEndDate.getYear(),dtEndDate.getMonth(), dtEndDate.getDate(), dtEndDate.getHours(), dtEndDate.getMinutes(),dtEndDate.getSeconds(),0);
                objCallableStatement.setTimestamp("EndTime", tsEndDate);
            }
            else
            { objCallableStatement.setTimestamp("EndTime", null); }
                
            if(objInnerUserSchedule.getExtra()!= null)
            {
                objCallableStatement.setString("Extra", objInnerUserSchedule.getExtra());
            }
            else
            { objCallableStatement.setString("Extra", objInnerUserSchedule.getExtra()); }
            
            objCallableStatement.execute();
            
            Long intUserScheduleID = objInnerUserSchedule.getUserScheduleID();
            objDbResponse.add(String.valueOf(intUserScheduleID));
            objDbResponse.add("No Error");
            objConn.close();
            logger.info("User Schedule saved successfully, User Details="+objUserSchedule);
        }
        catch (Exception e)
        {
        	logger.info("Error in updated User Schedule");
        	objDbResponse.add("Error in updated User Schedule");
        }   
        
        return objDbResponse;
    }

    /**
     * This is implementation function for retrieving UserSchedule.
     * @param objUserSchedule
     * @return List of UserSchedule 
     */
    @Override
    public List<UserSchedule> RetriveData(Object objUserSchedule) {
        UserSchedule objOuterUserSchedule = new UserSchedule();
        List<UserSchedule> objListInnerUserSchedule = new ArrayList<UserSchedule>();
        objOuterUserSchedule =  (UserSchedule) objUserSchedule;
        
        try
        {
            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UserScheduleByUserID(?, ?, ?)}");
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
            Date dtStartDate = sdf.parse(objOuterUserSchedule.getStartTime());
            Timestamp tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);
            
            Date dtEndDate =sdf.parse( objOuterUserSchedule.getEndTime()); //.getTime();
            Timestamp tsEndDate = new Timestamp(dtEndDate.getYear(),dtEndDate.getMonth(), dtEndDate.getDate(), dtEndDate.getHours(), dtEndDate.getMinutes(),dtEndDate.getSeconds(),0);
                        
            objCallableStatement.setLong("UserID", objOuterUserSchedule.getUserID());
            objCallableStatement.setTimestamp("StartTime", tsStartDate);
            objCallableStatement.setTimestamp("EndTime", tsEndDate);
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                UserSchedule objInnerUserSchedule = new UserSchedule();
                objInnerUserSchedule.setUserScheduleID(objResultSet.getLong("UserScheduleID"));
                objInnerUserSchedule.setUserID(objResultSet.getLong("UserID"));
                objInnerUserSchedule.setScheduledTask(objResultSet.getString("ScheduledTask"));
               
                
                tsStartDate = objResultSet.getTimestamp("StartTime"); //updated
                objInnerUserSchedule.setStartTime(tsStartDate.toString());
                
                tsEndDate = objResultSet.getTimestamp("EndTime"); // updated
                objInnerUserSchedule.setEndTime(tsEndDate.toString());
                
                if(objResultSet.getString("Extra") != null)
                {
                    objInnerUserSchedule.setExtra(objResultSet.getString("Extra"));
                }
                objListInnerUserSchedule.add(objInnerUserSchedule);
            }
            objConn.close();
            logger.info("User Schedule loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading User Schedule");
        }   
        return objListInnerUserSchedule;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet."); 
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/utils/TimeUtil.java<|end_filename|>
package org.uclab.mm.icl.utils;

/*
Copyright [2016] [<NAME>, Kang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;


public class TimeUtil {
	static SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss", Locale.KOREA);//"yyyy:MM:dd_HH:mm:ss.SSS"
	static SimpleDateFormat demoSdf = new SimpleDateFormat("HH:mm:ss", Locale.KOREA);//"yyyy:MM:dd_HH:mm:ss.SSS"
	static SimpleDateFormat fileName = new SimpleDateFormat("HHmmss", Locale.KOREA);//"yyyy:MM:dd_HH:mm:ss.SSS"
	
	
	public String toDemoStr(Calendar cal){
		synchronized(this){
			String formatted = demoSdf.format(cal.getTime());
			return formatted;
		}
	}
	
	public String parseCal(Calendar cal){
		synchronized(this){
			String formatted = sdf.format(cal.getTime());
			return formatted;
		}
	}
	
	public Calendar parseString(String str){
		synchronized(this){
			Calendar cal = Calendar.getInstance();
			try {
				cal.setTime(sdf.parse(str));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return cal;
		}
	}
	
	public String getFileName(){
		synchronized(this){
			Calendar cal = Calendar.getInstance();
		    return fileName.format(cal.getTime());
		}
	}
	public String getTime(){
		synchronized(this){
			Calendar cal = Calendar.getInstance();
		    return sdf.format(cal.getTime());
		}
	}
	public static long getCurTime(){
		return System.nanoTime();
	}
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/OntologyTools/InferredContextOntology.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.OntologyTools;
import java.util.Iterator;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.reasoner.StandardValidityReport;
import com.hp.hpl.jena.reasoner.ValidityReport;
import com.hp.hpl.jena.reasoner.ValidityReport.Report;
/**
 * InferredContextOntology extends the ContextOntology class in order to provide
 * the mechanisms to validate the Context Ontology which represents the Mining
 * Minds Context Model.
 * 
 * @author <NAME> and <NAME>
 * @version 2.5
 * @since 2015-10-28
 */
public class InferredContextOntology extends ContextOntology {
	/**
	 * Constructor of a new InferredContextOntology
	 * 
	 * @param ctxModel
	 *            OntModel associated to the inferred version of the Context
	 *            Ontology which represents the Mining Minds Context Model.
	 */
	public InferredContextOntology(OntModel ctxModel) {
		super(ctxModel);
	}
	/**
	 * Method to validate the Context Ontology which represents the Mining Minds
	 * Context Model.
	 * 
	 * @return true if the Context Ontology passed the consistency check, and
	 *         false otherwise.
	 */
	public boolean isValid() {
		return (validate().isValid());
	}
	/**
	 * Method to validate the Context Ontology which represents the Mining Minds
	 * Context Model.
	 * 
	 * @return Validity Report which contains the description of the errors in
	 *         the consistency check of the Context Ontology.
	 */
	public ValidityReport validate() {
		ValidityReport validity = ctxModel.validate();
		if (validity.isValid()) {
			if (!validity.isClean()) {
				StandardValidityReport report = new StandardValidityReport();
				report.add(true, "Context Ontology contains errors in the class definition", "");
				Iterator<Report> it = validity.getReports();
				while (it.hasNext())
					report.add(it.next());
				return report;
			}
			if (ctxModel.getNsURIPrefix(HLCA.ns) == null) {
				StandardValidityReport report = new StandardValidityReport();
				report.add(true, "Context Ontology does not contain the namespace", HLCA.ns);
				return report;
			}
			if (ctxModel.getOntClass(HLCA.pacClassName) == null) { 
				StandardValidityReport report = new StandardValidityReport();
				report.add(true, "Context Ontology does not contain the PAC class", HLCA.pacClassName); 
				return report;
			}
			if (ctxModel.getOntClass(HLCA.clinicalClassName) == null) { 
				StandardValidityReport report = new StandardValidityReport();
				report.add(true, "Context Ontology does not contain the Clinical class", HLCA.clinicalClassName); 
				return report;
			}
			if (ctxModel.getOntClass(HLCA.nutrClassName) == null) { 
				StandardValidityReport report = new StandardValidityReport();
				report.add(true, "Context Ontology does not contain the Nut class", HLCA.nutrClassName); 
				return report;
			}
		}
		return validity;
	}
}


<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/monitoring/MonitoringStrategy.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */
package org.uclab.mm.dcl.llm.monitoring;

import java.sql.Connection;
import java.sql.SQLException;
import org.uclab.mm.dcl.llm.objectmodel.FoodLog;

/**
 * This is an interface to define the strategy for the monitoring of the
 * activities which may be either physical or nutrition.
 *
 * @author Rizvi
 */
public interface MonitoringStrategy{

  /**
   * This method is used to monitor the different kinds of physical activities.
   *
   * @param dbConn
   * @param objMonitoringEvent
   */
  public void doMonitor(Connection dbConn, String objMonitoringEvent) throws SQLException;

  /**
   * This method is used to monitor the Food nutrition.
   *
   * @param objFoodLog
   */
  public void doMonitor(FoodLog objFoodLog);

}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/ContextOntologyManager/ContextQueryGenerator.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.ContextOntologyManager;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.sparql.core.Var;
import com.hp.hpl.jena.sparql.expr.E_GreaterThan;
import com.hp.hpl.jena.sparql.expr.E_GreaterThanOrEqual;
import com.hp.hpl.jena.sparql.expr.E_LessThan;
import com.hp.hpl.jena.sparql.expr.E_LessThanOrEqual;
import com.hp.hpl.jena.sparql.expr.E_NotEquals;
import com.hp.hpl.jena.sparql.expr.E_NotExists;
import com.hp.hpl.jena.sparql.expr.Expr;
import com.hp.hpl.jena.sparql.expr.ExprVar;
import com.hp.hpl.jena.sparql.expr.NodeValue;
import com.hp.hpl.jena.sparql.expr.aggregate.AggregatorFactory;
import com.hp.hpl.jena.sparql.expr.nodevalue.NodeValueDT;
import com.hp.hpl.jena.sparql.syntax.ElementFilter;
import com.hp.hpl.jena.sparql.syntax.ElementGroup;
import com.hp.hpl.jena.sparql.syntax.ElementTriplesBlock;
import com.hp.hpl.jena.sparql.syntax.ElementUnion;
import com.hp.hpl.jena.vocabulary.RDF.Nodes;

import mm.icl.hlc.OntologyTools.ContextOntology;
import mm.icl.hlc.OntologyTools.HLCA;
import mm.icl.hlc.OntologyTools.LowLevelContext;
import mm.icl.hlc.OntologyTools.NutritionContext;
import mm.icl.hlc.OntologyTools.PhysicalActivityContext;
import mm.icl.hlc.OntologyTools.ClinicalContext;
/**
 * Context Query Generator: Subcomponent of the Context Ontology Manager which
 * generates the SPARQL queries required by the Context Handler to find the
 * matching Context instances stored in the Context Ontology Storage.
 * 
 * @author <NAME> and <NAME>
 * @version 2.5
 * @since 2015-10-28
 */
public class ContextQueryGenerator {
	private static ContextQueryGenerator contextQueryGenerator = null;
	
	/**
	 * Method to generate a SPARQL query for the previous valid and unfinished
	 * High Level Context instance.
	 * 
	 * @param hlc
	 *            PhysicalActivity Context instance for which the previous context
	 *            should be matched.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return The SPARQL Query to retrieve the previous valid and unfinished
	 *         PhysicalActivity Context instance.
	 */
	public Query generateQueryForPreviousValidAndUnfinishedHlc(PhysicalActivityContext hlc, ContextOntology ont) {
		ElementUnion union = createTriplesUnionForHlcUserStartTime(
				hlc.getObjectPropertyValue(ont.getContextOfProp()), ont);
		ElementFilter filterNeg = createFilterNotExistsEndTimeInHlc(ont);
		ElementFilter filterLessThanOrEqual = createFilterStartTimeLessThanOrEqual(
				hlc.getDataPropertyValue(ont.getStartTimeProp()));
		return createHlcQuery(union, filterNeg, filterLessThanOrEqual);
	}
	/**
	 * Method to generate a SPARQL query for the previous valid and unfinished
	 * High Level Context instance.
	 * 
	 * @param hlc
	 *            Nutrition Context instance for which the previous context
	 *            should be matched.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return The SPARQL Query to retrieve the previous valid and unfinished
	 *         Nutrition Context instance.
	 */
	public  Query generateQueryForPreviousValidAndUnfinishedHlc(NutritionContext hlc, ContextOntology ont) {
		ElementUnion union = createTriplesUnionForNutHlcUserStartTime(
				hlc.getObjectPropertyValue(ont.getContextOfProp()), ont);
		ElementFilter filterNeg = createFilterNotExistsEndTimeInHlc(ont);
		ElementFilter filterLessThanOrEqual = createFilterStartTimeLessThanOrEqual(
				hlc.getDataPropertyValue(ont.getStartTimeProp()));
		return createHlcQuery(union, filterNeg, filterLessThanOrEqual);
	}
	/**
	 * Method to generate a SPARQL query for the previous valid and unfinished
	 * High Level Context instance.
	 * 
	 * @param hlc
	 *            ClincialContext instance for which the previous context
	 *            should be matched.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return The SPARQL Query to retrieve the previous valid and unfinished
	 *         Clincial Context instance.
	 */
	public Query generateQueryForPreviousValidAndUnfinishedHlc(ClinicalContext hlc, ContextOntology ont) {
		ElementUnion union = createTriplesUnionForCliHlcUserStartTime(
				hlc.getObjectPropertyValue(ont.getContextOfProp()), ont);
		ElementFilter filterNeg = createFilterNotExistsEndTimeInHlc(ont);
		ElementFilter filterLessThanOrEqual = createFilterStartTimeLessThanOrEqual(
				hlc.getDataPropertyValue(ont.getStartTimeProp()));
		return createHlcQuery(union, filterNeg, filterLessThanOrEqual);
	}

	/**
	 * Method to generate a SPARQL query for the previous valid and finished
	 * High Level Context instance.
	 * 
	 * @param hlc
	 *            PhysicalActivity Context instance for which the previous context
	 *            should be matched.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return The SPARQL Query to retrieve the previous valid and finished PhysicalActivity
	 *         Context instance.
	 */
	public  Query generateQueryForPreviousValidAndFinishedHlc(PhysicalActivityContext hlc, ContextOntology ont) {
		ElementUnion union = createTriplesUnionForHlcUserStartAndEndTime(
				hlc.getObjectPropertyValue(ont.getContextOfProp()), ont);
		Literal time = hlc.getDataPropertyValue(ont.getStartTimeProp());
		ElementFilter filterLessThanOrEqual = createFilterStartTimeLessThanOrEqual(time);
		ElementFilter filterGreaterThan = createFilterEndTimeGreaterThan(time);
		return createHlcQuery(union, filterLessThanOrEqual, filterGreaterThan);
	}	
	/**
	 * Method to generate a SPARQL query for the previous valid and finished
	 * High Level Context instance.
	 * 
	 * @param hlc
	 *            Nutrition Context instance for which the previous context
	 *            should be matched.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return The SPARQL Query to retrieve the previous valid and finished Nutrition
	 *          Context instance.
	 */
	public  Query generateQueryForPreviousValidAndFinishedHlc(NutritionContext hlc, ContextOntology ont) {
		ElementUnion union = createTriplesUnionForHlcUserStartAndEndTime(
				hlc.getObjectPropertyValue(ont.getContextOfProp()), ont);
		Literal time = hlc.getDataPropertyValue(ont.getStartTimeProp());
		ElementFilter filterLessThanOrEqual = createFilterStartTimeLessThanOrEqual(time);
		ElementFilter filterGreaterThan = createFilterEndTimeGreaterThan(time);
		return createHlcQuery(union, filterLessThanOrEqual, filterGreaterThan);
	}
	/**
	 * Method to generate a SPARQL query for the previous valid and finished
	 * High Level Context instance.
	 * 
	 * @param hlc
	 *            PhysicalActivity Context instance for which the previous context
	 *            should be matched.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return The SPARQL Query to retrieve the previous valid and finished PhysicalActivity
	 *         Context instance.
	 */
	public  Query generateQueryForPreviousValidAndFinishedHlc(ClinicalContext hlc, ContextOntology ont) {
		ElementUnion union = createTriplesUnionForHlcUserStartAndEndTime(
				hlc.getObjectPropertyValue(ont.getContextOfProp()), ont);
		Literal time = hlc.getDataPropertyValue(ont.getStartTimeProp());
		ElementFilter filterLessThanOrEqual = createFilterStartTimeLessThanOrEqual(time);
		ElementFilter filterGreaterThan = createFilterEndTimeGreaterThan(time);
		return createHlcQuery(union, filterLessThanOrEqual, filterGreaterThan);
	}
	/**
	 * Method to generate a SPARQL query for the start time of the next High
	 * Level Context instance.
	 * 
	 * @param hlc
	 *            PhysicalActivity Context instance for which the start time of the
	 *            next context should be matched.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return The SPARQL Query to retrieve the start time of the next PhysicalActivity
	 *          Context instance.
	 */
	public  Query generateQueryForStartTimeOfNextHlc(PhysicalActivityContext hlc, ContextOntology ont) {
		ElementUnion union= createTriplesUnionForHlcUserStartTime(hlc.getObjectPropertyValue(ont.getContextOfProp()), ont);  
		ElementFilter filterGreaterThan = createFilterStartTimeGreaterThan(
				hlc.getDataPropertyValue(ont.getStartTimeProp()));
		return createMinStartTimeQuery(union, filterGreaterThan);
	}
	/**
	 * Method to generate a SPARQL query for the start time of the next High
	 * Level Context instance.
	 * 
	 * @param hlc
	 *            Nutrition Context instance for which the start time of the
	 *            next context should be matched.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return The SPARQL Query to retrieve the start time of the next Nutrition
	 *         Context instance.
	 */
	public  Query generateQueryForStartTimeOfNextHlc(NutritionContext hlc, ContextOntology ont) {
		ElementUnion union= createTriplesUnionForHlcUserStartTime(hlc.getObjectPropertyValue(ont.getContextOfProp()), ont);  
		ElementFilter filterGreaterThan = createFilterStartTimeGreaterThan(
				hlc.getDataPropertyValue(ont.getStartTimeProp()));
		return createMinStartTimeQuery(union, filterGreaterThan);
	}
	/**
	 * Method to generate a SPARQL query for the start time of the next High
	 * Level Context instance.
	 * 
	 * @param hlc
	 *            PhysicalActivity Context instance for which the start time of the
	 *            next context should be matched.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return The SPARQL Query to retrieve the start time of the next PhysicalActivity
	 *          Context instance.
	 */
	public  Query generateQueryForStartTimeOfNextHlc(ClinicalContext hlc, ContextOntology ont) {
		ElementUnion union= createTriplesUnionForHlcUserStartTime(hlc.getObjectPropertyValue(ont.getContextOfProp()), ont);  
		ElementFilter filterGreaterThan = createFilterStartTimeGreaterThan(
				hlc.getDataPropertyValue(ont.getStartTimeProp()));
		return createMinStartTimeQuery(union, filterGreaterThan);
	}
	/**
	 * Method to generate a SPARQL query for the previous valid and unfinished
	 * Low Level Context instance.
	 * 
	 * @param llc
	 *            Low Level Context instance for which the previous context
	 *            should be matched.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return The SPARQL Query to retrieve the previous valid and unfinished
	 *         Low Level Context instance.
	 */
	public  Query generateQueryForPreviousValidAndUnfinishedLlc(LowLevelContext llc, ContextOntology ont) {
		ElementUnion union= createTriplesUnionForLlcCategoryUserStartTime (ont.getLlcTypeClass(llc.getLlcCategoryName()), 
																			llc.getObjectPropertyValue(ont.getContextOfProp()), 	ont); 
		ElementFilter filterNeg = createFilterNotExistsEndTimeInLlc(ont);
		ElementFilter filterLessThanOrEqual = createFilterStartTimeLessThanOrEqual(llc.getDataPropertyValue(ont.getStartTimeProp()));
		return createLlcQuery(union, filterNeg, filterLessThanOrEqual);
	}
	/**
	 * Method to generate a SPARQL query for the previous valid and unfinished
	 * Low Level Context instance.
	 * 
	 * @param category
	 *            OntClass representing the category, i.e., activity, emotion or
	 *            location, for which a previous Low Level Context instance
	 *            should be matched.
	 * @param user
	 *            Resource representing the instance of the user for which the
	 *            previous Low Level Context instance should be matched.
	 * @param time
	 *            xsd:dateTime typed Literal representing the time for which the
	 *            previous Low Level Context instance should be matched.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return The SPARQL Query to retrieve the previous valid and unfinished
	 *         Low Level Context instance.
	 */
	public  Query generateQueryForPreviousValidAndUnfinishedLlc(OntClass category, Resource user, Literal time,
			ContextOntology ont) {
		ElementUnion union = createTriplesUnionForLlcCategoryUserStartTime(category, user, ont);  
		ElementFilter filterNeg = createFilterNotExistsEndTimeInLlc(ont);
		ElementFilter filterLessThanOrEqual = createFilterStartTimeLessThanOrEqual(time);
		return createLlcQuery(union, filterNeg, filterLessThanOrEqual);
	}
	/**
	 * Method to generate a SPARQL query for the previous valid and finished Low
	 * Level Context instance.
	 * 
	 * @param llc
	 *            Low Level Context instance for which the previous context
	 *            should be matched.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return The SPARQL Query to retrieve the previous valid and finished High
	 *         Level Context instance.
	 */
	public  Query generateQueryForPreviousValidAndFinishedLlc(LowLevelContext llc, ContextOntology ont) {
		ElementUnion union = createTriplesUnionForLlcCategoryUserStartAndEndTime(  
				ont.getLlcTypeClass(llc.getLlcCategoryName()), llc.getObjectPropertyValue(ont.getContextOfProp()), ont);
		Literal time = llc.getDataPropertyValue(ont.getStartTimeProp());
		ElementFilter filterLessThanOrEqual = createFilterStartTimeLessThanOrEqual(time);
		ElementFilter filterGreaterThan = createFilterEndTimeGreaterThan(time);
		return createLlcQuery(union, filterLessThanOrEqual, filterGreaterThan);
	}
	/**
	 * Method to generate a SPARQL query for the previous valid and finished Low
	 * Level Context instance.
	 * 
	 * @param category
	 *            OntClass representing the category, i.e., activity, emotion or
	 *            location, for which a previous Low Level Context instance
	 *            should be matched.
	 * @param user
	 *            Resource representing the instance of the user for which the
	 *            previous Low Level Context instance should be matched.
	 * @param time
	 *            xsd:dateTime typed Literal representing the time for which the
	 *            previous Low Level Context instance should be matched.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return The SPARQL Query to retrieve the previous valid and finished High
	 *         Level Context instance.
	 */
	public  Query generateQueryForPreviousValidAndFinishedLlc(OntClass category, Resource user, Literal time,
			ContextOntology ont) {
		ElementUnion union = createTriplesUnionForLlcCategoryUserStartAndEndTime(category, user, ont);  
		ElementFilter filterLessThanOrEqual = createFilterStartTimeLessThanOrEqual(time);
		ElementFilter filterGreaterThan = createFilterEndTimeGreaterThan(time);
		return createLlcQuery(union, filterLessThanOrEqual, filterGreaterThan);
	}
	/**
	 * Method to generate a SPARQL query for the start time of the next Low
	 * Level Context instance.
	 * 
	 * @param llc
	 *            Low Level Context instance for which the start time of the
	 *            next context should be matched.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return The SPARQL Query to retrieve the start time of the next Low Level
	 *         Context instance.
	 */
	public  Query generateQueryForStartTimeOfNextLlc(LowLevelContext llc, ContextOntology ont) {
		ElementUnion union = createTriplesUnionForLlcCategoryUserStartTime(  
				ont.getLlcTypeClass(llc.getLlcCategoryName()), llc.getObjectPropertyValue(ont.getContextOfProp()), ont);
		ElementFilter filterGreaterThan = createFilterStartTimeGreaterThan(
				llc.getDataPropertyValue(ont.getStartTimeProp()));
		return createMinStartTimeQuery(union, filterGreaterThan);
	}
	/**
	 * Method to generate a SPARQL query for Low Level Context instances which
	 * have their start time within a time window.
	 * 
	 * @param windowStart
	 *            xsd:dateTime typed Literal representing the start time of the
	 *            window.
	 * @param windowEnd
	 *            xsd:dateTime typed Literal representing the end time of the
	 *            window.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return The SPARQL Query to retrieve the Low Level Context instances
	 *         which have their start time within a time window.
	 */
	public  Query generateQueryForLlcWithStartTimeInWindow(Literal windowStart, Literal windowEnd,
			ContextOntology ont) {
		
		ElementUnion union= createTriplesUnionForLlcStartTime(ont);
		ElementFilter filterGreaterThanOrEqual = createFilterStartTimeGreaterThanOrEqual(windowStart);
		ElementFilter filterLessThan = createFilterStartTimeLessThan(windowEnd);
		Query q = createLlcQuery(union, filterGreaterThanOrEqual, filterLessThan);
		q.addOrderBy(new ExprVar(HLCA.startTimeSparqlVar), Query.ORDER_ASCENDING);
		return q;
	}
	/**
	 * Method to generate a SPARQL query for the Low Level Context instances
	 * which have their end time within a time window and which do not have a
	 * contiguous Low Level Context instance.
	 * 
	 * @param windowStart
	 *            xsd:dateTime typed Literal representing the start time of the
	 *            window.
	 * @param windowEnd
	 *            xsd:dateTime typed Literal representing the end time of the
	 *            window.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return The SPARQL Query to retrieve the Low Level Context instances
	 *         which have their end time within a time window and which do not
	 *         have a contiguous Low Level Context instance.
	 */
	public  Query generateQueryForLlcWithEndTimeInWindowAndNoContiguousLlc(Literal windowStart, Literal windowEnd, ContextOntology ont) {  
		ElementUnion union = createTriplesUnionForLlcUserAndEndTimeVar(ont);
		ElementFilter filterGreaterThanOrEqual = createFilterEndTimeGreaterThanOrEqual(windowStart);
		ElementFilter filterLessThan = createFilterEndTimeLessThan(windowEnd);
		ElementFilter filterNoAdj = createFilterNotExistsAdjacentLlc(ont);
		Query q = createLlcQuery(union, filterGreaterThanOrEqual, filterLessThan, filterNoAdj);
		q.addOrderBy(new ExprVar(HLCA.endTimeSparqlVar), Query.ORDER_ASCENDING);
		return q;
	}
	/**
	 * Method to generate a SPARQL query for unfinished Low Level Context
	 * instances which are concurrent at the start time of a Low Level Context
	 * instance.
	 * 
	 * @param llc
	 *            Low Level Context instance for which concurrent context
	 *            instances should be matched.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return The SPARQL Query to retrieve unfinished Low Level Context
	 *         instances which are concurrent at the start time of a Low Level
	 *         Context instance.
	 */
	public  Query generateQueryForConcurrentAtStartTimeUnfinishedLlc(LowLevelContext llc, ContextOntology ont) {
		ElementUnion union = createTriplesUnionForLlcUserStartTime(       
				llc.getObjectPropertyValue(ont.getContextOfProp()), ont);
		ElementFilter filterNeg = createFilterNotExistsEndTimeInLlc(ont);
		ElementFilter filterLessThanOrEqual = createFilterStartTimeLessThanOrEqual(
				llc.getDataPropertyValue(ont.getStartTimeProp()));
		ElementFilter filterNotEquals = createFilterLlcNotEquals(llc.getCtxIndiv());
		ElementFilter filterNotEqualsCategory = createFilterLlcCategoryNotEquals(
				ont.getLlcCategoryClass(llc.getLlcCategoryName()));
		return createLlcQuery(union, filterNeg, filterLessThanOrEqual, filterNotEquals, filterNotEqualsCategory);
	}
	/**
	 * Method to generate a SPARQL query for finished Low Level Context
	 * instances which are concurrent at the start time of a Low Level Context
	 * instance.
	 * 
	 * @param llc
	 *            Low Level Context instance for which concurrent context
	 *            instances should be matched.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return The SPARQL Query to retrieve finished Low Level Context instances
	 *         which are concurrent at the start time of a Low Level Context
	 *         instance.
	 */
	public  Query generateQueryForConcurrentAtStartTimeFinishedLlc(LowLevelContext llc, ContextOntology ont) {
		ElementUnion union = createTriplesUnionForLlcUserStartAndEndTime(        
				llc.getObjectPropertyValue(ont.getContextOfProp()), ont);
		Literal time = llc.getDataPropertyValue(ont.getStartTimeProp());
		ElementFilter filterLessThanOrEqual = createFilterStartTimeLessThanOrEqual(time);
		ElementFilter filterGreaterThan = createFilterEndTimeGreaterThan(time);
		ElementFilter filterNotEquals = createFilterLlcNotEquals(llc.getCtxIndiv());
		ElementFilter filterNotEqualsCategory = createFilterLlcCategoryNotEquals(
				ont.getLlcCategoryClass(llc.getLlcCategoryName()));
		return createLlcQuery(union, filterLessThanOrEqual, filterGreaterThan, filterNotEquals,	filterNotEqualsCategory);
	}
	/**
	 * Method to generate a SPARQL query for unfinished Low Level Context
	 * instances which are concurrent at the end time of a Low Level Context
	 * instance.
	 * 
	 * @param llc
	 *            Low Level Context instance for which concurrent context
	 *            instances should be matched.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return The SPARQL Query to retrieve unfinished Low Level Context
	 *         instances which are concurrent at the end time of a Low Level
	 *         Context instance.
	 */
	public  Query generateQueryForConcurrentAtEndTimeUnfinishedLlc(LowLevelContext llc, ContextOntology ont) {
		ElementUnion union = createTriplesUnionForLlcUserStartTime(
				llc.getObjectPropertyValue(ont.getContextOfProp()), ont);
		ElementFilter filterNeg = createFilterNotExistsEndTimeInLlc(ont);
		ElementFilter filterLessThanOrEqual = createFilterStartTimeLessThanOrEqual(
				llc.getDataPropertyValue(ont.getEndTimeProp()));
		ElementFilter filterNotEqualsCategory = createFilterLlcCategoryNotEquals(
				ont.getLlcCategoryClass(llc.getLlcCategoryName()));
		return createLlcQuery(union, filterNeg, filterLessThanOrEqual, filterNotEqualsCategory);
	}
	/**
	 * Method to generate a SPARQL query for finished Low Level Context
	 * instances which are concurrent at the end time of a Low Level Context
	 * instance.
	 * 
	 * @param llc
	 *            Low Level Context instance for which concurrent context
	 *            instances should be matched.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return The SPARQL Query to retrieve finished Low Level Context instances
	 *         which are concurrent at the end time of a Low Level Context
	 *         instance.
	 */
	public  Query generateQueryForConcurrentAtEndTimeFinishedLlc(LowLevelContext llc, ContextOntology ont) {
		ElementUnion union = createTriplesUnionForLlcUserStartAndEndTime(
				llc.getObjectPropertyValue(ont.getContextOfProp()), ont);
		Literal time = llc.getDataPropertyValue(ont.getEndTimeProp());
		ElementFilter filterLessThanOrEqual = createFilterStartTimeLessThanOrEqual(time);
		ElementFilter filterGreaterThan = createFilterEndTimeGreaterThan(time);
		ElementFilter filterNotEqualsCategory = createFilterLlcCategoryNotEquals(
				ont.getLlcCategoryClass(llc.getLlcCategoryName()));
		return createLlcQuery(union, filterLessThanOrEqual, filterGreaterThan, filterNotEqualsCategory);
	}
	/**
	 * Method to create a block of triples which include the High Level Context,
	 * the user and the start time.
	 * 
	 * @param user
	 *            Resource representing the instance of the user for which the
	 *            triple should be created.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return Triples block for the High Level Context, the user and the start
	 *         time.
	 */
		private  ElementUnion createTriplesUnionForHlcUserStartTime(Resource user, ContextOntology ont) { //Asif
		Triple pattern1 = Triple.create(Var.alloc(HLCA.hlcSparqlVar), Nodes.type, ont.getHlcClass().asNode());
		Triple pattern2 = Triple.create(Var.alloc(HLCA.hlcSparqlVar), ont.getContextOfProp().asNode(), user.asNode());
		Triple pattern3 = Triple.create(Var.alloc(HLCA.hlcSparqlVar), ont.getStartTimeProp().asNode(),
				Var.alloc(HLCA.startTimeSparqlVar));
		ElementTriplesBlock blocka = new ElementTriplesBlock();
		ElementUnion union= new ElementUnion();
		blocka.addTriple(pattern1);
		blocka.addTriple(pattern2);
		blocka.addTriple(pattern3);
		union.addElement(blocka);
		return union;
	}
		/**
		 * Method to create a block of triples which include the High Level Context,
		 * the user and the start time.
		 * 
		 * @param user
		 *            Resource representing the instance of the user for which the
		 *            triple should be created.
		 * @param ont
		 *            Context Ontology which represents the Mining Minds Context
		 *            Model.
		 * @return Triples block for the High Level Context, the user and the start
		 *         time.
		 */
			private  ElementUnion createTriplesUnionForNutHlcUserStartTime(Resource user, ContextOntology ont) { 
			Triple pattern4 = Triple.create(Var.alloc(HLCA.hlcSparqlVar), Nodes.type, ont.getNutHlcClass().asNode());  
			Triple pattern5 = Triple.create(Var.alloc(HLCA.hlcSparqlVar), ont.getContextOfProp().asNode(), user.asNode());
			Triple pattern6 = Triple.create(Var.alloc(HLCA.hlcSparqlVar), ont.getStartTimeProp().asNode(),
					Var.alloc(HLCA.startTimeSparqlVar));
			ElementTriplesBlock blockb = new ElementTriplesBlock();
			ElementUnion union= new ElementUnion();
			blockb.addTriple(pattern4);
			blockb.addTriple(pattern5);
			blockb.addTriple(pattern6);
			union.addElement(blockb);
			return union;
		}
			/**
			 * Method to create a block of triples which include the High Level Context,
			 * the user and the start time.
			 * 
			 * @param user
			 *            Resource representing the instance of the user for which the
			 *            triple should be created.
			 * @param ont
			 *            Context Ontology which represents the Mining Minds Context
			 *            Model.
			 * @return Triples block for the High Level Context, the user and the start
			 *         time.
			 */
			private  ElementUnion createTriplesUnionForCliHlcUserStartTime(Resource user, ContextOntology ont) { //Asif
			Triple pattern1 = Triple.create(Var.alloc(HLCA.hlcSparqlVar), Nodes.type, ont.getClinicalHlcClass().asNode());
			Triple pattern2 = Triple.create(Var.alloc(HLCA.hlcSparqlVar), ont.getContextOfProp().asNode(), user.asNode());
			Triple pattern3 = Triple.create(Var.alloc(HLCA.hlcSparqlVar), ont.getStartTimeProp().asNode(),
					Var.alloc(HLCA.startTimeSparqlVar));
			ElementTriplesBlock blocka = new ElementTriplesBlock();
			ElementUnion union= new ElementUnion();
			blocka.addTriple(pattern1);
			blocka.addTriple(pattern2);
			blocka.addTriple(pattern3);
			union.addElement(blocka);
			return union;
			}
	/**
	 * Method to create a block of triples which include the High Level Context,
	 * the user, the start time and the end time.
	 * 
	 * @param user
	 *            Resource representing the instance of the user for which the
	 *            triple should be created.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return Triples block for the High Level Context, the user, the start
	 *         time and the end time.
	 */
		private  ElementUnion createTriplesUnionForHlcUserStartAndEndTime(Resource user, ContextOntology ont) { 
		ElementUnion union = createTriplesUnionForHlcUserStartTime(user, ont);
		Triple pattern1 = Triple.create(Var.alloc(HLCA.hlcSparqlVar), ont.getEndTimeProp().asNode(),Var.alloc(HLCA.endTimeSparqlVar));
		ElementTriplesBlock blocka = new ElementTriplesBlock();
		blocka.addTriple(pattern1);
		union.addElement(blocka);
		return union;
	}
	/**
	 * Method to create a block of triples which include the Low Level Context,
	 * the category, the user and the start time.
	 * 
	 * @param category
	 *            OntClass representing the category of the Low Level Context,
	 *            i.e., activity, emotion, food or location, for which the the triple
	 *            should be created.
	 * @param user
	 *            Resource representing the instance of the user for which the
	 *            triple should be created.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return Triples block for the Low Level Context, the category, the user
	 *         and the start time.
	 */
	private  ElementUnion createTriplesUnionForLlcCategoryUserStartTime(OntClass category, Resource user,   
			ContextOntology ont) {
		OntClass SuperClassCategory  = ont.getLlcSuperClassCategory(category);		
				ElementTriplesBlock blocka = new ElementTriplesBlock();
				ElementTriplesBlock blockb = new ElementTriplesBlock();
				Triple pattern1=null;
				Triple pattern2=null;
				Triple pattern3=null;
				Triple pattern4=null;
				Triple pattern5=null;
				Triple pattern6=null;
				Triple pattern7=null;
				Triple pattern8=null;
				Triple pattern9=null;
				ElementUnion union = new ElementUnion();
				if (SuperClassCategory.getLocalName().equals("Food") )
				{
				pattern1 = Triple.create(Var.alloc(HLCA.llcSparqlVar), Nodes.type, Var.alloc(HLCA.llcTypeSparqlVar));
				pattern2 = Triple.create(Var.alloc(HLCA.llcTypeSparqlVar),com.hp.hpl.jena.vocabulary.RDFS.Nodes.subClassOf, SuperClassCategory.asNode());  
				pattern3 = Triple.create(Var.alloc(HLCA.llcSparqlVar), ont.getContextOfProp().asNode(), user.asNode());
				pattern4 = Triple.create(Var.alloc(HLCA.llcSparqlVar), ont.getStartTimeProp().asNode(),Var.alloc(HLCA.startTimeSparqlVar));
				pattern5 = Triple.create(Var.alloc(HLCA.llcSparqlVar), Nodes.type, Var.alloc(HLCA.llcTypeSparqlVar));
				pattern6 = Triple.create(Var.alloc(HLCA.llcTypeSparqlVar),com.hp.hpl.jena.vocabulary.RDFS.Nodes.subClassOf, Var.alloc(HLCA.llcType1SparqlVar));
				pattern7 = Triple.create(Var.alloc(HLCA.llcType1SparqlVar),com.hp.hpl.jena.vocabulary.RDFS.Nodes.subClassOf, SuperClassCategory.asNode()); 
				pattern8 = Triple.create(Var.alloc(HLCA.llcSparqlVar), ont.getContextOfProp().asNode(), user.asNode());
				pattern9 = Triple.create(Var.alloc(HLCA.llcSparqlVar), ont.getStartTimeProp().asNode(),Var.alloc(HLCA.startTimeSparqlVar));
				}
				else {
				pattern1 = Triple.create(Var.alloc(HLCA.llcSparqlVar), Nodes.type, Var.alloc(HLCA.llcTypeSparqlVar));
				pattern2 = Triple.create(Var.alloc(HLCA.llcTypeSparqlVar),com.hp.hpl.jena.vocabulary.RDFS.Nodes.subClassOf, category.asNode());   
				pattern3 = Triple.create(Var.alloc(HLCA.llcSparqlVar), ont.getContextOfProp().asNode(), user.asNode());
				pattern4 = Triple.create(Var.alloc(HLCA.llcSparqlVar), ont.getStartTimeProp().asNode(),Var.alloc(HLCA.startTimeSparqlVar));
				pattern5 = Triple.create(Var.alloc(HLCA.llcSparqlVar), Nodes.type, Var.alloc(HLCA.llcTypeSparqlVar));
				pattern6 = Triple.create(Var.alloc(HLCA.llcTypeSparqlVar),com.hp.hpl.jena.vocabulary.RDFS.Nodes.subClassOf, Var.alloc(HLCA.llcType1SparqlVar));
				pattern7 = Triple.create(Var.alloc(HLCA.llcType1SparqlVar),com.hp.hpl.jena.vocabulary.RDFS.Nodes.subClassOf, category.asNode()); 
				pattern8 = Triple.create(Var.alloc(HLCA.llcSparqlVar), ont.getContextOfProp().asNode(), user.asNode());
				pattern9 = Triple.create(Var.alloc(HLCA.llcSparqlVar), ont.getStartTimeProp().asNode(),Var.alloc(HLCA.startTimeSparqlVar));
				}
		blocka.addTriple(pattern1);
		blocka.addTriple(pattern2);
		blocka.addTriple(pattern3);
		blocka.addTriple(pattern4);
		blockb.addTriple(pattern5);
		blockb.addTriple(pattern6);
		blockb.addTriple(pattern7);
		blockb.addTriple(pattern8);
		blockb.addTriple(pattern9);
		union.addElement(blocka);
		union.addElement(blockb);
		return union;
	}
	/**
	 * Method to create a block of triples which include the Low Level Context,
	 * the category, the user, the start time and the end time.
	 * 
	 * @param category
	 *            OntClass representing the category of the Low Level Context,
	 *            i.e., activity, emotion, food or location, for which the the triple
	 *            should be created.
	 * @param user
	 *            Resource representing the instance of the user for which the
	 *            triple should be created.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return Triples block for the Low Level Context, the category, the user,
	 *         the start time and the end time.
	 */
	private  ElementUnion createTriplesUnionForLlcCategoryUserStartAndEndTime(OntClass category, 
			Resource user, ContextOntology ont) {
		ElementUnion union = createTriplesUnionForLlcCategoryUserStartTime(category, user, ont);  
		Triple patterna = Triple.create(Var.alloc(HLCA.llcSparqlVar), ont.getEndTimeProp().asNode(), Var.alloc(HLCA.endTimeSparqlVar));
		ElementTriplesBlock blocka = new ElementTriplesBlock();
		blocka.addTriple(patterna);
		union.addElement(blocka);
		return union;
	}
	/**
	 * Method to create a block of triples which include the Low Level Context
	 * and the start time.
	 * 
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return Triples block for the Low Level Context and the start time.
	 */
	private  ElementUnion createTriplesUnionForLlcStartTime(ContextOntology ont) {  
		Triple pattern1 = Triple.create(Var.alloc(HLCA.llcSparqlVar),         Nodes.type,                                       Var.alloc(HLCA.llcTypeSparqlVar));
		Triple pattern2 = Triple.create(Var.alloc(HLCA.llcTypeSparqlVar),    com.hp.hpl.jena.vocabulary.RDFS.Nodes.subClassOf, Var.alloc(HLCA.llcCategorySparqlVar));
		Triple pattern3 = Triple.create(Var.alloc(HLCA.llcCategorySparqlVar), com.hp.hpl.jena.vocabulary.RDFS.Nodes.subClassOf, ont.getLlcClass().asNode());
		Triple pattern4 = Triple.create(Var.alloc(HLCA.llcSparqlVar),         ont.getStartTimeProp().asNode(),                  Var.alloc(HLCA.startTimeSparqlVar));
		Triple pattern5 = Triple.create(Var.alloc(HLCA.llcSparqlVar),         Nodes.type,                                       Var.alloc(HLCA.llcTypeSparqlVar));
		Triple pattern6 = Triple.create(Var.alloc(HLCA.llcTypeSparqlVar),     com.hp.hpl.jena.vocabulary.RDFS.Nodes.subClassOf, Var.alloc(HLCA.llcType1SparqlVar));
		Triple pattern7 = Triple.create(Var.alloc(HLCA.llcType1SparqlVar),    com.hp.hpl.jena.vocabulary.RDFS.Nodes.subClassOf, Var.alloc(HLCA.llcCategorySparqlVar));
		Triple pattern8 = Triple.create(Var.alloc(HLCA.llcCategorySparqlVar), com.hp.hpl.jena.vocabulary.RDFS.Nodes.subClassOf, ont.getLlcClass().asNode());
		Triple pattern9 = Triple.create(Var.alloc(HLCA.llcSparqlVar),         ont.getStartTimeProp().asNode(),                  Var.alloc(HLCA.startTimeSparqlVar));
		ElementTriplesBlock blocka = new ElementTriplesBlock();
		ElementTriplesBlock blockb = new ElementTriplesBlock();
		ElementUnion union = new ElementUnion();
		blocka.addTriple(pattern1);
		blocka.addTriple(pattern2);
		blocka.addTriple(pattern3);
		blocka.addTriple(pattern4);
		blockb.addTriple(pattern5);
		blockb.addTriple(pattern6);
		blockb.addTriple(pattern7);
		blockb.addTriple(pattern8);
		blockb.addTriple(pattern9);
		union.addElement(blocka);
		union.addElement(blockb);
	return union;
	}
	/**
	 * Method to create a block of triples which include the Low Level Context,
	 * the start time and the end time.
	 * 
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return Triples block for the Low Level Context, the start time and the
	 *         end time.
	 */
	private  ElementUnion createTriplesUnionForLlcStartAndEndTime(ContextOntology ont) {
		ElementUnion union = createTriplesUnionForLlcStartTime(ont);
		Triple pattern1 = Triple.create(Var.alloc(HLCA.llcSparqlVar), ont.getEndTimeProp().asNode(),	Var.alloc(HLCA.endTimeSparqlVar));
		ElementTriplesBlock blocka = new ElementTriplesBlock();
		blocka.addTriple(pattern1);
		union.addElement(blocka);
		return union;
	}
	/**
	 * Method to create a block of triples which include the Low Level Context,
	 * the user and the start time.
	 * 
	 * @param user
	 *            Resource representing the instance of the user for which the
	 *            triple should be created.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return Triples block for the Low Level Context, the user and the start
	 *         time.
	 */
	private  ElementUnion createTriplesUnionForLlcUserStartTime(Resource user, ContextOntology ont) {  
		ElementUnion union = createTriplesUnionForLlcStartTime(ont);
		Triple pattern1 = Triple.create(Var.alloc(HLCA.llcSparqlVar), ont.getContextOfProp().asNode(), user.asNode());
		ElementTriplesBlock blocka = new ElementTriplesBlock();
		blocka.addTriple(pattern1);
		union.addElement(blocka);
		return union ;
	}
	/**
	 * Method to create a block of triples which include the Low Level Context,
	 * the user, the start time and the end time.
	 * 
	 * @param user
	 *            Resource representing the instance of the user for which the
	 *            triple should be created.
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return Triples block for the Low Level Context, the user, the start time
	 *         and the end time.
	 */
	private  ElementUnion createTriplesUnionForLlcUserStartAndEndTime(Resource user, ContextOntology ont) { 
		ElementUnion union = createTriplesUnionForLlcStartAndEndTime(ont);  
		Triple pattern1 = Triple.create(Var.alloc(HLCA.llcSparqlVar), ont.getContextOfProp().asNode(), user.asNode());
		ElementTriplesBlock blocka = new ElementTriplesBlock();
		blocka.addTriple(pattern1);
		union.addElement(blocka);
		return union;
	}
	/**
	 * Method to create a block of triples which include the Low Level Context,
	 * and the user and the end time as variables.
	 * 
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return Triples block for the Low Level Context, and the user and the end
	 *         time as variables.
	 */
	private  ElementUnion createTriplesUnionForLlcUserAndEndTimeVar(ContextOntology ont) {  
		Triple pattern1 = Triple.create(Var.alloc(HLCA.llcSparqlVar), Nodes.type, Var.alloc(HLCA.llcTypeSparqlVar));
		Triple pattern2 = Triple.create(Var.alloc(HLCA.llcTypeSparqlVar), com.hp.hpl.jena.vocabulary.RDFS.Nodes.subClassOf, Var.alloc(HLCA.llcCategorySparqlVar));
		Triple pattern3 = Triple.create(Var.alloc(HLCA.llcCategorySparqlVar),	com.hp.hpl.jena.vocabulary.RDFS.Nodes.subClassOf, ont.getLlcClass().asNode());
		Triple pattern4 = Triple.create(Var.alloc(HLCA.llcSparqlVar), ont.getContextOfProp().asNode(),				Var.alloc(HLCA.userSparqlVar));
		Triple pattern5 = Triple.create(Var.alloc(HLCA.llcSparqlVar), ont.getEndTimeProp().asNode(),				Var.alloc(HLCA.endTimeSparqlVar));
		Triple pattern6 = Triple.create(Var.alloc(HLCA.llcSparqlVar), Nodes.type, Var.alloc(HLCA.llcTypeSparqlVar));
		Triple pattern7 = Triple.create(Var.alloc(HLCA.llcTypeSparqlVar), com.hp.hpl.jena.vocabulary.RDFS.Nodes.subClassOf, Var.alloc(HLCA.llcType1SparqlVar));
		Triple pattern8 = Triple.create(Var.alloc(HLCA.llcType1SparqlVar), com.hp.hpl.jena.vocabulary.RDFS.Nodes.subClassOf, Var.alloc(HLCA.llcCategorySparqlVar));
		Triple pattern9 = Triple.create(Var.alloc(HLCA.llcCategorySparqlVar),	com.hp.hpl.jena.vocabulary.RDFS.Nodes.subClassOf, ont.getLlcClass().asNode());
		Triple pattern10 = Triple.create(Var.alloc(HLCA.llcSparqlVar), ont.getContextOfProp().asNode(),				Var.alloc(HLCA.userSparqlVar));
		Triple pattern11 = Triple.create(Var.alloc(HLCA.llcSparqlVar), ont.getEndTimeProp().asNode(),				Var.alloc(HLCA.endTimeSparqlVar));
		ElementTriplesBlock blocka = new ElementTriplesBlock();
		ElementTriplesBlock blockb = new ElementTriplesBlock();
		ElementUnion union = new ElementUnion();
		blocka.addTriple(pattern1);
		blocka.addTriple(pattern2);
		blocka.addTriple(pattern3);
		blocka.addTriple(pattern4);
		blocka.addTriple(pattern5);
		blockb.addTriple(pattern6);
		blockb.addTriple(pattern7);
		blockb.addTriple(pattern8);
		blockb.addTriple(pattern9);
		blockb.addTriple(pattern10);
		blockb.addTriple(pattern11);
		union.addElement(blocka);
		union.addElement(blockb);
	return union;
	}
	/**
	 * Method to create a filter for start time less than a value.
	 * 
	 * @param xsd:dateTime
	 *            typed Literal representing the time.
	 * @return Filter for start time less than the value of time.
	 */
	private  ElementFilter createFilterStartTimeLessThan(Literal time) {
		Expr exprLessThan = new E_LessThan(new ExprVar(HLCA.startTimeSparqlVar),
				new NodeValueDT(time.getValue().toString(), time.asNode()));
		return new ElementFilter(exprLessThan);
	}
	/**
	 * Method to create a filter for start time less than or equal to a value.
	 * 
	 * @param xsd:dateTime
	 *            typed Literal representing the time.
	 * @return Filter for start time less than or equal to the value of time.
	 */
	private  ElementFilter createFilterStartTimeLessThanOrEqual(Literal time) {
		Expr exprLessThanOrEqual = new E_LessThanOrEqual(new ExprVar(HLCA.startTimeSparqlVar),
				new NodeValueDT(time.getValue().toString(), time.asNode()));
		return new ElementFilter(exprLessThanOrEqual);
	}
	/**
	 * Method to create a filter for start time greater than a value.
	 * 
	 * @param xsd:dateTime
	 *            typed Literal representing the time.
	 * @return Filter for start time greater than the value of time.
	 */
	private  ElementFilter createFilterStartTimeGreaterThan(Literal time) {
		Expr exprGreaterThan = new E_GreaterThan(new ExprVar(HLCA.startTimeSparqlVar),
				new NodeValueDT(time.getValue().toString(), time.asNode()));
		return new ElementFilter(exprGreaterThan);
	}
	/**
	 * Method to create a filter for start time greater than or equal to a
	 * value.
	 * 
	 * @param xsd:dateTime
	 *            typed Literal representing the time.
	 * @return Filter for start time greater than or equal to the value of time.
	 */
	private  ElementFilter createFilterStartTimeGreaterThanOrEqual(Literal time) {
		Expr exprGreaterThanOrEqual = new E_GreaterThanOrEqual(new ExprVar(HLCA.startTimeSparqlVar),
				new NodeValueDT(time.getValue().toString(), time.asNode()));
		return new ElementFilter(exprGreaterThanOrEqual);
	}
	/**
	 * Method to create a filter for end time less than a value.
	 * 
	 * @param xsd:dateTime
	 *            typed Literal representing the time.
	 * @return Filter for end time less than the value of time.
	 */
	private  ElementFilter createFilterEndTimeLessThan(Literal time) {
		Expr exprLessThan = new E_LessThan(new ExprVar(HLCA.endTimeSparqlVar),
				new NodeValueDT(time.getValue().toString(), time.asNode()));
		return new ElementFilter(exprLessThan);
	}
	/**
	 * Method to create a filter for end time greater than a value.
	 * 
	 * @param xsd:dateTime
	 *            typed Literal representing the time.
	 * @return Filter for end time greater than the value of time.
	 */
	private  ElementFilter createFilterEndTimeGreaterThan(Literal time) {
		Expr exprGreaterThan = new E_GreaterThan(new ExprVar(HLCA.endTimeSparqlVar),
				new NodeValueDT(time.getValue().toString(), time.asNode()));
		return new ElementFilter(exprGreaterThan);
	}
	/**
	 * Method to create a filter for end time greater than or equal to a value.
	 * 
	 * @param xsd:dateTime
	 *            typed Literal representing the time.
	 * @return Filter for end time greater than or equal to the value of time.
	 */
	private  ElementFilter createFilterEndTimeGreaterThanOrEqual(Literal time) {
		Expr exprGreaterThanOrEqual = new E_GreaterThanOrEqual(new ExprVar(HLCA.endTimeSparqlVar),
				new NodeValueDT(time.getValue().toString(), time.asNode()));
		return new ElementFilter(exprGreaterThanOrEqual);
	}
	/**
	 * Method to create a filter for "not exists" end time in High Level
	 * Context.
	 * 
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return Filter for "not exists" end time in High Level Context.
	 */
	private  ElementFilter createFilterNotExistsEndTimeInHlc(ContextOntology ont) {
		Triple pattern = Triple.create(Var.alloc(HLCA.hlcSparqlVar), ont.getEndTimeProp().asNode(),
				Var.alloc(HLCA.endTimeSparqlVar));
		ElementTriplesBlock negation = new ElementTriplesBlock();
		negation.addTriple(pattern);
		Expr exprNeg = new E_NotExists(negation);
		return new ElementFilter(exprNeg);
	}
	/**
	 * Method to create a filter for "not exists" end time in Low Level Context.
	 * 
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return Filter for "not exists" end time in Low Level Context.
	 */
	private  ElementFilter createFilterNotExistsEndTimeInLlc(ContextOntology ont) {
		Triple pattern = Triple.create(Var.alloc(HLCA.llcSparqlVar), ont.getEndTimeProp().asNode(),
				Var.alloc(HLCA.endTimeSparqlVar));
		ElementTriplesBlock negation = new ElementTriplesBlock();
		negation.addTriple(pattern);
		Expr exprNeg = new E_NotExists(negation);
		return new ElementFilter(exprNeg);
	}
	/**
	 * Method to create a filter for "not exists" end adjacent posterior Low
	 * Level Context.
	 * 
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 * @return Filter for "not exists" end adjacent posterior Low Level Context.
	 */
	private  ElementFilter createFilterNotExistsAdjacentLlc(ContextOntology ont) {
		String adj = "Adjacent";
		Triple pattern1 = Triple.create(Var.alloc(HLCA.llcSparqlVar + adj), Nodes.type, Var.alloc(HLCA.llcTypeSparqlVar + adj));
		Triple pattern2 = Triple.create(Var.alloc(HLCA.llcTypeSparqlVar + adj), com.hp.hpl.jena.vocabulary.RDFS.Nodes.subClassOf, Var.alloc(HLCA.llcCategorySparqlVar));
		Triple pattern3 = Triple.create(Var.alloc(HLCA.llcSparqlVar + adj), ont.getContextOfProp().asNode(), Var.alloc(HLCA.userSparqlVar));
		Triple pattern4 = Triple.create(Var.alloc(HLCA.llcSparqlVar + adj), ont.getStartTimeProp().asNode(), Var.alloc(HLCA.endTimeSparqlVar));
		Triple pattern5 = Triple.create(Var.alloc(HLCA.llcSparqlVar + adj), Nodes.type, Var.alloc(HLCA.llcTypeSparqlVar + adj));
		Triple pattern6 = Triple.create(Var.alloc(HLCA.llcTypeSparqlVar + adj), com.hp.hpl.jena.vocabulary.RDFS.Nodes.subClassOf, Var.alloc(HLCA.llcType1SparqlVar + adj));
		Triple pattern7 = Triple.create(Var.alloc(HLCA.llcType1SparqlVar + adj), com.hp.hpl.jena.vocabulary.RDFS.Nodes.subClassOf, Var.alloc(HLCA.llcCategorySparqlVar));
		Triple pattern8 = Triple.create(Var.alloc(HLCA.llcSparqlVar + adj), ont.getContextOfProp().asNode(), Var.alloc(HLCA.userSparqlVar));
		Triple pattern9 = Triple.create(Var.alloc(HLCA.llcSparqlVar + adj), ont.getStartTimeProp().asNode(), Var.alloc(HLCA.endTimeSparqlVar));
		ElementTriplesBlock negationa = new ElementTriplesBlock();
		ElementTriplesBlock negationb = new ElementTriplesBlock();
		negationa.addTriple(pattern1);
		negationa.addTriple(pattern2);
		negationa.addTriple(pattern3);
		negationa.addTriple(pattern4);
		negationb.addTriple(pattern5);
		negationb.addTriple(pattern6);
		negationb.addTriple(pattern7);
		negationb.addTriple(pattern8);
		negationb.addTriple(pattern9);
		ElementUnion union = new ElementUnion();
		union.addElement(negationa);
		union.addElement(negationb);
		Expr exprNotEquals = new E_NotEquals(new ExprVar(HLCA.llcSparqlVar), new ExprVar(HLCA.llcSparqlVar + adj));
		ElementFilter notEqual = new ElementFilter(exprNotEquals);
		ElementGroup body = new ElementGroup();
		body.addElement(union);
		body.addElement(notEqual);
		Expr exprNeg = new E_NotExists(body);
		return new ElementFilter(exprNeg);
	}
	/**
	 * Method to create a filter for "not equals" to a given Low Level Context.
	 * 
	 * @param llc
	 *            Low Level Context for which the matching one has to be not
	 *            equal.
	 * @return Filter for "not equals" to llc.
	 */
	private  ElementFilter createFilterLlcNotEquals(Individual llc) {
		Expr exprNotEquals = new E_NotEquals(new ExprVar(HLCA.llcSparqlVar), NodeValue.makeNode(llc.asNode()));
		return new ElementFilter(exprNotEquals);
	}
	/**
	 * Method to create a filter for "not equals" to a Low Level Context
	 * category, e.g. Activity, Emotion or Location.
	 * 
	 * @param llcCategory
	 *            OntClass representing the category of Low Level Context in the
	 *            Context Ontolog, which does not have to match.
	 * @return Filter for "not equals" to the llcCategory.
	 */
	private  ElementFilter createFilterLlcCategoryNotEquals(OntClass llcCategory) {
		Expr exprNotEquals = new E_NotEquals(new ExprVar(HLCA.llcCategorySparqlVar),
				NodeValue.makeNode(llcCategory.asNode()));
		return new ElementFilter(exprNotEquals);
	}
	/**
	 * Method to create a select SPARQL query for High Level Context.
	 * 
	 * @param block
	 *            Triples block to be part of the SPARQL query.
	 * @param filter1
	 *            Filter to be part of the SPARQL query.
	 * @param filter2
	 *            Triples block to be part of the SPARQL query.
	 * @return A select SPARQL query for High Level Context which is composed of
	 *         the block, filter1 and filter2.
	 */
	private  Query createHlcQuery(ElementUnion union, ElementFilter filter1, ElementFilter filter2) {  
		ElementGroup body = new ElementGroup();
		body.addElement(union);
		body.addElement(filter1);
		body.addElement(filter2);
		Query q = QueryFactory.make();
		q.setQueryPattern(body);
		q.setQuerySelectType();
		q.addResultVar(HLCA.hlcSparqlVar);
		return q;
	}
	/**
	 * Method to create a select SPARQL query for Low Level Context.
	 * 
	 * @param block
	 *            Triples block to be part of the SPARQL query.
	 * @param filter1
	 *            First filter to be part of the SPARQL query.
	 * @param filter2
	 *            Second filter to be part of the SPARQL query.
	 * @return A select SPARQL query for Low Level Context which is composed of
	 *         the block, filter1 and filter2.
	 */
		private  Query createLlcQuery(ElementUnion union, ElementFilter filter1, ElementFilter filter2) {
		ElementGroup body = new ElementGroup();
		body.addElement(union);
		body.addElement(filter1);
		body.addElement(filter2);
		Query q = QueryFactory.make();
		q.setQueryPattern(body);
		q.setQuerySelectType();
		q.addResultVar(HLCA.llcSparqlVar);
		return q;
	}
	/**
	 * Method to create a select SPARQL query for Low Level Context.
	 * 
	 * @param block
	 *            Triples block to be part of the SPARQL query.
	 * @param filter1
	 *            First filter to be part of the SPARQL query.
	 * @param filter2
	 *            Second filter to be part of the SPARQL query.
	 * @param filter3
	 *            Third filter to be part of the SPARQL query.
	 * @return A select SPARQL query for Low Level Context which is composed of
	 *         the block, filter1, filter2 and filter3.
	 */
	private  Query createLlcQuery(ElementUnion union, ElementFilter filter1, ElementFilter filter2,
			ElementFilter filter3) {
		ElementGroup body = new ElementGroup();
		body.addElement(union);
		body.addElement(filter1);
		body.addElement(filter2);
		body.addElement(filter3);
		Query q = QueryFactory.make();
		q.setQueryPattern(body);
		q.setQuerySelectType();
		q.addResultVar(HLCA.llcSparqlVar);
		return q;
	}
	/**
	 * Method to create a select SPARQL query for Low Level Context.
	 * 
	 * @param block
	 *            Triples block to be part of the SPARQL query.
	 * @param filter1
	 *            First filter to be part of the SPARQL query.
	 * @param filter2
	 *            Second filter to be part of the SPARQL query.
	 * @param filter3
	 *            Third filter to be part of the SPARQL query.
	 * @param filter4
	 *            Forth filter to be part of the SPARQL query.
	 * @return A select SPARQL query for Low Level Context which is composed of
	 *         the block, filter1, filter2 and filter3.
	 */
	private  Query createLlcQuery(ElementUnion union , ElementFilter filter1, ElementFilter filter2, 
			ElementFilter filter3, ElementFilter filter4) {
		ElementGroup body = new ElementGroup();
		body.addElement(union);
		body.addElement(filter1);
		body.addElement(filter2);
		body.addElement(filter3);
		body.addElement(filter4);
		Query q = QueryFactory.make();
		q.setQueryPattern(body);
		q.setQuerySelectType();
		q.addResultVar(HLCA.llcSparqlVar);
		return q;
	}
	/**
	 * Method to create a select SPARQL query for the minimum start time of a
	 * context.
	 * 
	 * @param block
	 *            Triples block to be part of the SPARQL query.
	 * @param filter
	 *            Filter to be part of the SPARQL query.
	 * @return A select SPARQL query for the minimum start time of a context.
	 */
	private  Query createMinStartTimeQuery(ElementUnion union , ElementFilter filter) {  
		ElementGroup body = new ElementGroup();
		body.addElement(union);
		body.addElement(filter);
		Query q = QueryFactory.make();
		q.setQueryPattern(body);
		q.setQuerySelectType();
		q.allocAggregate(AggregatorFactory.createMin(false, new ExprVar(HLCA.startTimeSparqlVar)));
		return q;
	}
	private ContextQueryGenerator(){
		
	}
	public static ContextQueryGenerator getContextQueryGenerator(){
		if(contextQueryGenerator == null){
			contextQueryGenerator = new ContextQueryGenerator();
		}
		return contextQueryGenerator;
	}
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/config/UnifierType.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Kang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.config;



public enum UnifierType {
	
	MajorityVoting(0);
    private int value;
    
    /**
     * Unique constructor of UnifierType.
     * @param _value
     */
    private UnifierType(int _value){
        value = _value;
    }
    
    /**
     * Return the string which describes the current unifier type
     */
    @Override
    public String toString(){
    	switch(value){
    	case 0:
    		return "MajorityVoting";
    	}
    	return null;
    }
    
    
    
    
}

<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/ic/dataadapter/FoodLogAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.ic.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.ic.FoodLog;


/**
 * This is FoodLogAdapter class which implements the Data Access Interface for CRUD operations
 * @author Taqdir
 */
public class FoodLogAdapter implements DataAccessInterface {

    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(FoodLogAdapter.class);
    public FoodLogAdapter()
    {
        
    }
   
    /**
     * This is implementation function for saving FoodLog. 
     * @param objFoodLog
     * @return List of String
     */
    @Override
    public List<String> Save(Object objFoodLog) {
        FoodLog objInnerFoodLog = new FoodLog();
        objInnerFoodLog =  (FoodLog) objFoodLog;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {
                  
            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_FoodLog(?, ?, ?, ?, ?)}");
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
            Date dtEatingTime = sdf.parse(objInnerFoodLog.getEatingTime());
            Timestamp tsEatingTime = new Timestamp(dtEatingTime.getYear(),dtEatingTime.getMonth(), dtEatingTime.getDate(), dtEatingTime.getHours(), dtEatingTime.getMinutes(),dtEatingTime.getSeconds(),0);
                       
            objCallableStatement.setLong("UserID", objInnerFoodLog.getUserId());
            objCallableStatement.setString("FoodName", objInnerFoodLog.getFoodName());
            objCallableStatement.setTimestamp("EatingTime", tsEatingTime);
            
            if(objInnerFoodLog.getByteImage() != null)
            {
                objCallableStatement.setBytes("FoodImage", objInnerFoodLog.getByteImage());
            }
            else
            {
                objCallableStatement.setBytes("FoodImage", null);
            }
                                   
            objCallableStatement.registerOutParameter("FoodLogID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intFoodLogID = objCallableStatement.getLong("FoodLogID");
            objDbResponse.add(String.valueOf(intFoodLogID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("food log saved successfully, food log Details="+objFoodLog);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding food log");
        	objDbResponse.add("Error in adding food log");
        } 
        return objDbResponse;
    }

    @Override
    public <T> List<String> Update(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    /**
     * This is implementation function for retrieving FoodLog.
     * @param objFoodLog
     * @return List of FoodLog 
     */
    @Override
    public List<FoodLog> RetriveData(Object objFoodLog) {
        FoodLog objOuterFoodLog = new FoodLog();
        List<FoodLog> objListInnerFoodLog = new ArrayList<FoodLog>();
        objOuterFoodLog =  (FoodLog) objFoodLog;
        
        try
        {
            CallableStatement objCallableStatement = null;
            Timestamp tsStartDate = null;
            Timestamp tsEndDate = null;
                       
            if(objOuterFoodLog.getRequestType() == "LatestByUser")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_FoodLogByUserLatest(?)}");
                objCallableStatement.setLong("UserID", objOuterFoodLog.getUserId());
                ResultSet objResultSet = objCallableStatement.executeQuery();
                while(objResultSet.next())
                {
                    FoodLog objInnerFoodLog = new FoodLog();
                    objInnerFoodLog.setUserId(objResultSet.getLong("UserID"));
                    objInnerFoodLog.setFoodName(objResultSet.getString("FoodName"));
                    Timestamp tsEatingTime = null;
                    if(objResultSet.getTimestamp("EatingTime") != null)
                    {
                        tsEatingTime = objResultSet.getTimestamp("EatingTime");// updated
                        objInnerFoodLog.setStartTime( tsEatingTime.toString());
                    }
                    else
                    {
                        objInnerFoodLog.setStartTime(null);
                    }
                    objListInnerFoodLog.add(objInnerFoodLog);
                }
                objConn.close();
                logger.info("food log loaded successfully");
            }
            else
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_FoodLogByUserIDandDateRange(?, ?, ?)}");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
               if(objOuterFoodLog.getStartTime() != null)
                {
                    Date dtStartDate = sdf.parse(objOuterFoodLog.getStartTime());
                    tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);
                }
                else
                {
                    tsStartDate = null;
                }
                if(objOuterFoodLog.getStartTime() != null)
                {
                    Date dtEndDate = sdf.parse(objOuterFoodLog.getEndTime());
                    tsEndDate = new Timestamp(dtEndDate.getYear(),dtEndDate.getMonth(), dtEndDate.getDate(), dtEndDate.getHours(), dtEndDate.getMinutes(),dtEndDate.getSeconds(),0);
                }
                else
                {
                    tsEndDate = null;
                }
                objCallableStatement.setLong("UserID", objOuterFoodLog.getUserId());
                objCallableStatement.setTimestamp("StartTime", tsStartDate);
                objCallableStatement.setTimestamp("EndTime", tsEndDate);
                
                ResultSet objResultSet = objCallableStatement.executeQuery();
                while(objResultSet.next())
                {
                    FoodLog objInnerFoodLog = new FoodLog();
                    objInnerFoodLog.setUserId(objResultSet.getLong("UserID"));
                    objInnerFoodLog.setFoodName(objResultSet.getString("FoodName"));
                    
                    objInnerFoodLog.setTotalFoodItem(objResultSet.getLong("TotalFoodItem"));
                    objInnerFoodLog.setEatingTime(objResultSet.getString("EatingTime"));
                    objInnerFoodLog.setTotalFat(objResultSet.getLong("TotalFat")); 
                    objInnerFoodLog.setTotalProtein(objResultSet.getLong("TotalProtein"));
                    objInnerFoodLog.setTotalCarbohydrate(objResultSet.getLong("TotalCarbohydrate"));
                     
                    objListInnerFoodLog.add(objInnerFoodLog);
                }
                objConn.close();
                logger.info("food log loaded successfully");
            }
        }
        catch (Exception e)
        {
        	logger.info("Error in loading  food log");
        }   
        return objListInnerFoodLog;
    }
  
    
    
    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/hlca/ContextCSV.java<|end_filename|>
package mm.hlca;

public class ContextCSV {

    private String userId;
    private String llcLabel;
    private String cal;
  
    
    public ContextCSV(String userId, String cal, String llcLabel) {

    	super();
        this.userId = userId;
        this.cal = cal;
        this.llcLabel = llcLabel;
    }
    public ContextCSV()
    {
    	
    }
    
    public String getuserId() {
        return userId;
    }
    public void setuserId(String userId) {
        this.userId = userId;
    }
    public String getcal() {
        return cal;
    }
    public void setCal(String cal) {
        this.cal= cal;
    }

    public String getllcLabel() {
        return llcLabel;
    }
    public void setllcLabel(String llcLabel) {
        this.llcLabel = llcLabel;
    }
    
//    @Override
//    public String toString() {
//        return "Employee [empId=" + userId //+ ", userId=" + userId
//                + ", llcLabel=" + llcLabel + ", cal=" + cal + "]";
//    }
//    
    
}








/*
 * 
 * package contextInputcsv;

public class ContextCSV {


    private int empId;
    private String firstName;
    private String lastName;
    private int salary;
    
    public ContextCSV(int empId, String firstName, 
                     String lastName, int salary) {
        super();
        this.empId = empId;
        this.firstName = firstName;
        this.lastName = lastName;
        this.salary = salary;
    }
    
    public int getEmpId() {
        return empId;
    }
    public void setEmpId(int empId) {
        this.empId = empId;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Employee [empId=" + empId + ", firstName=" + userId
                + ", lastName=" + lastName + ", salary=" + salary + "]";
    }
    
    
}

 * 
 * 
 * 
 * 
 * 
 * */


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/MMDataCurationRestfulService/src/main/java/org/uclab/mm/rs/servicecuration/ServiceCurationResource.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.rs.servicecuration;

import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.AbstractDataBridge;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.DatabaseStorage;
import org.uclab.mm.datamodel.dc.dataadapter.UserDataAdapter;
import org.uclab.mm.datamodel.ic.FoodLog;
import org.uclab.mm.datamodel.ic.UserDetectedLocation;
import org.uclab.mm.datamodel.ic.UserRecognizedActivity;
import org.uclab.mm.datamodel.ic.UserRecognizedEmotion;
import org.uclab.mm.datamodel.ic.UserRecognizedHLC;
import org.uclab.mm.datamodel.ic.dataadapter.FoodLogAdapter;
import org.uclab.mm.datamodel.ic.dataadapter.UserDetectedLocationAdapter;
import org.uclab.mm.datamodel.ic.dataadapter.UserRecognizedActivityAdapter;
import org.uclab.mm.datamodel.ic.dataadapter.UserRecognizedEmotionAdapter;
import org.uclab.mm.datamodel.ic.dataadapter.UserRecognizedHLCAdapter;
import org.uclab.mm.datamodel.sc.Achievements;
import org.uclab.mm.datamodel.sc.ActivityPlan;
import org.uclab.mm.datamodel.sc.ActivityRecommendation;
import org.uclab.mm.datamodel.sc.ActivityRecommendationLog;
import org.uclab.mm.datamodel.sc.CurrentContextPacket;
import org.uclab.mm.datamodel.sc.Facts;
import org.uclab.mm.datamodel.sc.ProfileData;
import org.uclab.mm.datamodel.sc.Recommendation;
import org.uclab.mm.datamodel.sc.RecommendationException;
import org.uclab.mm.datamodel.sc.RecommendationExplanation;
import org.uclab.mm.datamodel.sc.Situation;
import org.uclab.mm.datamodel.sc.UserGoal;
import org.uclab.mm.datamodel.sc.UserPreferredActivities;
import org.uclab.mm.datamodel.sc.UserRewards;
import org.uclab.mm.datamodel.sc.dataadapter.AchievementsAdapter;
import org.uclab.mm.datamodel.sc.dataadapter.ActivityPlanAdapter;
import org.uclab.mm.datamodel.sc.dataadapter.ActivityRecommendationAdapter;
import org.uclab.mm.datamodel.sc.dataadapter.ActivityRecommendationLogAdapter;
import org.uclab.mm.datamodel.sc.dataadapter.FactsAdapter;
import org.uclab.mm.datamodel.sc.dataadapter.ProfileDataAdapter;
import org.uclab.mm.datamodel.sc.dataadapter.RecommendationAdapter;
import org.uclab.mm.datamodel.sc.dataadapter.RecommendationExceptionAdapter;
import org.uclab.mm.datamodel.sc.dataadapter.RecommendationExplanationAdapter;
import org.uclab.mm.datamodel.sc.dataadapter.SituationAdapter;
import org.uclab.mm.datamodel.sc.dataadapter.UserGoalAdapter;
import org.uclab.mm.datamodel.sc.dataadapter.UserPreferredActivitiesAdapter;
import org.uclab.mm.datamodel.sc.dataadapter.UserRewardsAdapter;
import org.uclab.mm.rs.datacuration.DataCurationResource;

/**
 * REST Web Service
 *
 * @author <NAME>
 */
@Path("ServiceCuration")
public class ServiceCurationResource {

    @Context
    private UriInfo context;

    /**
     * Creates a new instance of ServiceCurationResource
     */
    public ServiceCurationResource() {
    }

    private static final Logger logger = LoggerFactory.getLogger(DataCurationResource.class);
    
    /**
     * This function is using to Retrieves Profile Data by UserID 
     * @param UserID
     * @return an instance of List of ProfileData
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("ProfileData/{UserID}")
    public List<ProfileData> GetProfileData(@PathParam ("UserID") String UserID) {
        ProfileData objOuterProfileData = new ProfileData();
        List<ProfileData> objListProfileData = new  ArrayList<>();
        try
        {
            objOuterProfileData.setUserID(Long.parseLong(UserID));
            DataAccessInterface objDAInterface = new ProfileDataAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListProfileData = objADBridge.RetriveProfileData(objOuterProfileData);
            logger.info("Profile Data loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Profile Data");
        }
        return objListProfileData;
    }
    
    /**
     * This function is using to Add User Preferred Activities
     * @param objOuterUserPreferredActivities
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddUserPreferredActivities")
    public List<String> AddUserPreferredActivities(UserPreferredActivities objOuterUserPreferredActivities) {
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserPreferredActivitiesAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveUserPreferredActivities(objOuterUserPreferredActivities);
            logger.info("User Preferred Activities saved successfully, User Preferred Activities Details="+objOuterUserPreferredActivities);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding User Preferred Activities");
        	response.add("Error in adding User Preferred Activities");
        }
        return response;
    }
    
    /**
     * This function is using to Retrieves users preferred activities by UserID 
     * @param UserID
     * @return an instance of list of UserPreferredActivities
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UserPreferredActivities/{UserID}")
    public List<UserPreferredActivities> GetUserPreferredActivities(@PathParam ("UserID") String UserID) {
        UserPreferredActivities objOuterUserPreferredActivities = new UserPreferredActivities();
        List<UserPreferredActivities> objListUserPreferredActivities = new  ArrayList<UserPreferredActivities>();
        try
        {
            objOuterUserPreferredActivities.setUserId(Long.parseLong(UserID));
            DataAccessInterface objDAInterface = new UserPreferredActivitiesAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserPreferredActivities = objADBridge.RetriveUserPreferredActivities(objOuterUserPreferredActivities);
            logger.info("User Preferred Activities Data loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Profile Data");
        }
        return objListUserPreferredActivities;
    }
    
    
    /**
     * This function is using to Update User Preferred Activities
     * @param objOuterUserPreferredActivities
     * @return a list of object string with "Error", "No Error" and updated ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UpdateUserPreferredActivities")
    public List<String> UpdateUserPreferredActivities(UserPreferredActivities objOuterUserPreferredActivities) {
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserPreferredActivitiesAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.UpdateUserPreferredActivities(objOuterUserPreferredActivities);
            logger.info("User Preferred Activities updated successfully, User Preferred Activities Details="+objOuterUserPreferredActivities);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating User Preferred Activities");
        	response.add("Error in updating User Preferred Activities");
        }
        return response;
    }
    
    /**
     * This function is using to Add User Goal
     * @param objOuterUserGoal
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddUserGoal")
    public List<String> AddUserGoal(UserGoal objOuterUserGoal) {
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserGoalAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveUserGoal(objOuterUserGoal);
            logger.info("User Goal saved successfully, User Goal Details="+objOuterUserGoal);
        }
        catch(Exception ex)
        {
        	logger.info("Error in Adding User Goal");
        	response.add("Error in Adding User Goal");
        }
        return response;
    }
    
    /**
     * This function is using to Retrieves User Goal by UserID 
     * @param UserID
     * @return an instance of list of UserGoal
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UserGoal/{UserID}")
    public List<UserGoal> GetUserGoal(@PathParam ("UserID") String UserID) {
        UserGoal objOuterUserGoal = new UserGoal();
        List<UserGoal> objListUserGoal = new  ArrayList<UserGoal>();
        try
        {
            objOuterUserGoal.setUserId(Long.parseLong(UserID));
            objOuterUserGoal.setRequestType("ByUserOnly");
            DataAccessInterface objDAInterface = new UserGoalAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserGoal = objADBridge.RetriveUserGoal(objOuterUserGoal);
            logger.info(" User Goal loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading  User Goal");
        }
        return objListUserGoal;
    }
    
    /**
     * This function is using to Retrieves User Goal by UserID, start time and end time
     * @param objOuterUserGoal
     * @return an instance of list of UserGoal
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("RetrieveUserBurnedCaloriesByDate")
    public List<UserGoal> RetrieveUserBurnedCaloriesByDate(UserGoal objOuterUserGoal) {
        List<UserGoal> objListUserGoal = new  ArrayList<UserGoal>();
        try
        {
            objOuterUserGoal.setRequestType("ByUserandDate");
            DataAccessInterface objDAInterface = new UserGoalAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserGoal = objADBridge.RetriveUserGoal(objOuterUserGoal);
            logger.info("User Goal loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading User Goal");
        }
        return objListUserGoal;
    }
    
    /**
     * This function is using to add Activity Plan
     * @param objOuterActivityPlan
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddActivityPlan")
    public List<String> AddActivityPlan(ActivityPlan objOuterActivityPlan) {
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new ActivityPlanAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveActivityPlan(objOuterActivityPlan);
            logger.info("Activity Plan saved successfully, Activity Plan Details="+objOuterActivityPlan);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Activity Plan");
        	response.add("Error in adding Activity Plan");
        }
        return response;
    }
    
    /**
     * This function is using to Retrieves User Goal by UserGoalID 
     * @param UserGoalID
     * @return an instance of list of ActivityPlan
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("ActivityPlan/{UserGoalID}")
    public List<ActivityPlan> GetActivityPlan(@PathParam ("UserGoalID") String UserGoalID) {
        ActivityPlan objOuterActivityPlan = new ActivityPlan();
        List<ActivityPlan> objListActivityPlan = new  ArrayList<ActivityPlan>();
        try
        {
            objOuterActivityPlan.setUserGoalId(Long.parseLong(UserGoalID));
            DataAccessInterface objDAInterface = new ActivityPlanAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListActivityPlan = objADBridge.RetriveActivityPlan(objOuterActivityPlan);
            logger.info("User Goal loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading User Goal");
        }
        return objListActivityPlan;
    }
    
     /**
     * This function is using to add Activity Recommendation
     * @param objOuterActivityRecommendation
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddActivityRecommendation")
    public List<String> AddActivityRecommendation(ActivityRecommendation objOuterActivityRecommendation) {
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new ActivityRecommendationAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveActivityRecommendation(objOuterActivityRecommendation);
            logger.info("Activity Recommendation saved successfully, Activity Recommendation Details="+objOuterActivityRecommendation);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Activity Recommendation");
        	response.add("Error in adding Activity Recommendation");
        }
        return response;
    }
    
    /**
     * This function is using to add Activity Recommendation for log
     * @param objOuterActivityRecommendationLog
     * @return  a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddActivityRecommendationLog")
    public List<String> AddActivityRecommendationLog(ActivityRecommendationLog objOuterActivityRecommendationLog) {
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new ActivityRecommendationLogAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveActivityRecommendationLog(objOuterActivityRecommendationLog);
            logger.info("Activity Recommendation saved successfully, Activity Recommendation Details="+objOuterActivityRecommendationLog);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Activity Recommendation");
        	response.add("Error in adding Activity Recommendation");
        }
        return response;
    }
    
    /**
     * This function is using to Retrieve Activity Recommendation By ActivityPlanID 
     * @param ActivityPlanID
     * @return an instance of list of ActivityRecommendation
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("ActivityRecommendation/{ActivityPlanID}")
    public List<ActivityRecommendation> RetrieveActivityRecommendationByActivityPlanID(@PathParam ("ActivityPlanID") String ActivityPlanID) {
        ActivityRecommendation objOuterActivityRecommendation = new ActivityRecommendation();
        List<ActivityRecommendation> objListActivityRecommendation = new  ArrayList<ActivityRecommendation>();
        try
        {
            objOuterActivityRecommendation.setActivityPlanId(Long.parseLong(ActivityPlanID));
            objOuterActivityRecommendation.setRequestType("ByPlan");
            
            DataAccessInterface objDAInterface = new ActivityRecommendationAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListActivityRecommendation = objADBridge.RetriveActivityRecommendation(objOuterActivityRecommendation);
            logger.info("Activity Recommendation loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Activity Recommendation");
        }
        return objListActivityRecommendation;
    }
    
    /**
     * This function is using to Retrieve Activity Recommendation Log By ActivityPlanID 
     * @param ActivityPlanID
     * @return an instance of list of ActivityRecommendationLog
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("ActivityRecommendationLog/{ActivityPlanID}")
    public List<ActivityRecommendationLog> RetrieveActivityRecommendationLogByActivityPlanID(@PathParam ("ActivityPlanID") String ActivityPlanID) {
        ActivityRecommendationLog objOuterActivityRecommendationLog = new ActivityRecommendationLog();
        List<ActivityRecommendationLog> objListActivityRecommendationLog = new  ArrayList<ActivityRecommendationLog>();
        try
        {
            objOuterActivityRecommendationLog.setActivityPlanId(Long.parseLong(ActivityPlanID));
            objOuterActivityRecommendationLog.setRequestType("ByPlan");
            
            DataAccessInterface objDAInterface = new ActivityRecommendationLogAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListActivityRecommendationLog = objADBridge.RetriveActivityRecommendationLog(objOuterActivityRecommendationLog);
            logger.info("Activity Recommendation loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Activity Recommendation");
        }
        return objListActivityRecommendationLog;
    }
    
    /**
     * This function is using to Retrieves User Activity Recommendation by UserID and date range
     * @param objOuterActivityRecommendation
     * @return an instance of list of ActivityRecommendation
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("RetrieveActivityRecommendationByUserAndDate")
    public List<ActivityRecommendation> RetrieveActivityRecommendationByUserAndDate(ActivityRecommendation objOuterActivityRecommendation) {
        List<ActivityRecommendation> objListActivityRecommendation = new  ArrayList<ActivityRecommendation>();
        try
        {
            objOuterActivityRecommendation.setRequestType("ByUserDate");
            DataAccessInterface objDAInterface = new ActivityRecommendationAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListActivityRecommendation = objADBridge.RetriveActivityRecommendation(objOuterActivityRecommendation);
            logger.info("Activity Recommendation loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Activity Recommendation");
        }
        return objListActivityRecommendation;
    }
    
    /**
     * This function is using to Retrieves User Activity Recommendation Log by UserID and date range
     * @param objOuterActivityRecommendationLog
     * @return an instance of list of ActivityRecommendationLog 
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("RetrieveActivityRecommendationLogByUserAndDate")
    public List<ActivityRecommendationLog> RetrieveActivityRecommendationLogByUserAndDate(ActivityRecommendationLog objOuterActivityRecommendationLog) {
        List<ActivityRecommendationLog> objListActivityRecommendationLog = new  ArrayList<ActivityRecommendationLog>();
        try
        {
            objOuterActivityRecommendationLog.setRequestType("ByUserDate");
            DataAccessInterface objDAInterface = new ActivityRecommendationLogAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListActivityRecommendationLog = objADBridge.RetriveActivityRecommendationLog(objOuterActivityRecommendationLog);
            logger.info("Activity Recommendation log loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Activity Recommendation log");
        }
        return objListActivityRecommendationLog;
    }
    
    /**
     * This function is using to  Retrieves User Rewards by UserID 
     * @param UserID
     * @return an instance of list of UserRewards
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UserRewards/{UserID}")
    public List<UserRewards> GetUserRewards(@PathParam ("UserID") String UserID) {
        UserRewards objOuterUserRewards = new UserRewards();
        List<UserRewards> objListUserRewards = new  ArrayList<UserRewards>();
        try
        {
            objOuterUserRewards.setUserID(Long.parseLong(UserID));
                       
            DataAccessInterface objDAInterface = new UserRewardsAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserRewards = objADBridge.RetriveUserRewards(objOuterUserRewards);
            logger.info(" User Rewards loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading  User Rewards");
        }
        return objListUserRewards;
    }
    
    /**
     * This function is using to update User Rewards
     * @param objOuterUserRewards
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UpdateUserRewards")
    public List<String> UpdateUserRewards(UserRewards objOuterUserRewards) {
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserRewardsAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.UpdateUserRewards(objOuterUserRewards);
            logger.info("User Rewards updated successfully, User Rewards Details="+objOuterUserRewards);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating User Rewards");
        	response.add("Error in updating User Rewards");
        }
        return response;
    }
    
    /**
     * This function is using to add User Rewards
     * @param objOuterUserRewards
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddUserRewards")
    public List<String> AddUserRewards(UserRewards objOuterUserRewards) {
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new UserRewardsAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveUserRewards(objOuterUserRewards);
            logger.info("User Rewards saved successfully, User Rewards Details="+objOuterUserRewards);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding User Rewards");
        	response.add("Error in adding User Rewards");
        }
        return response;
    }
    
    /**
     * This function is using to Add situation
     * @param objOuterSituation
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddSituation")
    public List<String> AddSituation(Situation objOuterSituation) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new SituationAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveSituation(objOuterSituation);
            logger.info("situation saved successfully, User Details="+objOuterSituation);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding situation");
        	response.add("Error in adding situation");
        }
        return response;
    }
    
    /**
     * This function is using to Update situation
     * @param objOuterSituation
     * @return  a list of object string with "Error", "No Error" and updated ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UpdateSituation")
    public List<String> UpdateSituation(Situation objOuterSituation) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new SituationAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.UpdateSituation(objOuterSituation);
            logger.info("situation saved successfully, situation Details="+objOuterSituation);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating situation");
        	response.add("Error in updating situation");
        }
        return response;
    }
    
    /**
     * This function is using to Retrieves situation by UserID 
     * @param UserID
     * @return an instance of list of Situation
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("Situation/{UserID}")
    public List<Situation> RetrieveSituationByUserID(@PathParam ("UserID") String UserID) {
        Situation objOuterSituation = new Situation();
        List<Situation> objListSituation = new  ArrayList<Situation>();
        try
        {
            objOuterSituation.setUserID(Long.parseLong(UserID));
            objOuterSituation.setRequestType("ByUserOnly");
            
            DataAccessInterface objDAInterface = new SituationAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListSituation = objADBridge.RetriveSituation(objOuterSituation);
            logger.info("situation loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading situation");
        }
        return objListSituation;
    }
    
    /**
     * This function is using to Retrieves Situation by UserID and date range
     * @param objOuterSituation
     * @return an instance of list of Situation
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("RetrieveSituationByUserIDDate")
    public List<Situation> RetrieveSituationByUserIDDate(Situation objOuterSituation) {
        
        List<Situation> objListSituation = new  ArrayList<Situation>();
        try
        {
            objOuterSituation.setRequestType("ByUserandDate");
            
            DataAccessInterface objDAInterface = new SituationAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListSituation = objADBridge.RetriveSituation(objOuterSituation);
            logger.info("situation loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading situation");
        }
        return objListSituation;
    }
    
    /**
     *  This function is using to Retrieves situation by SituationID 
     * @param SituationID
     * @return an instance of list of Situation
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("SituationBySituationID/{SituationID}")
    public List<Situation> RetrieveSituationBySituationID(@PathParam ("SituationID") String SituationID) {
        Situation objOuterSituation = new Situation();
        List<Situation> objListSituation = new  ArrayList<Situation>();
        try
        {
            objOuterSituation.setSituationID(Long.parseLong(SituationID));
            objOuterSituation.setRequestType("BySituationID");
            
            DataAccessInterface objDAInterface = new SituationAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListSituation = objADBridge.RetriveSituation(objOuterSituation);
            logger.info("situation loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading situation");
        }
        return objListSituation;
    }
    
    
    /**
     *  This function is using to Add Recommendation
     * @param objRecommendation
     * @return  a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddRecommendation")
    public List<String> AddRecommendation(Recommendation objRecommendation) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new RecommendationAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveRecommendation(objRecommendation);
            logger.info("Recommendation saved successfully, Recommendation Details="+objRecommendation);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Recommendation");
        	response.add("Error in adding Recommendation");
        }
        return response;
    }
    
    /**
     * This function is using to Update Recommendation
     * @param objRecommendation
     * @return list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UpdateRecommendation")
    public List<String> UpdateRecommendation(Recommendation objRecommendation) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new RecommendationAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.UpdateRecommendation(objRecommendation);
            logger.info("Recommendation saved successfully, Recommendation Details="+objRecommendation);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating Recommendation");
        	response.add("Error in updating Recommendation");
        }
       return response;
    }
    
    /**
     * This function is using to Retrieves Recommendation by UserID 
     * @param UserID
     * @return an instance of list of Recommendation
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("Recommendation/{UserID}")
    public List<Recommendation> RetrieveRecommendationByUserID(@PathParam ("UserID") String UserID) {
        Recommendation objOuterRecommendation = new Recommendation();
        List<Recommendation> objListRecommendation = new  ArrayList<Recommendation>();
        try
        {
            objOuterRecommendation.setUserID(Long.parseLong(UserID));
            objOuterRecommendation.setRequestType("ByUserOnly");
            
            DataAccessInterface objDAInterface = new RecommendationAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListRecommendation = objADBridge.RetriveRecommendation(objOuterRecommendation);
            logger.info("Recommendation loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Recommendation");
        }
        return objListRecommendation;
    }
    
    /**
     * This function is using to Retrieves Recommendation by UserID and date range
     * @param objOuterRecommendation
     * @return an instance of list of Recommendation
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("RetrieveRecommendationByUserIDDate")
    public List<Recommendation> RetrieveRecommendationByUserIDDate(Recommendation objOuterRecommendation) {
        
        List<Recommendation> objListRecommendation = new  ArrayList<Recommendation>();
        try
        {
            objOuterRecommendation.setRequestType("ByUserandDate");
            
            DataAccessInterface objDAInterface = new RecommendationAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListRecommendation = objADBridge.RetriveRecommendation(objOuterRecommendation);
            logger.info("Recommendation loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Recommendation");
        }
        
        return objListRecommendation;
    }
    
    /**
     * This function is using to Retrieves Recommendation by Situation Category ID and date range
     * @param objOuterRecommendation
     * @return an instance of list of Recommendation
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("RetrieveRecommendationByDateRangeActivityIDs")
    public List<Recommendation> RetrieveRecommendationByDateRangeActivityIDs(Recommendation objOuterRecommendation) {
        
        List<Recommendation> objListRecommendation = new  ArrayList<Recommendation>();
        try
        {
            objOuterRecommendation.setRequestType("ByActivityIDsAndDate");
            
            DataAccessInterface objDAInterface = new RecommendationAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListRecommendation = objADBridge.RetriveRecommendation(objOuterRecommendation);
            logger.info("Recommendation loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Recommendation");
        }
        
        return objListRecommendation;
    }
    
    /**
     * This function is using to Add RecommendationException
     * @param objRecommendationException
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddRecommendationException")
    public List<String> AddRecommendationException(RecommendationException objRecommendationException) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new RecommendationExceptionAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveRecommendationException(objRecommendationException);
            logger.info("RecommendationException saved successfully, RecommendationException Details="+objRecommendationException);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding RecommendationException");
        	response.add("Error in adding RecommendationException");
        }
       return response;
    }
    
    /**
     * This function is using to Update RecommendationException
     * @param objRecommendationException
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UpdateRecommendationException")
    public List<String> UpdateRecommendationException(RecommendationException objRecommendationException) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new RecommendationExceptionAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.UpdateRecommendationException(objRecommendationException);
            logger.info("RecommendationException updated successfully, RecommendationException Details="+objRecommendationException);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating RecommendationException");
        	response.add("Error in updating RecommendationException");
        }
        return response;
    }
    
    /**
     * This function is using to Retrieves Recommendation Exception by RecommendationID 
     * @param RecommendationID
     * @return an instance of list of RecommendationException
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("RecommendationException/{RecommendationID}")
    public List<RecommendationException> RetrieveRecommendationExceptionByRecommendationID(@PathParam ("RecommendationID") String RecommendationID) {
        RecommendationException objOuterRecommendationException = new RecommendationException();
        List<RecommendationException> objListRecommendationException = new  ArrayList<RecommendationException>();
        try
        {
            objOuterRecommendationException.setRecommendationID(Long.parseLong(RecommendationID));
            
            DataAccessInterface objDAInterface = new RecommendationExceptionAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListRecommendationException = objADBridge.RetriveRecommendationException(objOuterRecommendationException);
            logger.info("Recommendation Exception loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Recommendation Exception");
        }
        return objListRecommendationException;
    }
    
    /**
     * This function is using to Add RecommendationExplanation
     * @param objRecommendationExplanation
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddRecommendationExplanation")
    public List<String> AddRecommendationExplanation(RecommendationExplanation objRecommendationExplanation) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new RecommendationExplanationAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveRecommendationExplanation(objRecommendationExplanation);
            logger.info("RecommendationExplanation saved successfully, RecommendationExplanation Details="+objRecommendationExplanation);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding RecommendationExplanation");
        	response.add("Error in adding RecommendationExplanation");
        }
        return response;
    }
    
    /**
     * This function is using to Update RecommendationExplanation
     * @param objRecommendationExplanation
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UpdateRecommendationExplanation")
    public List<String> UpdateRecommendationExplanation(RecommendationExplanation objRecommendationExplanation) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new RecommendationExplanationAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.UpdateRecommendationExplanation(objRecommendationExplanation);
            logger.info("RecommendationExplanation updated successfully, RecommendationExplanation Details="+objRecommendationExplanation);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating RecommendationExplanation");
        	response.add("Error in updating RecommendationExplanation");
        }
        return response;
    }
    
    /**
     * This function is using to Retrieves Recommendation Explanation by RecommendationID 
     * @param RecommendationID
     * @return an instance of list of RecommendationExplanation
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("RecommendationExplanation/{RecommendationID}")
    public List<RecommendationExplanation> RetrieveRecommendationExplanationByRecommendationID(@PathParam ("RecommendationID") String RecommendationID) {
        RecommendationExplanation objOuterRecommendationExplanation = new RecommendationExplanation();
        List<RecommendationExplanation> objListRecommendationExplanation = new  ArrayList<RecommendationExplanation>();
        try
        {
            objOuterRecommendationExplanation.setRecommendationID(Long.parseLong(RecommendationID));
            
            DataAccessInterface objDAInterface = new RecommendationExplanationAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListRecommendationExplanation = objADBridge.RetriveRecommendationExplanation(objOuterRecommendationExplanation);
            logger.info("Recommendation Explanation loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Recommendation Explanation");
        }
        return objListRecommendationExplanation;
    }
    
    /**
     * This function is using to Add Facts
     * @param objFacts
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddFacts")
    public List<String> AddFacts(Facts objFacts) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new FactsAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveFacts(objFacts);
            logger.info("Facts saved successfully, Facts Details="+objFacts);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Facts");
        	response.add("Error in adding Facts");
        }
        return response;
    }
    
    /**
     * This function is using to Update Facts
     * @param objFacts
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UpdateFacts")
    public List<String> UpdateFacts(Facts objFacts) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new FactsAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.UpdateFacts(objFacts);
            logger.info("Facts updated successfully, Facts Details="+objFacts);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating Facts");
        	response.add("Error in updating Facts");
        }
        return response;
    }
    
    /**
     * This function is using to Retrieves Facts by UserID 
     * @param UserID
     * @return an instance of list of Facts
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("Facts/{UserID}")
    public List<Facts> RetrieveFactsByUserID(@PathParam ("UserID") String UserID) {
        Facts objOuterFacts = new Facts();
        List<Facts> objListFacts = new  ArrayList<Facts>();
        try
        {
            objOuterFacts.setUserID(Long.parseLong(UserID));
            objOuterFacts.setRequestType("ByUserOnly");
            
            DataAccessInterface objDAInterface = new FactsAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListFacts = objADBridge.RetriveFacts(objOuterFacts);
            logger.info("Facts loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Facts");
        }
        
        return objListFacts;
    }
    
    /**
     * This function is using to Retrieves Facts by UserID and date range
     * @param objOuterFacts
     * @return an instance of list of Facts
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("RetrieveFactsByUserIDDate")
    public List<Facts> RetrieveFactsByUserIDDate(Facts objOuterFacts) {
        
        List<Facts> objListFacts = new  ArrayList<Facts>();
        try
        {
            objOuterFacts.setRequestType("ByUserandDate");
            
            DataAccessInterface objDAInterface = new FactsAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListFacts = objADBridge.RetriveFacts(objOuterFacts);
            logger.info("Facts loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Facts");
        }
        
        return objListFacts;
    }
    
    /**
     * This function is using to Add Achievements
     * @param objAchievements
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("AddAchievements")
    public List<String> AddAchievements(Achievements objAchievements) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new AchievementsAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.SaveAchievements(objAchievements);
            logger.info("Achievements saved successfully, Achievements Details="+objAchievements);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Achievements");
        	response.add("Error in adding Achievements");
        }
        return response;
    }
    
    /**
     * This function is using to  Update Achievements
     * @param objAchievements
     * @return a list of object string with "Error", "No Error" and new added ID
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UpdateAchievements")
    public List<String> UpdateAchievements(Achievements objAchievements) {
        
        List<String> response = new ArrayList<String>();
        try
        {
            DataAccessInterface objDAInterface = new AchievementsAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            response = objADBridge.UpdateAchievements(objAchievements);
            logger.info("Achievements updated successfully, Achievements Details="+objAchievements);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating Achievements");
        	response.add("Error in updating Achievements");
        }
        return response;
    }
    
    /**
     * This function is using to Retrieves Achievements by UserID 
     * @param UserID
     * @return an instance of list of Achievements
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("Achievements/{UserID}")
    public List<Achievements> RetrieveAchievementsByUserID(@PathParam ("UserID") String UserID) {
        Achievements objOuterAchievements = new Achievements();
        List<Achievements> objListAchievements = new  ArrayList<Achievements>();
        try
        {
            objOuterAchievements.setUserID(Long.parseLong(UserID));
            objOuterAchievements.setRequestType("ByUserOnly");
            
            DataAccessInterface objDAInterface = new AchievementsAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListAchievements = objADBridge.RetriveAchievements(objOuterAchievements);
            logger.info("Achievements loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Achievements");
        }
        
        return objListAchievements;
    }
    
    /**
     * This function is using to Retrieves Achievements by UserID and date range
     * @param objOuterAchievements
     * @return an instance of list of Achievements
     */
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("RetrieveAchievementsByUserIDDate")
    public List<Achievements> RetrieveAchievementsByUserIDDate(Achievements objOuterAchievements) {
        
        List<Achievements> objListAchievements = new  ArrayList<Achievements>();
        try
        {
            objOuterAchievements.setRequestType("ByUserandDate");
            
            DataAccessInterface objDAInterface = new AchievementsAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListAchievements = objADBridge.RetriveAchievements(objOuterAchievements);
            logger.info("Achievements loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading Achievements");
        }
        
        return objListAchievements;
    }
    
     /**
     * This function is using to Retrieves users current context, Activity, location, HLC, and Emotion by UserID 
     * @param UserID
     * @return an instance of CurrentContextPacket
     */
    @GET
    @Produces("application/json")
    @Consumes("application/json")
    @Path("UserCurrentContext/{UserID}")
    public CurrentContextPacket UserCurrentContext(@PathParam ("UserID") String UserID) {
        
        CurrentContextPacket objCurrentContextPacket = new CurrentContextPacket();
        
        try
        {
            List<UserRecognizedActivity> objListUserRecognizedActivity = new ArrayList<UserRecognizedActivity>();
            UserRecognizedActivity objOuterUserRecognizedActivity = new UserRecognizedActivity();
            objOuterUserRecognizedActivity.setRequestType("LatestByUser");
            objOuterUserRecognizedActivity.setUserId(Long.parseLong(UserID));
        
            DataAccessInterface objDAInterface = new UserRecognizedActivityAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserRecognizedActivity = objADBridge.RetriveUserRecognizedActivity(objOuterUserRecognizedActivity);
            objCurrentContextPacket.setObjListUserRecognizedActivity(objListUserRecognizedActivity);
            logger.info("UserRecognizedActivity loaded successfully");
        }
        catch(Exception ex)
        { 
        	logger.info("Error in loading UserRecognizedActivity"); 
        }
        try
        {
            List<UserDetectedLocation> objListUserDetectedLocation = new ArrayList<UserDetectedLocation>();
            UserDetectedLocation objOuterUserDetectedLocation = new UserDetectedLocation();
            objOuterUserDetectedLocation.setRequestType("LatestByUser");
            objOuterUserDetectedLocation.setUserId(Long.parseLong(UserID));
        
            DataAccessInterface objDAInterface = new UserDetectedLocationAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserDetectedLocation = objADBridge.RetriveUserDetectedLocation(objOuterUserDetectedLocation);
            objCurrentContextPacket.setObjListUserDetectedLocation(objListUserDetectedLocation);
            logger.info("UserDetectedLocation loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading UserDetectedLocation");
        }
        
        try
        {
            List<UserRecognizedEmotion> objListUserRecognizedEmotion = new ArrayList<UserRecognizedEmotion>();
            UserRecognizedEmotion objOuterUserRecognizedEmotion = new UserRecognizedEmotion();
            objOuterUserRecognizedEmotion.setRequestType("LatestByUser");
            objOuterUserRecognizedEmotion.setUserId(Long.parseLong(UserID));
        
            DataAccessInterface objDAInterface = new UserRecognizedEmotionAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserRecognizedEmotion = objADBridge.RetriveUserRecognizedEmotion(objOuterUserRecognizedEmotion);
            objCurrentContextPacket.setObjListUserRecognizedEmotion(objListUserRecognizedEmotion);
            logger.info("UserRecognizedEmotion loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading UserRecognizedEmotion");
        }
        
        try
        {
            List<UserRecognizedHLC> objListUserRecognizedHLC = new ArrayList<UserRecognizedHLC>();
            UserRecognizedHLC objOuterUserRecognizedHLC = new UserRecognizedHLC();
            objOuterUserRecognizedHLC.setRequestType("LatestByUser");
            objOuterUserRecognizedHLC.setUserId(Long.parseLong(UserID));
        
            DataAccessInterface objDAInterface = new UserRecognizedHLCAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListUserRecognizedHLC = objADBridge.RetriveUserRecognizedHLC(objOuterUserRecognizedHLC);
            objCurrentContextPacket.setObjListUserRecognizedHLC(objListUserRecognizedHLC);
            logger.info("UserRecognizedHLC loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading UserRecognizedHLC");
        }
        
         try
        {
            List<FoodLog> objListFoodLog = new ArrayList<FoodLog>();
            FoodLog objOuterFoodLog = new FoodLog();
            objOuterFoodLog.setRequestType("LatestByUser");
            objOuterFoodLog.setUserId(Long.parseLong(UserID));
        
            DataAccessInterface objDAInterface = new FoodLogAdapter();
            AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
            objListFoodLog = objADBridge.RetriveFoodLog(objOuterFoodLog);
            objCurrentContextPacket.setObjListFoodLog(objListFoodLog);
            logger.info("FoodLog loaded successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in loading FoodLog");
        }
         
        return objCurrentContextPacket;
    }
    
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/HLCReasoner/AbstractReasoner.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.HLCReasoner;

import mm.icl.hlc.OntologyTools.NutritionContext;
import mm.icl.hlc.OntologyTools.PhysicalActivityContext;
/**
 * Abstract Reasoner contains all Function required by Reasoners
 * for reasoning purpose. It provides Most Common methods for 
 * re-use purpose by implementing Pattern
 * 
 * @author <NAME>
 * @version 2.5
 * @since 2016-10-28
 */
public abstract class AbstractReasoner {
	
	public abstract PhysicalActivityContext inferHlc(PhysicalActivityContext unclassified);
	public abstract NutritionContext inferHlc(NutritionContext unclassified);
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/SCLResponse.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author <NAME>
 */
//@Entity
public class SCLResponse {
//    private static final long serialVersionUID = 1L;
//    @Id
//    @GeneratedValue(strategy = GenerationType.AUTO)
//    private Long id;
    
    private List<String> result = new ArrayList<String>();
    
//    public Long getId() {
//        return id;
//    }
//
//    public void setId(Long id) {
//        this.id = id;
//    }

//    @Override
//    public int hashCode() {
//        int hash = 0;
//        hash += (id != null ? id.hashCode() : 0);
//        return hash;
//    }

//    @Override
//    public boolean equals(Object object) {
//        // TODO: Warning - this method won't work in the case the id fields are not set
//        if (!(object instanceof SCLResponse)) {
//            return false;
//        }
//        SCLResponse other = (SCLResponse) object;
//        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
//            return false;
//        }
//        return true;
//    }

//    @Override
//    public String toString() {
//        return "org.uclab.mm.datamodel.sc.SCLResponse[ id=" + id + " ]";
//    }

    /**
     * @return the result
     */
    public List<String> getResult() {
        return result;
    }

    /**
     * @param result the result to set
     */
    public void setResult(List<String> result) {
        this.result = result;
    }
    
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/test/java/org/uclab/mm/datamodel/sl/dataadapter/testcases/RecommendationFeedbackAdapterTest.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sl.dataadapter.testcases;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.uclab.mm.datamodel.AbstractDataBridge;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.DatabaseStorage;
import org.uclab.mm.datamodel.sl.RecommendationFeedback;
import org.uclab.mm.datamodel.sl.dataadapter.RecommendationFeedbackAdapter;

/**
 * This is a class for testing the insertion, fetching, and update of RecommendationFeedback
 * @author <NAME>
 *
 */
public class RecommendationFeedbackAdapterTest {

	/**
	 * This is function for testing the insertion, fetching, and update of RecommendationFeedback 
	 */
	@Test
	public void test() {
		/* Preparing input object for insertion*/
		RecommendationFeedback objOuterRecommendationFeedback = new RecommendationFeedback();
		RecommendationFeedback objInnerRecommendationFeedback = new RecommendationFeedback();
		List<RecommendationFeedback> objListRecommendationFeedback = new  ArrayList<RecommendationFeedback>();
		
		objOuterRecommendationFeedback.setUserID(2L);
		objOuterRecommendationFeedback.setRecommendationID(11179L);
		objOuterRecommendationFeedback.setRate(1);
		objOuterRecommendationFeedback.setReason("I like it");
		objOuterRecommendationFeedback.setFeedbackDate("2016 12 12 02:30:01");
	
		/* Testing of insertion function*/
		 DataAccessInterface objDAInterface = new RecommendationFeedbackAdapter();
         AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
         List<String> lstResponse = objADBridge.SaveRecommendationFeedback(objOuterRecommendationFeedback);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerRecommendationFeedback.setUserID(2L);
        	 objInnerRecommendationFeedback.setRequestType("ByUserID");
        	 DataAccessInterface objDAInterfaceRetrieval = new RecommendationFeedbackAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListRecommendationFeedback = objADBridgeRetrieval.RetriveRecommendationFeedback(objInnerRecommendationFeedback);
        	 objInnerRecommendationFeedback = objListRecommendationFeedback.get(0);
         }
         
         assertEquals(objOuterRecommendationFeedback.getReason(), objInnerRecommendationFeedback.getReason());
         
         /* Testing of Update function*/
         objInnerRecommendationFeedback.setReason("I like it updated");
         objInnerRecommendationFeedback.setFeedbackDate("2016 12 12 02:30:01");
         DataAccessInterface objDAInterfaceUpdate = new RecommendationFeedbackAdapter();
         AbstractDataBridge objADBridgeUpdate = new DatabaseStorage(objDAInterfaceUpdate);
         lstResponse = objADBridgeUpdate.UpdateRecommendationFeedback(objInnerRecommendationFeedback);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerRecommendationFeedback.setUserID(2L);
        	 objInnerRecommendationFeedback.setRequestType("ByUserID");
        	 DataAccessInterface objDAInterfaceRetrieval = new RecommendationFeedbackAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListRecommendationFeedback = objADBridgeRetrieval.RetriveRecommendationFeedback(objInnerRecommendationFeedback);
        	 objInnerRecommendationFeedback = objListRecommendationFeedback.get(0);
         }
         
         assertEquals(objInnerRecommendationFeedback.getReason(), "I like it updated");
	}

}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/framework/recbuilder/RecBuilderPacket.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.framework.recbuilder;

import java.util.List;

import org.uclab.scl.datamodel.FiredRule;
import org.uclab.scl.datamodel.RecommendationIngredients;
import org.uclab.scl.framework.AbstractRecBuilderPacket;

public class RecBuilderPacket extends AbstractRecBuilderPacket<RecommendationIngredients, List<FiredRule>, String> {
  
  /**
   * prepares and returns recommendation input
   * <p>
   * 
   * @return RecommendationIngredients
   */
  @Override
  public RecommendationIngredients getRecommendationInput(){
    return this.recommendationInput;
  }
  
  /**
   * sets recommendation input
   * <p>
   * 
   * @param RecommendationIngredients
   * @return void
   */
  @Override
  public void setRecommendationInput(RecommendationIngredients recommendationInput){
    this.recommendationInput = recommendationInput;
  }
  
  /**
   * returns recommendation output
   * <p>
   * 
   * @return List<FiredRule>
   */
  @Override
  public List<FiredRule> getRecommendationOutput(){
    return this.recommendationOutput;
  }
  
  /**
   * sets recommendation output
   * <p>
   * 
   * @return void
   */
  @Override
  public void setRecommendationOutput(List<FiredRule> recommendationOutput){
    this.recommendationOutput = recommendationOutput;
  }
  
  /**
   * returns recommendation facts
   * <p>
   * 
   * @return String
   */
  @Override
  public String getRecommendationFacts(){
    return this.recommendationFacts;
  }
  
  /**
   * sets recommendation facts
   * <p>
   * 
   * @return void
   */
  @Override
  public void setRecommendationFacts(String recommendationFacts){
    this.recommendationFacts = recommendationFacts;
  }
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/dc/dataadapter/UserDisabilitiesAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.dc.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.dc.UserDisabilities;
import org.uclab.mm.datamodel.dc.Users;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This is UserDisabilitiesAdapter class which implements the Data Access Interface for CRUD operations
 * @author <NAME>
 */
public class UserDisabilitiesAdapter implements DataAccessInterface {

    private Connection objConn;
    
    private static final Logger logger = LoggerFactory.getLogger(UserDisabilitiesAdapter.class);
    
    public UserDisabilitiesAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving UserDisabilities. 
     * @param objUserDisabilities
     * @return List of String
     */
    @Override
    public List<String> Save(Object objUserDisabilities) {
        UserDisabilities objInnerUserDisabilities = new UserDisabilities();
        objInnerUserDisabilities =  (UserDisabilities) objUserDisabilities;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_UserDisabilities(?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserID", objInnerUserDisabilities.getUserID());
            objCallableStatement.setInt("DisabilityID", objInnerUserDisabilities.getDisabilityID());
            objCallableStatement.setInt("StatusID", objInnerUserDisabilities.getStatusID());
            
            objCallableStatement.registerOutParameter("UserDisabilityID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intUserDisabilityID = objCallableStatement.getLong("UserDisabilityID");
            objDbResponse.add(String.valueOf(intUserDisabilityID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("User Disabilities saved successfully, User Disabilities Details="+objUserDisabilities);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding User Disabilities");
        	objDbResponse.add("Error in adding User Disabilities");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for updating UserDisabilities. 
     * @param objUserDisabilities
     * @return List of String
     */
    @Override
    public List<String> Update(Object objUserDisabilities) {
        UserDisabilities objInnerUserDisabilities = new UserDisabilities();
        objInnerUserDisabilities =  (UserDisabilities) objUserDisabilities;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_UserDisabilities(?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserDisabilityID", objInnerUserDisabilities.getUserDisabilityID());
            objCallableStatement.setLong("UserID", objInnerUserDisabilities.getUserID());
            objCallableStatement.setInt("DisabilityID", objInnerUserDisabilities.getDisabilityID());
            objCallableStatement.setInt("StatusID", objInnerUserDisabilities.getStatusID());
            
            objCallableStatement.execute();
            
            Long intUserDisabilityID = objInnerUserDisabilities.getUserDisabilityID();
            objDbResponse.add(String.valueOf(intUserDisabilityID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("User Disabilities updated successfully, User Details="+objUserDisabilities);
        }
        catch (Exception e)
        {
        	logger.info("Error in updated User Disabilities");
        	objDbResponse.add("Error in updated User Disabilities");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for retrieving UserDisabilities. 
     * @param objUserDisabilities
     * @return List of UserDisabilities
     */
    @Override
    public List<UserDisabilities> RetriveData(Object objUserDisabilities) {
        UserDisabilities objOuterUserDisabilities = new UserDisabilities();
        List<UserDisabilities> objListInnerUserDisabilities = new ArrayList<UserDisabilities>();
        objOuterUserDisabilities =  (UserDisabilities) objUserDisabilities;
        
        try
        {
            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UserDisabilitiesByUserID(?)}");
            objCallableStatement.setLong("UserID", objOuterUserDisabilities.getUserID());
            ResultSet objResultSet = objCallableStatement.executeQuery();
            while(objResultSet.next())
            {
                UserDisabilities objInnerUserDisabilities = new UserDisabilities();
                objInnerUserDisabilities.setUserDisabilityID(objResultSet.getLong("UserDisabilityID"));
                objInnerUserDisabilities.setUserID(objResultSet.getLong("UserID"));
                objInnerUserDisabilities.setDisabilityID(objResultSet.getInt("DisabilityID"));
                objInnerUserDisabilities.setStatusID(objResultSet.getInt("StatusID"));
                
                objInnerUserDisabilities.setDisabilityDescription(objResultSet.getString("DisabilityDescription"));
                objInnerUserDisabilities.setStatusDescription(objResultSet.getString("StatusDescription"));
                
                objListInnerUserDisabilities.add(objInnerUserDisabilities);
            }
            objConn.close();
            logger.info("User Disabilities loaded successfully, User Details=");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading User Disabilities");
        }   
        return objListInnerUserDisabilities;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet."); 
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/test/TestRetrieveLLC.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.test;

import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;

import mm.icl.hlc.ContextOntologyManager.ContextHandler;
import mm.icl.hlc.ContextOntologyManager.ContextOntologyManager;
import mm.icl.hlc.OntologyTools.LowLevelContext;



public class TestRetrieveLLC {

	static final String directory ="E:\\ICL_LOG\\TDB";        
	
/*ACTIVITY EMOTION LOCATION FOOD*/	
	
	static final String sparqlQueryLlc = 
			"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> "
			+ "PREFIX owl: <http://www.w3.org/2002/07/owl#> "
			+ "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> "
			+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "
			+ "PREFIX icl3: <http://www.miningminds.re.kr/icl/context/context-v3.owl#> " //    context-v3-0  context-v2-5  change icl2 icl3
			+ "SELECT ?llc "   //?llc         (COUNT(DISTINCT ?llc) AS ?count)
			+ "WHERE { "

			+ "{?llc rdf:type ?c. "
			+ "?c rdfs:subClassOf ?type . "                              
			+ "?type rdfs:subClassOf icl3:LowLevelContext.} "            // change icl2 icl3


			
			+ "UNION {?llc rdf:type ?c. "
			+ "?c rdfs:subClassOf ?type . "                              
			+ "?type rdfs:subClassOf ?type1 . "                          			
			+ "?type1 rdfs:subClassOf icl3:LowLevelContext.} "            // change icl2 icl3
		+ "}";



	public static void main(String[] args) {
		 long llc_retr_start = System.currentTimeMillis();	
		ContextOntologyManager mng = new ContextOntologyManager(directory);
		
		if(mng.correctInitialization()) {
			
			List<LowLevelContext> llcList = (List<LowLevelContext>)(List<?>) ContextHandler.retrieveContextInstancesMatchingSparqlQuery(sparqlQueryLlc);
			
			Iterator<LowLevelContext> it = llcList.iterator();
			
			while(it.hasNext()) {
				
				System.out.println("------------------------");
				
				LowLevelContext inst = it.next();

			inst.getCtxModel().write(System.out, "Turtle");
			
		}
			
			long elapsed = System.currentTimeMillis() - llc_retr_start;
			DateFormat df = new SimpleDateFormat("HH 'hours', mm 'mins,' ss 'seconds', SSS  'milliseconds'");
			df.setTimeZone(TimeZone.getTimeZone("GMT+0"));
			System.out.println("Time taken to retrieve LLC" + df.format(new Date(elapsed)));
		
	}
	else  {
		System.out.println("No LLC Exists First Add LLC by Running _________");
	}
	
}}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/DataAccessInterface.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel;

import java.util.List;

/**
 *
 * @author Taqdir
 */
public interface DataAccessInterface {
    /**
     * This is interface for accessing database with all CRUD operations
     * @param <T> T is any entity persistent object.
     * @param objEntity 
     * @return Returns list of string indicating status of the storage.
     */
	
	/**
	 * This is Save interface for insertion data
	 * @param objEntity
	 * @return List of String
	 */
    public <T> List<String> Save(T objEntity);
    
    /**
	 * This is Update interface for editing data
	 * @param objEntity
	 * @return List of String
	 */
    public <T> List<String> Update(T objEntity);
    
    /**
	 * This is RetrieveData interface for fetching data
	 * @param objEntity
	 * @return List of any entity
	 */
    public <T> List<T> RetriveData(T objEntity);
    
    /**
	 * This is Delete interface for deleting data
	 * @param objEntity
	 * @return List of any entity
	 */
    public <T> List<T> Delete(T objEntity);
    
    /**
	 * This is ConfigureAdapter interface for making connection with database
	 * @param objConf
	 */
    public <T> void ConfigureAdapter(T objConf);
    
    
}


<|start_filename|>data-curation-layer/data-persistence/DPServer.js<|end_filename|>


/**
 * @author <NAME>
 * @since 2016.11.21
 * @version 0.1
 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at

 *   http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


//DPServer.js - nodejs server for Datapersistence

/**
 * @example
 * Usage:
 * 	node DPServer.js
 */

/**
 * @description Run all of the modules.
 * @description If local file size is going to enough to store, then start sendHDFS module.
 */

//modules in node_modules.
var express		=require('express');
var bodyParser  =require('body-parser');
var requestify  =require('requestify');
var util = require('util');
var nodeProcess = require('process');
var fs = require('fs');

//modules in local.
var manu = require('./DataManufacture');
var fileio = require('./LocalFileManagement');
var store = require('./sendHDFS');
var config = require('./config.json');

//public value
var cnt;
var port = config.port;
/*Server initialization***********************************************************************************************/
var app	=express();
app.use(bodyParser.json());
var urlencodedParser = bodyParser.urlencoded({ extended: true })
/*Server initialization***********************************************************************************************/     

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
//Post request.
app.post('/saveData', urlencodedParser,  function (req,res)
{
	var result = manu.dmf(req); //data sorting
    	cnt = fileio.lfm(result[0], result[1], result[2]);
	if(cnt != -1)
	{
		console.log("cnt is not -1");
		store.wc(cnt);
	}
	res.json({response:0});
});

//Use the PORT environment variable
app.listen('8083', function (){
	console.log('Server is running');
});


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/HLCNotifier/HLCNotifier.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.HLCNotifier;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Scanner;
import java.util.TimeZone;

import com.hp.hpl.jena.datatypes.xsd.XSDDateTime;
import com.hp.hpl.jena.rdf.model.Literal;

import mm.hlca.TestHLCA;
import mm.icl.hlc.ContextOntologyManager.ContextHandler;
import mm.icl.hlc.OntologyTools.ContextOntology;
import mm.icl.hlc.OntologyTools.NutritionContext;
import mm.icl.hlc.OntologyTools.ClinicalContext;
import mm.icl.hlc.OntologyTools.PhysicalActivityContext;
import mm.icl.rest.RestClients;
import mm.icl.utils.FileUtil;
import mm.icl.utils.TimeUtil;
import org.apache.log4j.Logger;
/**
 * HLC Notifier: Component of HLCA which communicates the newly recognized 
 * PhysicalActivity and Nutrition instance to Data Curation Layer and persists it into the
 * Context Ontology Storage.
 * 
 * @author <NAME> and <NAME>
 * @version 2.5
 * @since 2015-10-28
 */
public class HLCNotifier {
	private static Logger logger = Logger.getLogger(HLCNotifier.class);
	TimeUtil tutil = new TimeUtil();
	/**
	 * Context Ontology which represents the Mining Minds Context Model.
	 */
	private ContextOntology ont;
	/**
	 * Constructor of a new HLC Notifier.
	 * 
	 * @param ont
	 *            Context Ontology which represents the Mining Minds Context
	 *            Model.
	 */
	
	private ContextHandler contextHandler = ContextHandler.getContextHandler();
	
	public HLCNotifier(ContextOntology ont) {
		this.ont = ont;
	}
	/**
	 * Method that receives the newly classified High Level Context instance,
	 * stores it into the Context Ontology Storage, and if the new instance
	 * belongs to a different PhysicalActivity and Nutrition Context type than the previous one,
	 * notifies Data Curation Layer about the detection of a new High Level
	 * Context.
	 * 
	 * @param newHlc
	 *            Newly classified PhysicalActivity Context instance.
	 */
	public void notify(PhysicalActivityContext newHlc) {
		if (newHlc.isValidInstanceOfHlc()) {
			PhysicalActivityContext previousHlc = contextHandler.retrievePreviousHlcAndStoreNew(newHlc);
			if (previousHlc == null || !newHlc.getCtxTypeName().equals(previousHlc.getCtxTypeName()))
				notifyDCL(newHlc.getCtxInstanceLocalName(), newHlc.getCtxTypeLocalName(),
						newHlc.getObjectPropertyValue(ont.getContextOfProp()).getLocalName(),
						newHlc.getDataPropertyValue(ont.getStartTimeProp()));
		}
	}
	/**
	 * Method that receives the newly classified Nutrition Context instance,
	 * stores it into the Context Ontology Storage, and if the new instance
	 * belongs to a different Nutrition Context type than the previous one,
	 * notifies Data Curation Layer about the detection of a new High Level
	 * Context.
	 * 
	 * @param newHlc
	 *            Newly classified Nutrition Context instance.
	 */
	public void notify(NutritionContext  newHlc) {
		if (newHlc.isValidInstanceOfHlc()) {
			NutritionContext previousHlc = contextHandler.retrievePreviousHlcAndStoreNew(newHlc);
			if (previousHlc == null || !newHlc.getCtxTypeName().equals(previousHlc.getCtxTypeName()))
				notifyDCL(newHlc.getCtxInstanceLocalName(), newHlc.getCtxTypeLocalName(),
						newHlc.getObjectPropertyValue(ont.getContextOfProp()).getLocalName(),
						newHlc.getDataPropertyValue(ont.getStartTimeProp()));
		}
	}
	/**
	 * Method that receives the newly classified Nutrition Context instance,
	 * stores it into the Context Ontology Storage, and if the new instance
	 * belongs to a different Nutrition Context type than the previous one,
	 * notifies Data Curation Layer about the detection of a new High Level
	 * Context.
	 * 
	 * @param newHlc
	 *            Newly classified Nutrition Context instance.
	 */
	public void notify(ClinicalContext  newHlc) {
		if (newHlc.isValidInstanceOfHlc()) {
			ClinicalContext previousHlc = contextHandler.retrievePreviousHlcAndStoreNew(newHlc);
			if (previousHlc == null || !newHlc.getCtxTypeName().equals(previousHlc.getCtxTypeName()))
				notifyDCL(newHlc.getCtxInstanceLocalName(), newHlc.getCtxTypeLocalName(),
						newHlc.getObjectPropertyValue(ont.getContextOfProp()).getLocalName(),
						newHlc.getDataPropertyValue(ont.getStartTimeProp()));
		}
	}
	/**
	 * Test method that applies the same business logic than notify but prints
	 * messages through the standard output stream.
	 * 
	 * @param newHlc
	 *            Newly PhysicalActivity Level Context instance.
	 */
	public void notifyTest(PhysicalActivityContext newHlc) {
		if (newHlc.isValidInstanceOfHlc()) {
			PhysicalActivityContext previousHlc = contextHandler.retrievePreviousHlcAndStoreNew(newHlc);
			if (previousHlc != null) {
				if (!newHlc.getCtxTypeName().equals(previousHlc.getCtxTypeName())) {
					logger.info("[HLC Notifier: PhysicalActivityContext: ] New instance: " + newHlc.getCtxInstanceLocalName() + " - "
							+ newHlc.getCtxTypeLocalName() + ". Previous Instance: "
							+ previousHlc.getCtxInstanceLocalName() + " - " + previousHlc.getCtxTypeLocalName()
							+ ". Notify DCL.");
/*					FileUtil.WriteHLCLog("[HLC Notifier: PhysicalActivityContext: ] New instance: " + newHlc.getCtxInstanceLocalName() + " - "
							+ newHlc.getCtxTypeLocalName() + ". Previous Instance: "
							+ previousHlc.getCtxInstanceLocalName() + " - " + previousHlc.getCtxTypeLocalName()
							+ ". Notify DCL.");
					notifyDCL(newHlc.getCtxInstanceLocalName(), newHlc.getCtxTypeLocalName(),
							newHlc.getObjectPropertyValue(ont.getContextOfProp()).getLocalName(),
							newHlc.getDataPropertyValue(ont.getStartTimeProp()));
*/				}
				else{
/*					FileUtil.WriteHLCLog("[HLC Notifier: PhysicalActivityContext: ] New instance: " + newHlc.getCtxInstanceLocalName() + " - "
							+ newHlc.getCtxTypeLocalName() + ". Previous Instance: "
							+ previousHlc.getCtxInstanceLocalName() + " - " + previousHlc.getCtxTypeLocalName()
							+ ". Do not notify DCL.");
*/					logger.info("[HLC Notifier: PhysicalActivityContext: ] New instance: " + newHlc.getCtxInstanceLocalName() + " - "
							+ newHlc.getCtxTypeLocalName() + ". Previous Instance: "
							+ previousHlc.getCtxInstanceLocalName() + " - " + previousHlc.getCtxTypeLocalName()
							+ ". Do not notify DCL.");
				}
			}
			else {
				logger.info("[HLC Notifier: PhysicalActivityContext: ] New instance: " + newHlc.getCtxInstanceLocalName() + " - "
						+ newHlc.getCtxTypeLocalName() + ". Previous Instance: none" + ". Notify DCL.");
/*				FileUtil.WriteHLCLog("[HLC Notifier: PhysicalActivityContext: ] New instance: " + newHlc.getCtxInstanceLocalName() + " - "
						+ newHlc.getCtxTypeLocalName() + ". Previous Instance: none" + ". Notify DCL.");
				notifyDCL(newHlc.getCtxInstanceLocalName(), newHlc.getCtxTypeLocalName(),
						newHlc.getObjectPropertyValue(ont.getContextOfProp()).getLocalName(),
						newHlc.getDataPropertyValue(ont.getStartTimeProp()));
*/			}
		}
		else{
			logger.info("[HLC Notifier: PhysicalActivityContext: ] New High Level Context Instance is not valid.");
//			FileUtil.WriteHLCLog("[HLC Notifier: PhysicalActivityContext: ] New High Level Context Instance is not valid.");
		}
	}
	/**
	 * Test method that applies the same business logic than notify but prints
	 * messages through the standard output stream.
	 * 
	 * @param newHlc
	 *            Newly Nutrition Context instance.
	 */
	public void notifyTest (NutritionContext newHlc) {
		if (newHlc.isValidInstanceOfHlc()) {
			NutritionContext previousHlc = contextHandler.retrievePreviousHlcAndStoreNew(newHlc);
			if (previousHlc != null) {
				if (!newHlc.getCtxTypeName().equals(previousHlc.getCtxTypeName())) {
					logger.info("[HLC Notifier: NutritionContext: ] New instance: " + newHlc.getCtxInstanceLocalName() + " - "
							+ newHlc.getCtxTypeLocalName() + ". Previous Instance: "
							+ previousHlc.getCtxInstanceLocalName() + " - " + previousHlc.getCtxTypeLocalName()
							+ ". Notify DCL.");
/*					FileUtil.WriteHLCLog("[HLC Notifier: NutritionContext: ] New instance: " + newHlc.getCtxInstanceLocalName() + " - "
							+ newHlc.getCtxTypeLocalName() + ". Previous Instance: "
							+ previousHlc.getCtxInstanceLocalName() + " - " + previousHlc.getCtxTypeLocalName()
							+ ". Notify DCL.");
					notifyDCL(newHlc.getCtxInstanceLocalName(), newHlc.getCtxTypeLocalName(),
							newHlc.getObjectPropertyValue(ont.getContextOfProp()).getLocalName(),
							newHlc.getDataPropertyValue(ont.getStartTimeProp()));
*/				}
				else{
/*					FileUtil.WriteHLCLog("[HLC Notifie: NutritionContext: r] New instance: " + newHlc.getCtxInstanceLocalName() + " - "
							+ newHlc.getCtxTypeLocalName() + ". Previous Instance: "
							+ previousHlc.getCtxInstanceLocalName() + " - " + previousHlc.getCtxTypeLocalName()
							+ ". Do not notify DCL.");
*/					logger.info("[HLC Notifier: NutritionContext: ] New instance: " + newHlc.getCtxInstanceLocalName() + " - "
							+ newHlc.getCtxTypeLocalName() + ". Previous Instance: "
							+ previousHlc.getCtxInstanceLocalName() + " - " + previousHlc.getCtxTypeLocalName()
							+ ". Do not notify DCL.");
				}
			}
			else {
				logger.info("[HLC Notifier: NutritionContext: ] New instance: " + newHlc.getCtxInstanceLocalName() + " - "
						+ newHlc.getCtxTypeLocalName() + ". Previous Instance: none" + ". Notify DCL.");
/*				FileUtil.WriteHLCLog("[HLC Notifier: NutritionContext: ] New instance: " + newHlc.getCtxInstanceLocalName() + " - "
						+ newHlc.getCtxTypeLocalName() + ". Previous Instance: none" + ". Notify DCL.");
				notifyDCL(newHlc.getCtxInstanceLocalName(), newHlc.getCtxTypeLocalName(),
						newHlc.getObjectPropertyValue(ont.getContextOfProp()).getLocalName(),
						newHlc.getDataPropertyValue(ont.getStartTimeProp()));
*/			}
		}
		else{
			logger.info("[HLC Notifier: NutritionContext: ] New Nutrition Context Instance is not valid.");
//			FileUtil.WriteHLCLog("[HLC Notifier: NutritionContext: ] New Nutrition Context Instance is not valid.");
		}
	}
	/**
	 * Test method that applies the same business logic than notify but prints
	 * messages through the standard output stream.
	 * 
	 * @param newHlc
	 *            Newly Nutrition Context instance.
	 */
	public void notifyTest (ClinicalContext newHlc) {
		if (newHlc.isValidInstanceOfHlc()) {
			ClinicalContext previousHlc = contextHandler.retrievePreviousHlcAndStoreNew(newHlc);
			if (previousHlc != null) {
				if (!newHlc.getCtxTypeName().equals(previousHlc.getCtxTypeName())) {
					logger.info("[HLC Notifier: ClinicalContext: ] New instance: " + newHlc.getCtxInstanceLocalName() + " - "
							+ newHlc.getCtxTypeLocalName() + ". Previous Instance: "
							+ previousHlc.getCtxInstanceLocalName() + " - " + previousHlc.getCtxTypeLocalName()
							+ ". Notify DCL.");
/*					FileUtil.WriteHLCLog("[HLC Notifier: NutritionContext: ] New instance: " + newHlc.getCtxInstanceLocalName() + " - "
							+ newHlc.getCtxTypeLocalName() + ". Previous Instance: "
							+ previousHlc.getCtxInstanceLocalName() + " - " + previousHlc.getCtxTypeLocalName()
							+ ". Notify DCL.");
					notifyDCL(newHlc.getCtxInstanceLocalName(), newHlc.getCtxTypeLocalName(),
							newHlc.getObjectPropertyValue(ont.getContextOfProp()).getLocalName(),
							newHlc.getDataPropertyValue(ont.getStartTimeProp()));
*/				}
				else{
/*					FileUtil.WriteHLCLog("[HLC Notifie: NutritionContext: r] New instance: " + newHlc.getCtxInstanceLocalName() + " - "
							+ newHlc.getCtxTypeLocalName() + ". Previous Instance: "
							+ previousHlc.getCtxInstanceLocalName() + " - " + previousHlc.getCtxTypeLocalName()
							+ ". Do not notify DCL.");
*/					logger.info("[HLC Notifier: ClinicalContext: ] New instance: " + newHlc.getCtxInstanceLocalName() + " - "
							+ newHlc.getCtxTypeLocalName() + ". Previous Instance: "
							+ previousHlc.getCtxInstanceLocalName() + " - " + previousHlc.getCtxTypeLocalName()
							+ ". Do not notify DCL.");
				}
			}
			else {
				logger.info("[HLC Notifier: ClinicalContext: ] New instance: " + newHlc.getCtxInstanceLocalName() + " - "
						+ newHlc.getCtxTypeLocalName() + ". Previous Instance: none" + ". Notify DCL.");
/*				FileUtil.WriteHLCLog("[HLC Notifier: NutritionContext: ] New instance: " + newHlc.getCtxInstanceLocalName() + " - "
						+ newHlc.getCtxTypeLocalName() + ". Previous Instance: none" + ". Notify DCL.");
				notifyDCL(newHlc.getCtxInstanceLocalName(), newHlc.getCtxTypeLocalName(),
						newHlc.getObjectPropertyValue(ont.getContextOfProp()).getLocalName(),
						newHlc.getDataPropertyValue(ont.getStartTimeProp()));
*/			}
		}
		else{
			logger.info("[HLC Notifier: ClinicalContext: ] New Clinical Context Instance is not valid.");
//			FileUtil.WriteHLCLog("[HLC Notifier: ClinicalContext: ] New Clinical Context Instance is not valid.");
		}
	}	
	/**
	 * Method to notify Data Curation Layer about the detection of a new 
	 * PhysicalActivity and Nutrition Context.
	 * 
	 * @param id
	 * @param label
	 * @param user
	 * @param timestamp
	 */
	private void notifyDCL(String id, String label, String user, Literal timestamp) {
		TimeUtil t = new TimeUtil();
		try {
			RestClients.sendDemo("no", "no", "no", label, t.parseCal(((XSDDateTime) timestamp.getValue()).asCalendar()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		Scanner scan = null;
		scan = new Scanner(user).useDelimiter("_|\n");;
		String userID = scan.next();
		userID = scan.next();
		Calendar dateStart = ((XSDDateTime) timestamp.getValue()).asCalendar();
		String timestampS = tutil.parseCal(dateStart);

//		FileUtil.WriteHLCLog("[HLC Notifier] DCL Notification Message: " + id + ", " + userID + ", " + user + ", " + timestampS);
		logger.info(
				"[HLC Notifier] DCL Notification Message: " + id + ", " + label + ", " + userID + ", " + timestampS);
		try {
			logger.info("********---------------------*******************************------------------********************");
			logger.info(label);
			logger.info("rest hlc of label "+ label + " " + RestClients.addUserRecognizedHLC(35l, label, timestampS));
			logger.info("********---------------------*******************************------------------********************");
		} catch (Exception e) {
			logger.error("Error while Notifying HLC.  Message: " + e.getMessage());
			e.printStackTrace();
		}
	}
	public ContextHandler getContextHandler() {
		return contextHandler;
	}
	public void setContextHandler(ContextHandler contextHandler) {
		this.contextHandler = contextHandler;
	}
}

<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/communication/DCPhysiologicalFactorsWSClient.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.communication;

import java.util.List;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.uclab.scl.datamodel.PhysiologicalFactors;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
/**
 * @version MM v2.5
 * @author Afzal
 *
 */
public class DCPhysiologicalFactorsWSClient extends AbstractRestClient<List<PhysiologicalFactors>, String> {
  
  /**
   * Instantiates PhysiologicalFactors Webservice client
   * 
   * <p>
   * @param baseURI
   */
  public DCPhysiologicalFactorsWSClient(String baseURI) {
    super(baseURI);
  }
  
  /**
   * 
   * <p>
   * @param resource URI
   * @return PhysiologicalFactors
   */
  @Override
  public List<PhysiologicalFactors> GetData(String getResourceURI) {
    ClientConfig config = new DefaultClientConfig();
    config.getClasses().add(JacksonJsonProvider.class);
    Client client = Client.create(config);
    WebResource service = client.resource(UriBuilder.fromUri(baseURI).build());
    List<PhysiologicalFactors> physiologicalFactors = 
        service.path(getResourceURI).accept(MediaType.APPLICATION_JSON).get(new GenericType<List<PhysiologicalFactors>>() {});
    if (physiologicalFactors.size() > 0)
      return physiologicalFactors;
    else
      return null;
  }
  /**
   * 
   * <p>
   * @param resource URI
   * @param PhysiologicalFactors list
   * @return String
   */
  @Override
  public String PostData(String postResourceURI, List<PhysiologicalFactors> postedResource) {
    throw new UnsupportedOperationException("Not supported yet.");
  }

}


<|start_filename|>knowledge-curation-layer/DDKAT/target/DDKAT/WEB-INF/views/dataselector.jsp<|end_filename|>
<%@ page contentType="text/html; charset=UTF-8" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    

<HTML><HEAD><TITLE>Data Driven Knowledge Acquisition</TITLE>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="js/jquery.tree-multiselect.min.js" ></script>
<script type="text/javascript" src="js/bootstrap.min.js" ></script> 
<link href="css/jquery.tree-multiselect.css" rel="stylesheet" type="text/css">
<link href="css/ddka-interface.css" rel="stylesheet" type="text/css">
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"> 

<script language="javascript">

$(document).ready(function(){
	
	document.getElementById("loadselectedfeatures_btn").disabled = true;
	document.getElementById("visualizefeaturesscorecard_btn").disabled = true;
	document.getElementById("preprocessorloader_btn").disabled = true;
	
	$("#loadschema_btn").click(function () {

	jQuery.support.cors = true;
		
	$.ajax({
	    type : "GET",
		url : "http://private-b0977-schema5.apiary-mock.com/schema",
        dataType: "json",
       
	    success : function(data) {
	        var schematitle='<b>Schema Title : <font size="4" color="#004584">'+data.schema_name+ '</font></b><br><br>(Note: Please select the features to build the feature model) ';
		   	$('#schemaname').append(schematitle);
		   	var dataindex=1;
		   	var tableindex=0;
	       	while(tableindex < data.schema_tables.length ){
	       		var columnindex=0;
	       		while(columnindex < data.schema_tables[tableindex].table_metadata.length ){
	       			var treenodehtml='<option value="' + data.schema_tables[tableindex].table_name.toUpperCase()+'___'+data.schema_tables[tableindex].table_metadata[columnindex].column_name + '" data-section="' + data.schema_name +'/'+ data.schema_tables[tableindex].table_name.toUpperCase() + '" data-index="' + dataindex + '">' + data.schema_tables[tableindex].table_metadata[columnindex].column_name + ' ' + data.schema_tables[tableindex].table_metadata[columnindex].datatype + '</option>';
	       			$('#schematree').append(treenodehtml);
	       	   		columnindex = columnindex + 1;
	    	   		dataindex = dataindex + 1;
	       			}
	       		tableindex = tableindex + 1;	       	
	       		}
	       	$("#schematree").css('visibility','visible');
	       	$("#preprocessorloader_btn").css('visibility','visible');
	    	var options = { };
	    	$("select#schematree").treeMultiselect(options);
	    },
	    error: function (jqXHR, status, err) {
	    	console.log( 'something went wrong', status, err );
            if (jqXHR.status === 0) {
	                alert('Connection problem, please verify the DCL connection.');
	    	 	}
 	    	}
		}); // success or Error Ending 
	      	
		var button = document.getElementById('loadschema_btn');
		button.setAttribute('disabled', true);
	
		if(button.disabled)
	  		{
			button.style.cursor='hand';
	  		}
	  	else
	  		{
			button.style.cursor='default';
	  		}
		
		document.getElementById("loadselectedfeatures_btn").disabled = false;
		
        });
	 	
  	
    $("#loadselectedfeatures_btn").click(function () {
    	
    	$('#TextBoxesGroupDiv').empty();
    	
    	var i = 0;
    	var featurescounter=0;
    	var e = document.getElementById("schematree");
		var listLength = e.options.length;
		while(i<listLength){
			if(e.options[i].selected == true){
	  			var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + e.options[i].value); 
				newTextBoxDiv.after().html('<br/><label class="col-md-5 col-md-offset-1">'+ e.options[i].innerHTML + ' : </label>' + '<input type="text" id="textbox' + e.options[i].value + '" class="col-md-offset-1" value="">');  		  		            
		  		newTextBoxDiv.appendTo("#TextBoxesGroupDiv");
		  		featurescounter++;
				}
			i++;
			}
		
		if(featurescounter<1){
			alert("Please select Features first then click the 'Load Query Panel' button !");
			}
		else{
			document.getElementById("visualizefeaturesscorecard_btn").disabled = false;
			document.getElementById("preprocessorloader_btn").disabled = false;
			}
	    });
    
    
    $("#visualizefeaturesscorecard_btn").click(function () {
    	
		var jsonString ="";
		var j=0;
       	var queryObject = '[';
    	var absColumnName = [];
    	var tableName = '';
    	var columnName = '';
    	var tempQueryVar = '';

     	var e = document.getElementById("schematree");
 		var listLength = e.options.length;
 		
 		while(j<listLength){
 			if(e.options[j].selected == true){
 				absColumnName = (e.options[j].value).split("___");
 				tableName = absColumnName[0];
 				columnName = absColumnName[1];
 				queryObject += '{ \"table\":"'+ tableName +'", \"column\":"' + columnName + '", \"condition\":"' + $('#textbox' + e.options[j].value).val() + '"},';
 				tempQueryVar += tableName + columnName + $('#textbox' + e.options[j].value).val();
 				}
 			j++;	
 			}
		var query = queryObject.substring(0, queryObject.length-1);
		query += ']';
		
	$.ajaxSetup({
		contentType: "application/json; charset=utf-8"
		});
	
	// Send the data using post
	$.ajax({
	    url: "http://private-673d5-data11.apiary-mock.com/data?kcldataquery="+query,
	    type: 'POST',
	    success: function(data) {

	    	var emptyTemp;
	    	
	    	jsonString = "{\"unprocessed_data\": [";
    	
	    	console.log(data);
		   	var tempVar="";
	    	   			   	
			var columncounter = 0;
	    	jsonString += "[";
		   	while(columncounter < data.data_attributes.length){
		   		jsonString += "\""+data.data_attributes[columncounter].attribute_name +"\""+",";
		   		columncounter++;
		   		}
		   	jsonString = jsonString.substring(0, jsonString.length-1);
		   	jsonString += "],";		    	
	    	
	     	var rowcounter = 0;
		   	while(rowcounter < data.data_values.length){
		   		jsonString += "[";
		   		columncounter = 0;
		   		while(columncounter < data.data_attributes.length){
						tempVar = data.data_values[rowcounter][columncounter];
		   			if (tempVar==0){   
		   			    tempVar = "";
		   			 	jsonString += "\""+ data.data_values[rowcounter][columncounter] + "\",";
		   				}
		   			else{
		   				jsonString += "\""+ tempVar +"\",";
		   				}
		   			columncounter++;
			   		}
		   		jsonString = jsonString.substring(0, jsonString.length-1);
			   	jsonString += "],";
		   		rowcounter++;
		   		}
		   	jsonString = jsonString.substring(0, jsonString.length-1);
	    	jsonString += "]}";

	    	//console.log(jsonString);
	    	var filePath = "D:/DDKAResources/";
			var request = $.ajax({
				url: "featuresvisualizer?filepath="+filePath,
				type: "POST",
				data: jsonString,
				dataType: "json",
				success : function(response) {
	                var tabletitleHTML='<b><font size="4" color="#004584">Features Scorecard</font></b><br/><br/>';
				   	var tableHTML=''; 
					var headerrowHTML='<tr><td style="border-style: solid; border-width: 1px" vertical-align:middle" align="center"><font face="Times New Roman" size="3" color="#004584"><b>Feature Name</b></font></td>';
				   	headerrowHTML+='<td style="border-style: solid; border-width: 1px" vertical-align:middle" align="center"><font face="Times New Roman" size="3" color="#004584"><b>Feature Score</b></font></td>';
				   	headerrowHTML+='<td style="border-style: solid; border-width: 1px" vertical-align:middle" align="center"><font face="Times New Roman" size="3" color="#004584"><b>Relative Feature Weightage</b></font></td>';	   	
				   	headerrowHTML+='<td style="border-style: solid; border-width: 1px" vertical-align:middle" align="center"><font face="Times New Roman" size="3" color="#004584"><b>Feature Priority</b></font></td>';	   	
				   	headerrowHTML+='<td style="border-style: solid; border-width: 1px" vertical-align:middle" align="center"><font face="Times New Roman" size="3" color="#004584"><b>Feature Ranking</b></font></td></tr>';
				   	var datarowsHTML='';
				   	var rowcounter = 0;
				   	while(rowcounter < response.featureTitles.length){
				   		datarowsHTML+='<tr>';
				   		datarowsHTML+='<td style="border-style: solid; border-width: 1px; vertical-align:middle; padding-left: 7px;" width="20%" align="left"><font face="Times New Roman" size="3" color="#004584">' + response.featureTitles[rowcounter] + '</font></td>';
				   		datarowsHTML+='<td style="border-style: solid; border-width: 1px; vertical-align:middle" width="20%" align="center"><font face="Times New Roman" size="3" color="#004584">' + response.featureScores[rowcounter] + '</font></td>';		  
				   		datarowsHTML+='<td style="border-style: solid; border-width: 1px; vertical-align:middle" width="20%" align="center"><font face="Times New Roman" size="3" color="#004584">' + response.featureWeights[rowcounter] + ' %</font></td>';		  
				   		datarowsHTML+='<td style="border-style: solid; border-width: 1px; vertical-align:middle" width="20%" align="center"><font face="Times New Roman" size="3" color="#004584">' + response.featurePriorities[rowcounter] + '</font></td>';		  
				   		datarowsHTML+='<td style="border-style: solid; border-width: 1px; vertical-align:middle" width="20%" align="center"><font face="Times New Roman" size="3" color="#004584">' + (rowcounter+1) + '</font></td>';
					   	datarowsHTML+='</tr>';
				   		rowcounter++;
				   		}				    			   	
				   	tableHTML = tabletitleHTML + '<table border="2" width="100%" style="width: 70%" bordercolor="#004584">' + headerrowHTML + datarowsHTML + '</table>';
				   	document.getElementById("AttributeImportanceDiv").innerHTML = tableHTML;
				},
				error: function(e) {
					alert("error : " + e.responseText);
				}
				
	 		});		

	    	},
	        error: function(errorThrown){
	            alert(errorThrown);
	            alert("There is an error with AJAX!");
	        }        
		});
	});

  
    $("#preprocessorloader_btn").click(function () {
    	 
    	j=0;
    	var queryObject = '[';
    	var absColumnName = [];
    	var tableName = '';
    	var columnName = '';
    	var tempQueryVar = '';

     	var e = document.getElementById("schematree");
 		var listLength = e.options.length;
 		
 		while(j<listLength){
 			if(e.options[j].selected == true){
 				absColumnName = (e.options[j].value).split("___");
 				tableName = absColumnName[0];
 				columnName = absColumnName[1];
 				queryObject += '{ \"table\":"'+ tableName +'", \"column\":"' + columnName + '", \"condition\":"' + $('#textbox' + e.options[j].value).val() + '"},';
 				tempQueryVar += tableName + columnName + $('#textbox' + e.options[j].value).val();
 				}
 			j++;	
 			}
		var query = queryObject.substring(0, queryObject.length-1);
		query += ']';
		
		$("#loadingdataQuery").val(query);
		document.forms['featuremodelForm'].submit();
		
  		});
  
	});

</script>	

</HEAD>
<BODY>

<TABLE id=header cellPadding=0 style="width: 100%">
  <TBODY>
  <TR>
    <TD align="left" class="style1">
   	<img border="0" src="images/banner.jpg" height="106" /></TD>
    <TD align="right" style="width: 30%">
    <img border="0" src="images/MM_logo.png" height="106"></TD>
    </TR></TBODY></TABLE>
<TABLE cellPadding=0>
  <TBODY>
  <TR>
    <TD id=tran1></TD></TR>
  <TR>
    <TD id=tran2 height="171"></TD></TR></TBODY></TABLE>
<TABLE id=menubar cellPadding=0>
  <TBODY>
  <TR>
    <TD>
     <TABLE style="WIDTH: 100%" cellSpacing=0 cellPadding=0 border=0>
        <TBODY>
        <TR>
          <TD align=right>
          <a href="index.jsp">
		  <img border="0" src="images/main.gif" height="21"></a>
          </TD>
		  </TR></TBODY></TABLE></TD></TR></TBODY></TABLE>
		  
		  
<TABLE id=main cellPadding=0 width="777" style="width: 100%">
  <TBODY>
  <TR>
    <TD id=leftMenu width="654" rowspan="2">
                 &nbsp;</TD>
    </TR></TBODY></TABLE>
    <TABLE align=center border=2 borderColor=#39597d cellPadding=5 cellSpacing=5 width="82%">
              <TBODY>
              <TR>
                <TD>
        <br><br>
		<div align="center">
		     	<font size="5" color="#004584"><b>Data Selector</b></font><br><br><br>
		     	<p class="bg-info"><b>For loading of dataset schema, click <font color="#004584"><i>'Load Schema'</i></font> button.</b></p>
				<br>
				
				<form id = "form" action = "#" name = "form">
	  		  	<button id="loadschema_btn" class="btn btn-primary" type="button"><span class="glyphicon glyphicon-cloud-download"></span> Load Schema</button>
	  		  	</form>
	  		  	
                </div>
                    <br/>
                    <div id="schemaname" align="center"></div>
                    <br/>
                    <select id="schematree" multiple="multiple"></select>
<br/><br/>
<div align="center">
<p class="bg-info"><b>Query Configuration Panel</b></p><br>
	<div class="row">
		<div class="col-md-2 col-md-offset-1" align="left"> <button id="loadselectedfeatures_btn" class="btn btn-primary" type="button"><span class="glyphicon glyphicon-download-alt"></span> Load Query Panel</button></div>
		<div class="col-md-7" align="left">
			<fieldset>
				<div id="TextBoxesGroupDiv" style="border: 1px #d3d3d3 solid;"><br/></div><br/><br/>	
			</fieldset>
		</div>
	</div>
</div>
<div>
</div> 
<div class="row">
		<div id="AttributeImportanceDiv" align="center" style="border: 0px #d3d3d3 solid;"><br/></div><br/>
</div>
<br/>
	<div align="center">
		<form method="POST" name='featuremodelForm' action="preprocessor">
			<button id="visualizefeaturesscorecard_btn" class="btn btn-primary" type="button"><span class="glyphicon glyphicon-search"></span> Visualize Features Scorecard</button>
			&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
			<button id="preprocessorloader_btn" class="btn btn-primary" type="button"><span class="glyphicon glyphicon-forward"></span> Data Preprocessor </button> 
  			<input type="hidden" id="loadingdataQuery" name="loadingdataQuery" />
  		</form>
	</div>
  <br/>
  <br/>
    <table align="center" style="width: 100%">
           <tr>
		<td style="width: 100%; text-align:center">
		<font size="1" color="#39597B">
        <script language="JavaScript">
            copyright = new Date();
            currentYear = copyright.getFullYear();
            document.write("�" + currentYear + "Ubiquitous Computing Lab., Dept. of Computer Engg.");
            </script></font></td>
	</tr>
	<tr>
		<td style="width: 100%; text-align:center">
		<font size="1" color="#39597B">Kyung Hee University, Korea</font></td>
	</tr>
	      
                </table>
                </TD>
    </TR></TBODY></TABLE>
 </BODY></HTML>

<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/test/java/org/uclab/mm/datamodel/ic/dataadapter/testcases/UserDetectedLocationAdapterTest.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.ic.dataadapter.testcases;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.uclab.mm.datamodel.AbstractDataBridge;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.DatabaseStorage;
import org.uclab.mm.datamodel.ic.UserDetectedLocation;
import org.uclab.mm.datamodel.ic.dataadapter.UserDetectedLocationAdapter;

/**
 * This is a class for testing the insertion, fetching, and update of UserDetectedLocation
 * @author <NAME>
 *
 */
public class UserDetectedLocationAdapterTest {

	/**
	 * This is function for testing the insertion, fetching, and update of UserDetectedLocation 
	 */
	@Test
	public void test() {
		/* Preparing input object for insertion*/
		UserDetectedLocation objOuterUserDetectedLocation = new UserDetectedLocation();
		UserDetectedLocation objInnerUserDetectedLocation = new UserDetectedLocation();
		List<UserDetectedLocation> objListUserDetectedLocation = new  ArrayList<UserDetectedLocation>();
		
		objOuterUserDetectedLocation.setUserId(2L);
		objOuterUserDetectedLocation.setLocationLabel("kor k yam");
		objOuterUserDetectedLocation.setStartTime("2016 12 12 02:30:01");
	
		/* Testing of insertion function*/
		 DataAccessInterface objDAInterface = new UserDetectedLocationAdapter();
         AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
         List<String> lstResponse = objADBridge.SaveUserDetectedLocation(objOuterUserDetectedLocation);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerUserDetectedLocation.setUserId(2L);
        	 objInnerUserDetectedLocation.setRequestType("LatestByUser");
        	 DataAccessInterface objDAInterfaceRetrieval = new UserDetectedLocationAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListUserDetectedLocation = objADBridgeRetrieval.RetriveUserDetectedLocation(objInnerUserDetectedLocation);
        	 objInnerUserDetectedLocation = objListUserDetectedLocation.get(0);
         }
         
         assertEquals(objOuterUserDetectedLocation.getLocationLabel(), objInnerUserDetectedLocation.getLocationLabel());
	}

}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/outputModel/SCLResponse.java<|end_filename|>
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.uclab.scl.outputModel;

import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.annotate.JsonTypeInfo;
import org.codehaus.jackson.annotate.JsonTypeInfo.As;
import org.codehaus.jackson.annotate.JsonTypeInfo.Id;

/**
 * 
 * @author User
 */
@JsonTypeInfo(use = Id.NAME, include = As.WRAPPER_OBJECT)
public class SCLResponse {

  List<String> result;

  public SCLResponse() {
    this.result = new ArrayList<>();
  }

  public List<String> getResult() {
    return result;
  }

  public void setResult(List<String> result) {
    this.result = result;
  }

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/llm/SituationEvent.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.llm;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author Rizvi
 */
@XmlRootElement()
public class SituationEvent implements Serializable {
    private String SituationID;
    private List<SituationConditions> ListSConditions = new ArrayList<SituationConditions>();

    /**
     * @return the SituationID
     */
    public String getSituationID() {
        return SituationID;
    }

    /**
     * @param SituationID the SituationID to set
     */
    public void setSituationID(String SituationID) {
        this.SituationID = SituationID;
    }

    /**
     * @return the ListSConditions
     */
    public List<SituationConditions> getListSConditions() {
        return ListSConditions;
    }

    /**
     * @param ListSConditions the ListSConditions to set
     */
    public void setListSConditions(List<SituationConditions> ListSConditions) {
        this.ListSConditions = ListSConditions;
    }

}



<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/test/java/org/uclab/mm/datamodel/sc/dataadapter/testcases/UserRewardsAdapterTest.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc.dataadapter.testcases;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.uclab.mm.datamodel.AbstractDataBridge;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.DatabaseStorage;
import org.uclab.mm.datamodel.sc.UserRewards;
import org.uclab.mm.datamodel.sc.dataadapter.UserRewardsAdapter;

/**
 * This is a class for testing the insertion, fetching, and update of UserRewards
 * @author <NAME>
 *
 */

public class UserRewardsAdapterTest {

	
	/**
	 * This is function for testing the insertion, fetching, and update of UserRewards 
	 */
	@Test
	public void test() {
		/* Preparing input object for insertion*/
		UserRewards objOuterUserRewards = new UserRewards();
		UserRewards objInnerUserRewards = new UserRewards();
		List<UserRewards> objListUserRewards = new  ArrayList<UserRewards>();
		
		objOuterUserRewards.setUserID(2L);
		objOuterUserRewards.setRewardPoints(4);
		objOuterUserRewards.setRewardDescription("Unit Testing Reward");
		objOuterUserRewards.setRewardDate("2016 12 12 01:30:01");
		objOuterUserRewards.setRewardTypeID(1);
	
		/* Testing of insertion function*/
		 DataAccessInterface objDAInterface = new UserRewardsAdapter();
         AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
         List<String> lstResponse = objADBridge.SaveUserRewards(objOuterUserRewards);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerUserRewards.setUserID(2L);
        	 DataAccessInterface objDAInterfaceRetrieval = new UserRewardsAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListUserRewards = objADBridgeRetrieval.RetriveUserRewards(objInnerUserRewards);
        	 objInnerUserRewards = objListUserRewards.get(0);
         }
         
         assertEquals(objOuterUserRewards.getRewardDescription(), objInnerUserRewards.getRewardDescription());
         
         /* Testing of Update function*/
         objInnerUserRewards.setRewardDescription("Unit Testing Reward Updated");
         objInnerUserRewards.setRewardDate("2016 12 12 01:30:01");
         DataAccessInterface objDAInterfaceUpdate = new UserRewardsAdapter();
         AbstractDataBridge objADBridgeUpdate = new DatabaseStorage(objDAInterfaceUpdate);
         lstResponse = objADBridgeUpdate.UpdateUserRewards(objInnerUserRewards);
         if(lstResponse.size() == 2)
         {
        	 /* Testing of fetching function*/
        	 objInnerUserRewards.setUserID(2L);
        	 DataAccessInterface objDAInterfaceRetrieval = new UserRewardsAdapter();
             AbstractDataBridge objADBridgeRetrieval = new DatabaseStorage(objDAInterfaceRetrieval);
        	 objListUserRewards = objADBridgeRetrieval.RetriveUserRewards(objInnerUserRewards);
        	 objInnerUserRewards = objListUserRewards.get(0);
         }
         
         assertEquals(objInnerUserRewards.getRewardDescription(), "Unit Testing Reward Updated");
	}

}


<|start_filename|>supporting-layer/uiux-authoring-tool/accounts/templates/accounts/register.html<|end_filename|>

{% extends "base_login.html" %}

{% block content %}

</div>

<div class="login_wrapper">
        <div class="animate form login_form">
          <section class="login_content">

              <h1>Create Account</h1>
               {% include "accounts/form.html" with form=form %}

              <div class="clearfix"></div>

              <div class="separator">
                <p class="change_link">Already a member ?
                  <a href="/accounts/login/" class="to_register"> Log in </a>
                </p>
                <div class="clearfix"></div>
                <br />

                <div>
                  <p>©2016 All Rights Reserved.UI/UX Authoring Tool</p>
                </div>
              </div>

          </section>
        </div>

{% endblock %}

<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/framework/RemoveIt.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.framework;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

public class RemoveIt {
  private static Logger LOG = LogManager.getRootLogger();

  public static void main(String[] args) throws IOException {
    BufferedReader br = null;
    
    br = new BufferedReader(new FileReader(new File("krf_knowledge_base.json")));
    
    StringBuilder sb = new StringBuilder();
    
    String line = null;
    while((line = br.readLine()) != null){
      sb.append(line.trim());
    }
    
    Map<String, List<Map<String, Object>>> rules = buildRules(sb.toString());
    LOG.debug(rules.get("rules").size());
    LOG.debug(sb.toString().replace("\"", "\\\""));
    //. LOG.debug();
    
  }
  
  public static Map<String, List<Map<String, Object>>> buildRules(String jsonRules) {
    ObjectMapper mapper = new ObjectMapper();
    Map<String, List<Map<String, Object>>> rules = null;
    try {
      rules = mapper.readValue(jsonRules, new TypeReference<Map<String, List<Map<String, Object>>>>() {});
      
    } catch (Exception e) {
      e.printStackTrace();
    }
    
    return rules;
  }

}


<|start_filename|>data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/LLMController.java<|end_filename|>
/**
 * 
 * Copyright [2016] [<NAME>]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 *  ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 */


package org.uclab.mm.dcl.llm;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
/**
 * This class is used to define the base path to access the services.
 * @author Rizvi
 *
 */

@Path("/llm")
public class LLMController {

	@Path("/")
	@GET
	public String getIt() {
		return "Plz use the following link as base url: http://localhost:8080/LLMS/sc/servicecommunicator/[service Name]";
	}
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/ic/dataadapter/UserDetectedLocationAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel.ic.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.ic.UserDetectedLocation;
import org.uclab.mm.datamodel.ic.UserRecognizedActivity;

/**
 * This is UserDetectedLocationAdapter class which implements the Data Access Interface for CRUD operations
 * @author Taqdir
 */
public class UserDetectedLocationAdapter implements DataAccessInterface{

    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(UserDetectedLocationAdapter.class);
    public UserDetectedLocationAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving UserDetectedLocation. 
     * @param objUserDetectedLocation
     * @return List of String
     */
    @Override
    public List<String> Save(Object objUserDetectedLocation) {
        UserDetectedLocation objInnerUserDetectedLocation = new UserDetectedLocation();
        objInnerUserDetectedLocation =  (UserDetectedLocation) objUserDetectedLocation;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_UserDetectedLocation(?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserID", objInnerUserDetectedLocation.getUserId());
            objCallableStatement.setString("LocationLabel", objInnerUserDetectedLocation.getLocationLabel());
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
             Date dtStartDate = sdf.parse(objInnerUserDetectedLocation.getStartTime());
            Timestamp tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);
            
            objCallableStatement.setTimestamp("StartTime", tsStartDate);
                                               
            objCallableStatement.registerOutParameter("UserDetectedLocationID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intUserDetectedLocationID = objCallableStatement.getLong("UserDetectedLocationID");
            objDbResponse.add(String.valueOf(intUserDetectedLocationID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("User Detected Location saved successfully, User Detected Location Details="+objUserDetectedLocation);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding User Detected Location");
        	objDbResponse.add("Error in adding User Detected Location");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for saving UserDetectedLocation. 
     * Not Implemented
     */
    @Override
    public <T> List<String> Update(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for retrieving UserDetectedLocation.
     * @param objUserDetectedLocation
     * @return List of UserDetectedLocation 
     */
    @Override
    public List<UserDetectedLocation> RetriveData(Object objUserDetectedLocation) {
        UserDetectedLocation objOuterUserDetectedLocation = new UserDetectedLocation();
        List<UserDetectedLocation> objListInnerUserDetectedLocation = new ArrayList<UserDetectedLocation>();
        objOuterUserDetectedLocation =  (UserDetectedLocation) objUserDetectedLocation;
        
        try
        {
            CallableStatement objCallableStatement = null;
            Timestamp tsStartDate = null;
            Timestamp tsEndDate = null;
            if(objOuterUserDetectedLocation.getRequestType() == "LatestByUser" )
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_CurrentUserDetectedLocationByUserID(?)}");
                objCallableStatement.setLong("UserID", objOuterUserDetectedLocation.getUserId());
            }
            else if(objOuterUserDetectedLocation.getRequestType() == "UserDateRange")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UserDetectedLocationByUserID(?, ?, ?)}");
                 SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
                 Date dtStartDate = sdf.parse(objOuterUserDetectedLocation.getStartTime());
                tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);

                Date dtEndDate = sdf.parse(objOuterUserDetectedLocation.getEndTime());
                tsEndDate = new Timestamp(dtEndDate.getYear(),dtEndDate.getMonth(), dtEndDate.getDate(), dtEndDate.getHours(), dtEndDate.getMinutes(),dtEndDate.getSeconds(),0);

                objCallableStatement.setLong("UserID", objOuterUserDetectedLocation.getUserId());
                objCallableStatement.setTimestamp("StartTime", tsStartDate);
                objCallableStatement.setTimestamp("EndTime", tsEndDate);
            }
            
            
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                UserDetectedLocation objInnerUserDetectedLocation = new UserDetectedLocation();
                objInnerUserDetectedLocation.setUserDetectedLocationId(objResultSet.getLong("UserDetectedLocationID"));
                objInnerUserDetectedLocation.setUserId(objResultSet.getLong("UserID"));
                objInnerUserDetectedLocation.setLocationLabel(objResultSet.getString("LocationLabel"));
                if(objResultSet.getTimestamp("StartTime") != null)
                {
                    tsStartDate = objResultSet.getTimestamp("StartTime");
                    objInnerUserDetectedLocation.setStartTime( tsStartDate.toString());
                }
                
                if(objResultSet.getTimestamp("EndTime") != null)
                {
                    tsEndDate = objResultSet.getTimestamp("EndTime");
                    objInnerUserDetectedLocation.setEndTime( tsEndDate.toString());
                }
                
                objInnerUserDetectedLocation.setDuration(objResultSet.getLong("Duration"));
                
                objListInnerUserDetectedLocation.add(objInnerUserDetectedLocation);
            }
            objConn.close();
            logger.info("User Detected Location laoded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading User Detected Location");
        }   
        return objListInnerUserDetectedLocation;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/datamodel/RecommendationIngredients.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.datamodel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.uclab.scl.Utilities.AgeGroupEnum;
import org.uclab.scl.Utilities.DisibilitiesUtility;
import org.uclab.scl.Utilities.RiskFactorFinderUtility;

/**
 * @version MM v2.5
 * @author Afzal
 *
 */
public class RecommendationIngredients {

  // private Situation situation;
  private SituationNotification sNotification;
  private User user;
  private Map<String, String> riskFactors = new HashMap<>();
  private Map<String, String> disibilities = new HashMap<>();
  private AgeGroupEnum AgeGroup;
  private List<UserSchedule> listUserSchedle = new ArrayList<UserSchedule>();
  private List<PhysiologicalFactors> physFactors = new ArrayList<PhysiologicalFactors>();

  public Map<String, String> getRiskFactors() {
    return riskFactors;
  }

  public void setRiskFactors(Map<String, String> riskFactors) {
    this.riskFactors = riskFactors;
  }

  public void setRiskFactors(List<RiskFactors> riskFactorsList) {

    RiskFactorFinderUtility rfUtility = RiskFactorFinderUtility.getRiskFactorFinderUtility();

    this.riskFactors = rfUtility.getRiskFactors(riskFactorsList);
  }

  // /**
  // * @return the situation
  // */
  // public Situation getSituation() {
  // return situation;
  // }
  //
  // /**
  // * @param situation the situation to set
  // */
  // public void setSituation(Situation situation) {
  // this.situation = situation;
  // }

  /**
   * @return the userProfile
   */
  public User getUser() {
    return user;
  }

  /**
   * @param userProfile
   *          the userProfile to set
   */
  public void setUser(User user) {
    this.user = user;
  }

  /**
   * @return the AgeGroup
   */
  public AgeGroupEnum getAgeGroup() {
    return AgeGroup;
  }

  /**
   * @param AgeGroup
   *          the AgeGroup to set
   */
  public void setAgeGroup(AgeGroupEnum AgeGroup) {
    this.AgeGroup = AgeGroup;
  }

  /**
   * @return the disibilities
   */
  public Map<String, String> getDisibilities() {
    return disibilities;
  }

  /**
   * @param disibilities
   *          the disibilities to set
   */
  public void setDisibilities(Map<String, String> disibilities) {
    this.disibilities = disibilities;
  }

  public void setDisibilities(List<Disibilities> disibilities) {
    // Risk Factors Utility

    this.disibilities = DisibilitiesUtility.getDisabilitiesMap(disibilities);

  }

  /**
   * @return the listUserSchedle
   */
  public List<UserSchedule> getUserSchedle() {
    return listUserSchedle;
  }

  /**
   * @param listUserSchedle
   *          the listUserSchedle to set
   */
  public void setUserSchedle(List<UserSchedule> listUserSchedle) {
    this.listUserSchedle = listUserSchedle;
  }

  /**
   * @return the sNotification
   */
  public SituationNotification getsNotification() {
    return sNotification;
  }

  /**
   * @param sNotification
   *          the sNotification to set
   */
  public void setsNotification(SituationNotification sNotification) {
    this.sNotification = sNotification;
  }

  /**
   * getJSONKeyValue Scope: In current status this method provide key value of
   * main data (such as User, Situation (partial values)) required for rules in
   * form of JSON This JSON is required for recommendation builder to perform
   * reasoning
   * 
   * @return Single Object of Key Value in JSON format
   */

  public String getJSONKeyValue() {
    String keyValueJSON = "{\n" + this.toString() + "\n}";
    return keyValueJSON;
  }

  @Override
  public String toString() {
    String keyValue = "";

    keyValue += sNotification.toString();
    keyValue += user.toString() + "\n";

    for (String key : riskFactors.keySet())
      keyValue += "\"" + key + "\":\"Yes\",\n";

    for (String key : disibilities.keySet())
      keyValue += "\"Disability\":\"" + key + "\",\n";

    for (PhysiologicalFactors pFactor : physFactors)
      keyValue += "\"Weight Status\":\"" + pFactor.getWeightStatus() + "\"\n";

    return keyValue;

  }

  /**
   * @return the physFactors
   */
  public List<PhysiologicalFactors> getPhysFactors() {
    return physFactors;
  }

  /**
   * @param physFactors
   *          the physFactors to set
   */
  public void setPhysFactors(List<PhysiologicalFactors> physFactors) {
    this.physFactors = physFactors;
  }
}


<|start_filename|>service-curation-layer/recommendation-interpreter/src/main/java/org/uclab/scl/communication/SLSNSTrendsWSClient.java<|end_filename|>
/**
 * Copyright [2016] [<NAME>]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.uclab.scl.communication;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.uclab.scl.interpreterdatamodel.SNSTrends;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
/**
 * @version MM v2.5
 * @author Afzal
 *
 */
public class SLSNSTrendsWSClient extends AbstractRestClient<SNSTrends, String> {
  private static Logger LOG = LogManager.getRootLogger();
  
  public SLSNSTrendsWSClient(String baseURI) {
    super(baseURI);
  }

  @Override
  public SNSTrends GetData(String GET_ResourceURI) {
    List<SNSTrends> listSNSTrends = new ArrayList<>();
    SNSTrends snsTrends = null;
    try {
      ClientConfig config = new DefaultClientConfig();
      config.getClasses().add(JacksonJsonProvider.class);
      Client client = Client.create(config);
      baseURI += GET_ResourceURI;
      WebResource service = client.resource(UriBuilder.fromUri(baseURI).build());
      listSNSTrends = service.accept(MediaType.APPLICATION_JSON).get(new GenericType<List<SNSTrends>>() {});
      if (listSNSTrends.size() > 0)
        return snsTrends = listSNSTrends.get(0);
      else
        return null;
    } catch (Exception exp) {
      LOG.error(exp.getMessage());
    }
    return snsTrends;
  }
  
  @Override
  public String PostData(String POST_ResourceURI, SNSTrends postedResource) {
    throw new UnsupportedOperationException("Not supported yet.");
  }
}


<|start_filename|>knowledge-curation-layer/i-kat/src/main/java/org/uclab/mm/kcl/edkat/service/ConclusionServiceImpl.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.kcl.edkat.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.uclab.mm.kcl.edkat.dao.ConclusionDAO;
import org.uclab.mm.kcl.edkat.dao.RuleDAOImpl;
import org.uclab.mm.kcl.edkat.datamodel.Conclusion;

/**
* This is service implementation for the Conclusion it provides implementation to 
* create, update, retrieve of Conclusion of a specific rule
 * @author  <NAME>
 * @version 1.0
 * @since   2015-08-16
 * */
public class ConclusionServiceImpl implements ConclusionService {

	private ConclusionDAO conclusionDAO;
	/**
	 * This creation of static object of logger for Condition 
	*/
	private static final Logger logger = LoggerFactory.getLogger(RuleDAOImpl.class);
	
	
	/**
	 * getter of ConclusionDAO
	*/
	public ConclusionDAO getConclusionDAO() {
		return conclusionDAO;
	}

	/**
	 * setter of ConclusionDAO
	*/
	public void setConclusionDAO(ConclusionDAO conclusionDAO) {
		this.conclusionDAO = conclusionDAO;
	}
	
	/**
	 * This function is for add new Conclusion
	 * @param objConclusion
	 * @return object of Conclusion
	*/
	@Transactional
	public Conclusion addConclusion(Conclusion objConclusion) {
		try
		{
			Conclusion objInnerConclusion = new Conclusion();
			objInnerConclusion = this.conclusionDAO.addConclusion(objConclusion);
	        logger.info("Condition saved successfully, Condition Details="+objInnerConclusion);
	        return objInnerConclusion;
		}
		catch(Exception ex)
		{
			logger.info("Error occured in saving new condition, Error Details="+ex.getMessage());
			return objConclusion;
		}
		
	}

	/**
	 *  This function is for update the existing conclusion
	 * @param objConclusion
	 * @return object of Conclusion
	*/
	@Transactional
	public Conclusion updateConclusion(Conclusion objConclusion) {
		try
		{
			Conclusion objInnerConclusion = new Conclusion();
			objInnerConclusion = this.conclusionDAO.updateConclusion(objConclusion);
	        logger.info("Condition updated successfully, Condition Details="+objInnerConclusion);
	        return objInnerConclusion;
		}
		catch(Exception ex)
		{
			logger.info("Error occured in Updating new condition, Error Details="+ex.getMessage());
			return objConclusion;
		}
	}
	
	/**
	 * This function get all Conclusion of the rules
	 * @return List of Conclusion
	*/
	public List<Conclusion> listConclusion() {
		try
		{
	        List<Conclusion> conclusionList = this.conclusionDAO.listConclusion();
	        return conclusionList;
		}
		catch(Exception ex)
		{
			logger.info("Error occured in retrieving condition list, Error Details="+ex.getMessage());
			return null;
		}
	}

	/**
	 * This function get a specific Conclusion by Conclusion id (primary key)
	 * @param id
	 * @return Conclusion
	*/
	public Conclusion getConclusionById(int id) {
		return this.conclusionDAO.getConclusionById(id);
	}

	/**
	 * This function delete a specific Conclusion by Conclusion id (primary key)
	 * @param id
	*/
	public void removeConclusion(int id) {
		this.conclusionDAO.removeConclusion(id);
		
	}

}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/LLCManager/SensoryDataRouter.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Kang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.LLCManager;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.uclab.mm.icl.LLCServer;
import org.uclab.mm.icl.MainServlet;
import org.uclab.mm.icl.data.DeviceData;
import org.uclab.mm.icl.data.KinectData;
import org.uclab.mm.icl.data.SmartphoneData;
import org.uclab.mm.icl.llc.LLCRecognizer.AudioEmotionRecognizer;
import org.uclab.mm.icl.llc.config.DeviceType;
import org.uclab.mm.icl.llc.restservices.RestServices;

import com.sun.jersey.core.util.Base64;


/**
 * Sensory Data router class. Parses and routes the raw data to corresponding user instance, 
 * ultimately to the right recognizer inside the user instance
 * @author Nailbrainz
 *
 */
public class SensoryDataRouter implements Runnable{
	private final static Logger logger = Logger.getLogger(SensoryDataRouter.class);
	
	DeviceType it;
	Object data;
	LLCServer server;
	
	/**
	 * Unique constructor of SensoryDataRouter
	 * @param it sensor type the current router is dealing with
	 * @param data Data to route to user
	 * @param server LLCServer contains the user classes, which the data will be routed
	 */
	public SensoryDataRouter(DeviceType it, Object data, LLCServer server){
		this.it = it;
		this.data = data;
		this.server = server;
	}

	/**
	 * THis function routes the data sent from server, with the method defined in each SensorType Enum. 
	 */
	@Override
	public void run() {
		// TODO Auto-generated method stub
		DeviceData d = it.parseDeviceData(data);
		User user = server.getUser(d.getUserID());
		user.fillBuffer(it, d, d.getTimeStamp());
	}
	
}


<|start_filename|>information-curation-layer/high-level-context-awareness/src/main/java/mm/icl/hlc/OntologyTools/Context.java<|end_filename|>
/**
* 
* Copyright [2016] [<NAME> & <NAME>]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under 
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
*  ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and limitations under the License.
*/
package mm.icl.hlc.OntologyTools;
import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntResource;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
/**
 * Context is the class encapsulating the OntModel associated to a context
 * instance. This is an instance of the Context class in the Context Ontology
 * which represents the Mining Minds Context Model. This class provides
 * supporting methods to facilitate the access to the Context. .
 * 
 * @author <NAME> and <NAME>
 * @version 2.5
 * @since 2015-10-28
 */
public abstract class Context implements IContext{
	/**
	 * OntModel associated to a context instance in Context Ontology.
	 */
	protected OntModel ctxModel;
	/**
	 * Name of the Context Instance.
	 */
	protected String ctxInstanceName;
	/**
	 * Name of the type of context to which the instance belongs to as described
	 * in the Context Ontology. E.g., Sitting or Standing for the category
	 * Activity of Low Level Context, and OfficeWork or Amusement for the 
	 * PhysicalActivity and Nutrition Context.
	 */
	protected String ctxTypeName;
	/**
	 * Constructor of a new Context instance.
	 * 
	 * @param ctxModel
	 *            OntModel associated to the Context instance.
	 */
	public Context(OntModel ctxModel) {
		this.ctxModel = ctxModel;
	}
	/**
	 * Method to get the OntModel associated to the Context Instance.
	 * 
	 * @return OntModel representation of the Context Instance.
	 */
	public OntModel getCtxModel() {
		return ctxModel;
	}
	/**
	 * Method to set the OntModel associated to the Context Instance.
	 * 
	 * @param ctxModel
	 *            OntModel representation of the Context Instance.
	 */
	public void setCtxModel(OntModel ctxModel) {
		this.ctxModel = ctxModel;
	}
	/**
	 * Method to get the name of the Context Instance.
	 * 
	 * @return String representing the name of the Context Instance.
	 */
	public String getCtxInstanceName() {
		return ctxInstanceName;
	}
	/**
	 * Method to set the name of the Context Instance.
	 * 
	 * @param ctxInstaceName
	 *            String representing the name of the Context Instance.
	 */
	protected void setCtxInstanceName(String ctxInstaceName) {
		this.ctxInstanceName = ctxInstaceName;
	}
	/**
	 * Method to get the type of the Context Instance, e.g., Sitting or Standing
	 * for the category Activity of Low Level Context, and OfficeWork or
	 * Amusement for the PhysicalActivity and Nutrition Context.
	 * 
	 * @return String representing the type of the Context Instance.
	 */
	public String getCtxTypeName() {
		return ctxTypeName;
	}
	/**
	 * Method to set the type of the Context Instance, e.g., Sitting or Standing
	 * for the category Activity of Low Level Context, and OfficeWork or
	 * Amusement for the PhysicalActivity and Nutrition Context.
	 * 
	 * @param ctxType
	 *            String representing the type of the Context Instance.
	 */
	protected void setCtxTypeName(String ctxType) {
		this.ctxTypeName = ctxType;
	}
	/**
	 * Method to get the local name of the Context Instance. The local name
	 * refers to the name without the ontology namespace.
	 * 
	 * @return String representing the local name of the Context Instance.
	 */
	public String getCtxInstanceLocalName() {
		String str = getCtxInstanceName();
		return str.substring(str.indexOf("#") + 1);
	}
	/**
	 * Method to get the local name of the type of the Context Instance, e.g.,
	 * Sitting or Standing for the category Activity of Low Level Context, and
	 * OfficeWork or Amusement for the PhysicalActivity and Nutrition Context. The local name refers
	 * to the name without the ontology namespace.
	 * 
	 * @return String representing the local name of the type of the Context
	 *         Instance.
	 */
	public String getCtxTypeLocalName() {
		String str = getCtxTypeName();
		return str.substring(str.indexOf("#") + 1);
	}
	/**
	 * Method to get the Individual representing the Context Instance.
	 * 
	 * @return Individual representing the Context Instance.
	 */
	public Individual getCtxIndiv() {
		return getCtxModel().getIndividual(getCtxInstanceName());
	}
	/**
	 * Method to assert the value of a data property for the Context Instance.
	 * 
	 * @param p
	 *            The data property for which the value should be asserted.
	 * @param value
	 *            Literal value of the property to be asserted.
	 */
	public void setDataPropertyValue(Property p, Literal value) {
		getCtxIndiv().setPropertyValue(p, value);
	}
	/**
	 * Method to get the value of a data property for the Context Instance.
	 * 
	 * @param p
	 *            The data property for which the value is retrieved.
	 * @return Literal value of the property.
	 */
	public Literal getDataPropertyValue(Property p) {
		RDFNode n = getCtxIndiv().getPropertyValue(p);
		if (n == null)
			return null;
		return n.asLiteral();
	}
	/**
	 * Method to get the value of an object property for the Context Instance.
	 * 
	 * @param p
	 *            The object property for which the value is retrieved.
	 * @return Resource representation of the value of the property.
	 */
	public Resource getObjectPropertyValue(Property p) {
		RDFNode n = getCtxIndiv().getPropertyValue(p);
		if (n == null)
			return null;
		return n.asResource();
	}
}


<|start_filename|>service-curation-layer/recommendation-builder/src/main/java/org/uclab/scl/outputModel/Achievement/Achievement.java<|end_filename|>
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.uclab.scl.outputModel.Achievement;

/**
 * 
 * @author User
 */
public class Achievement {

  private String achievementDate;

  private long userID;

  private String achievementValue;

  private String achievementDescription;

  private String achievementStatusDescription;

  private int achievementStatusID;

  private long achievementID;

  private String supportingLink;

  public String getAchievementDate() {
    return achievementDate;
  }

  public void setAchievementDate(String achievementDate) {
    this.achievementDate = achievementDate;
  }

  public long getUserID() {
    return userID;
  }

  public void setUserID(long userID) {
    this.userID = userID;
  }

  public String getAchievementValue() {
    return achievementValue;
  }

  public void setAchievementValue(String achievementValue) {
    this.achievementValue = achievementValue;
  }

  public String getAchievementDescription() {
    return achievementDescription;
  }

  public void setAchievementDescription(String achievementDescription) {
    this.achievementDescription = achievementDescription;
  }

  public String getAchievementStatusDescription() {
    return achievementStatusDescription;
  }

  public void setAchievementStatusDescription(
      String achievementStatusDescription) {
    this.achievementStatusDescription = achievementStatusDescription;
  }

  public int getAchievementStatusID() {
    return achievementStatusID;
  }

  public void setAchievementStatusID(int achievementStatusID) {
    this.achievementStatusID = achievementStatusID;
  }

  public long getAchievementID() {
    return achievementID;
  }

  public void setAchievementID(long achievementID) {
    this.achievementID = achievementID;
  }

  public String getSupportingLink() {
    return supportingLink;
  }

  public void setSupportingLink(String supportingLink) {
    this.supportingLink = supportingLink;
  }

  @Override
  public String toString() {
    return "ClassPojo [achievementDate = " + achievementDate + ", userID = "
        + userID + ", achievementValue = " + achievementValue
        + ", achievementDescription = " + achievementDescription
        + ", achievementStatusDescription = " + achievementStatusDescription
        + ", achievementStatusID = " + achievementStatusID
        + ", achievementID = " + achievementID + ", supportingLink = "
        + supportingLink + "]";
  }

}


<|start_filename|>knowledge-curation-layer/DDKAT/src/main/java/org/uclab/mm/kcl/ddkat/controllers/DDKAController.java<|end_filename|>
/**
* Copyright [2017] [<NAME>]
* 
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.uclab.mm.kcl.ddkat.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.uclab.mm.kcl.ddkat.algoselector.AutoAlgorithmSelector;
import org.uclab.mm.kcl.ddkat.datapreprocessor.*;
import org.uclab.mm.kcl.ddkat.dataselector.FeatureEvaluator;
import org.uclab.mm.kcl.ddkat.modellearner.ModelLearner;
import org.uclab.mm.kcl.ddkat.modeltranslator.ModelTranslator;

import weka.core.Instances;

//TODO: Auto-generated Javadoc
/**
* This class controls the tasks of data selection, data preprocessing, algorithm selection, model learning, and model translation.
*/
@Controller
public class DDKAController {
	
	/** The data instances */	
	private Instances data;
	
	/** base directory to store resource data files */
	private static final String BASE_DIR = System.getProperty("user.home") + "\\DDKAT\\resources\\";
	
	/**
	 * Method to communicate the request/response of Web interface to open the data selection view.
	 *
	 * @return the model view
	 */
	// Open the data selection interface
	@RequestMapping("/dataselectionview")	
	public ModelAndView showMessage() {
		ModelAndView mv = new ModelAndView("dataselector");
		return mv;
		}
	
	
	/**
	 * Method to communicate the request/response of Web interface for data conversion as well as its storage.
	 *
	 * @param json the data string
	 * @return the data converter class object
	 * @throws Exception the exception
	 */
	// Convert the data into CSV format and then store it into local machine.
	@RequestMapping(value="/dataconverter", method=RequestMethod.POST, produces="application/json")
	public @ResponseBody String convertData(@RequestBody String json) throws Exception {
		String confirmationStr="Data is successfully converted into CSV format and is stored at : "+ BASE_DIR +"OriginalDataSet.arff";
		new DataConverter(json.toString());
		return confirmationStr;
    	}

	
	/**
	 * Method to communicate the request/response of Web interface with FeatureEvaluator class.
	 *
	 * @param json the data string
	 * @return the feature evaluator class object
	 * @throws Exception the exception
	 */	
	// Compute the EFRS methodology
	@RequestMapping(value="/featuresvisualizer", method=RequestMethod.POST, produces="application/json")
	public @ResponseBody FeatureEvaluator evaluateFeatures(@RequestBody String json) throws Exception {
		FeatureEvaluator fe = new FeatureEvaluator(json, data);
		return fe;
	}
	
	/**
	 * Method to communicate the request/response of Web interface to open the data preprocessing view.
	 */
	// Open the data preprocessing interface
	@RequestMapping(value ="/preprocessor", method = RequestMethod.POST)
    public String preProcess(@ModelAttribute("loadingdataQuery")String query, BindingResult preprocessor, Model model) {
       
        if(preprocessor.hasErrors()){
            return "dataselector";
        }else{
        	
        	 System.out.println("\n\nQuery for Required Data : " + query);
        	 model.addAttribute("loadingdataQueryId",query);
        	 return "preprocessor";
           }
    	}
	
	
   /**
    * Method to communicate the request/response of Web interface with MissingValueHandler class.
    *
    * @return the missing value handler
    * @throws Exception the exception
    */
   // Cleaning up the data
	@RequestMapping(value = "/missingvaluehandler", method = RequestMethod.POST, produces="application/json")
	public @ResponseBody MissingValueHandler missingValueHandler() throws Exception {
		MissingValueHandler mvh = new MissingValueHandler();
		return mvh;
		}
	
	
	/**
	 * Method to communicate the request/response of Web interface with OutlierHandler class.
	 *
	 * @return the string
	 * @throws Exception the exception
	 */
	// Detecting and Removing Outliers and Extreme Values
	@RequestMapping(value="/outlierhandler", method=RequestMethod.POST, produces="application/json")
	public @ResponseBody String outlierHandler() throws Exception {
		String confirmationStr="Outliers have been successfully removed and is stored at : "+ BASE_DIR +"ProcessedDataSet.arff";
		new OutlierHandler();
		return confirmationStr;
	}
	
	
	/**
	 * Method to communicate the request/response of Web interface with DataDiscretizer class.
	 *
	 * @return the data discretizer
	 * @throws Exception the exception
	 */
	// Discretize the data
	@RequestMapping(value = "/datadiscretizer", method = RequestMethod.POST, produces="application/json")
	public @ResponseBody DataDiscretizer dataDiscretization() throws Exception {
	    DataDiscretizer dd = new DataDiscretizer();
		return dd;
		}
	
	
	/**
	 * Method to communicate the request/response of Web interface with FeaturesSelector class.
	 *
	 * @return the features selector
	 * @throws Exception the exception
	 */
	// Filter the data
	@RequestMapping(value = "/featuresselector", method = RequestMethod.POST, produces="application/json")
	public @ResponseBody FeaturesSelector featuresSelection() throws Exception {
	    FeaturesSelector fs = new FeaturesSelector();
		return fs;
		}
	
	
	/**
	 * Method to communicate the request/response of Web interface to open the model learning interface.
	 *
	 * @param algo the decision tree algorithm string
	 * @return the model learner class object
	 * @throws Exception the exception
	 */	
	// Open the model learning interface
	@RequestMapping(value ="/modellearner", method = RequestMethod.POST)
    public String modelLearner(@ModelAttribute("communicationVariable")String communicationVariable, BindingResult modellearner, Model model) throws Exception {
       
        if(modellearner.hasErrors()){
            return "preprocessor";
        }else{
        	 model.addAttribute("communicationVariableId",communicationVariable);
        	 return "modellearner";
           }
    	}
	
	
	/**
	 * Method to communicate the request/response of Web interface with Auto Algorithm Selector class.
	 *
	 * @return the auto algorithm selector class object
	 * @throws Exception the exception
	 */	
	// Select the appropriate decision tree algorithm
	@RequestMapping(value="/autoalgoselection", method=RequestMethod.POST, produces="application/json")
	public @ResponseBody AutoAlgorithmSelector autoAlgoSelection() throws Exception {
		AutoAlgorithmSelector aas = new AutoAlgorithmSelector();
		return aas;
		}
	
	
	/**
	 * Method to communicate the request/response of Web interface with ModelTranslator class.
	 *
	 * @param algo the decision tree algorithm string
	 * @return the model learner class object
	 * @throws Exception the exception
	 */	
	// Learn the decision tree classification model
	@RequestMapping(value="/learnmodel", method=RequestMethod.POST, produces="application/json")
	public @ResponseBody ModelLearner learnModel(@RequestBody String algo) throws Exception {
		ModelLearner ml = new ModelLearner(algo);
		return ml;
		}
	
	
	/**
	 * Method to communicate the request/response of Web interface with ModelTranslator class.
	 *
	 * @param algo_modelstr the decision tree model string
	 * @return the model translator class object
	 * @throws Exception the exception
	 */
	// translate the model
	@RequestMapping(value="/modeltranslator", method=RequestMethod.POST, produces="application/json")
	public @ResponseBody ModelTranslator translateModel(@RequestBody String algo_modelstr) throws Exception {
		ModelTranslator mt = new ModelTranslator(algo_modelstr);
		return mt;
	}

	
}



<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/MachineLearningTools/WindowBasedSegmentation.java<|end_filename|>
/*
Copyright [2016] [<NAME>, Bang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.icl.llc.MachineLearningTools;

import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;

import org.uclab.mm.icl.llc.AER.jh.ConvertAudioData;

import mm.icl.llc.MachineLearningTools.Segmentation;

/**
 * This Class segment audio data based on seconds
 * 
 * @author <NAME>
 *
 */
public class WindowBasedSegmentation extends
		Segmentation<AudioInputStream, AudioInputStream> {
	int threshold;
	int size;
	AudioFormat audioFM;
	ConvertAudioData cad = new ConvertAudioData();
	boolean segFlag = false;

	/**
	 * Set Window for Segmentation with sample rate and second
	 * 
	 * @param sec
	 * @param samplerate
	 */
	public WindowBasedSegmentation(int sec, int samplerate) {
		this.threshold = sec * samplerate;
	}

	/**
	 * Segment Audio Data based on setted second
	 * 
	 * @param input
	 * @return AudioInputStream
	 */

	@Override
	public AudioInputStream segmentation(AudioInputStream input) {
		// TODO Auto-generated method stub
		AudioInputStream ais = null;
		size = (int) (threshold * input.getFormat().getFrameSize());
		if (threshold <= input.getFrameLength()+22) {
			audioFM = input.getFormat();
			ais = cad.convertAudioInputStream(segmentData(input), audioFM);
			segFlag = true;
		}
		return ais;
	}

	public AudioInputStream[] divideInputStream(AudioInputStream input,
			int divideNumber) {
		AudioInputStream[] ais = new AudioInputStream[divideNumber];
		for (int i = 0; i < divideNumber; i++) {
			try {
				AudioFormat audioFM = input.getFormat();
				byte[] header = new byte[44];
				byte[] data = new byte[(int) (input.getFrameLength()*input.getFormat().getFrameSize()) / divideNumber];
				input.read(header);
				input.read(data);

				ais[i] = cad.convertAudioInputStream(data, audioFM);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return ais;
	}

	/**
	 * Segment data by byte read
	 * 
	 * @param input
	 * @return byte[]
	 */

	public byte[] segmentData(AudioInputStream input) {
		byte[] header = new byte[44];
		byte[] temp = new byte[size];
		try {
			input.read(header);
			input.read(temp);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return temp;
	}

	/**
	 * return remained data
	 * 
	 * @param input
	 * @return AudioInputStream
	 */

	public AudioInputStream returnRemainedData(AudioInputStream input) {
		if (segFlag) {
			byte[] remained = new byte[(int) (input.getFrameLength()
					* input.getFormat().getFrameSize() - size)];
			AudioInputStream ais = null;
			try {
				input.read(remained);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ais = cad.convertAudioInputStream(remained, audioFM);
			segFlag = false;
			return ais;
		}
		return input;
	}
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sl/RecommendationFeedback.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sl;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author <NAME>
 */
@Entity
public class RecommendationFeedback implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private Long recommendationFeedbackID;
    private Long recommendationID;
    private Long userID;
    private int rate;
    private String reason;
    private String feedbackDate;
    
    private String requestType;
    private int situationCategoryID;
    private String situationCategoryDescription;
    
    

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof RecommendationFeedback)) {
            return false;
        }
        RecommendationFeedback other = (RecommendationFeedback) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.sl.RecommendationFeedback[ id=" + id + " ]";
    }

    /**
     * @return the recommendationFeedbackID
     */
    public Long getRecommendationFeedbackID() {
        return recommendationFeedbackID;
    }

    /**
     * @param recommendationFeedbackID the recommendationFeedbackID to set
     */
    public void setRecommendationFeedbackID(Long recommendationFeedbackID) {
        this.recommendationFeedbackID = recommendationFeedbackID;
    }

    /**
     * @return the recommendationID
     */
    public Long getRecommendationID() {
        return recommendationID;
    }

    /**
     * @param recommendationID the recommendationID to set
     */
    public void setRecommendationID(Long recommendationID) {
        this.recommendationID = recommendationID;
    }

    /**
     * @return the userID
     */
    public Long getUserID() {
        return userID;
    }

    /**
     * @param userID the userID to set
     */
    public void setUserID(Long userID) {
        this.userID = userID;
    }

    /**
     * @return the rate
     */
    public int getRate() {
        return rate;
    }

    /**
     * @param rate the rate to set
     */
    public void setRate(int rate) {
        this.rate = rate;
    }

    /**
     * @return the reason
     */
    public String getReason() {
        return reason;
    }

    /**
     * @param reason the reason to set
     */
    public void setReason(String reason) {
        this.reason = reason;
    }

    /**
     * @return the feedbackDate
     */
    public String getFeedbackDate() {
        return feedbackDate;
    }

    /**
     * @param feedbackDate the feedbackDate to set
     */
    public void setFeedbackDate(String feedbackDate) {
        this.feedbackDate = feedbackDate;
    }

    /**
     * @return the requestType
     */
    public String getRequestType() {
        return requestType;
    }

    /**
     * @param requestType the requestType to set
     */
    public void setRequestType(String requestType) {
        this.requestType = requestType;
    }

    /**
     * @return the situationCategoryID
     */
    public int getSituationCategoryID() {
        return situationCategoryID;
    }

    /**
     * @param situationCategoryID the situationCategoryID to set
     */
    public void setSituationCategoryID(int situationCategoryID) {
        this.situationCategoryID = situationCategoryID;
    }

    /**
     * @return the situationCategoryDescription
     */
    public String getSituationCategoryDescription() {
        return situationCategoryDescription;
    }

    /**
     * @param situationCategoryDescription the situationCategoryDescription to set
     */
    public void setSituationCategoryDescription(String situationCategoryDescription) {
        this.situationCategoryDescription = situationCategoryDescription;
    }
    
}


<|start_filename|>supporting-layer/uiux-authoring-tool/JavaDoc/org/uclab/mm/sl/uiux/analytics/QueryParams.html<|end_filename|>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_76-release) on Fri Dec 23 12:27:00 KST 2016 -->
<title>QueryParams</title>
<meta name="date" content="2016-12-23">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
    try {
        if (location.href.indexOf('is-external=true') == -1) {
            parent.document.title="QueryParams";
        }
    }
    catch(err) {
    }
//-->
var methods = {"i0":10,"i1":9,"i2":9};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!--   -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!--   -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/QueryParams.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/CustomVariables.html" title="class in org.uclab.mm.sl.uiux.analytics"><span class="typeNameLink">Prev&nbsp;Class</span></a></li>
<li><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/R.html" title="class in org.uclab.mm.sl.uiux.analytics"><span class="typeNameLink">Next&nbsp;Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/uclab/mm/sl/uiux/analytics/QueryParams.html" target="_top">Frames</a></li>
<li><a href="QueryParams.html" target="_top">No&nbsp;Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
  allClassesLink = document.getElementById("allclasses_navbar_top");
  if(window==top) {
    allClassesLink.style.display = "block";
  }
  else {
    allClassesLink.style.display = "none";
  }
  //-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary:&nbsp;</li>
<li>Nested&nbsp;|&nbsp;</li>
<li><a href="#enum.constant.summary">Enum Constants</a>&nbsp;|&nbsp;</li>
<li>Field&nbsp;|&nbsp;</li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail:&nbsp;</li>
<li><a href="#enum.constant.detail">Enum Constants</a>&nbsp;|&nbsp;</li>
<li>Field&nbsp;|&nbsp;</li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!--   -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.uclab.mm.sl.uiux.analytics</div>
<h2 title="Enum QueryParams" class="title">Enum QueryParams</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>java.lang.Enum&lt;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a>&gt;</li>
<li>
<ul class="inheritance">
<li>org.uclab.mm.sl.uiux.analytics.QueryParams</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.io.Serializable, java.lang.Comparable&lt;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a>&gt;</dd>
</dl>
<hr>
<br>
<pre>public enum <span class="typeNameLabel">QueryParams</span>
extends java.lang.Enum&lt;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a>&gt;</pre>
<div class="block">Query parameters supported by the tracking HTTP API.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="enum.constant.summary">
<!--   -->
</a>
<h3>Enum Constant Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Constant Summary table, listing enum constants, and an explanation">
<caption><span>Enum Constants</span><span class="tabEnd">&nbsp;</span></caption>
<tr>
<th class="colOne" scope="col">Enum Constant and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#ACTION_NAME">ACTION_NAME</a></span></code>
<div class="block">The title of the action being tracked.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#API_VERSION">API_VERSION</a></span></code>
<div class="block">The parameter &apiv=1 defines the api version to use (currently always set to 1)
 <p/>
 (recommended)</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#APP_ID">APP_ID</a></span></code>
<div class="block">The ID of the website we're tracking a visit/action for.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#AUTHENTICATION_TOKEN">AUTHENTICATION_TOKEN</a></span></code>
<div class="block"><span class="deprecatedLabel">Deprecated.</span>&nbsp;
<div class="block"><span class="deprecationComment">due to security concerns.</span></div>
</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#CAMPAIGN_KEYWORD">CAMPAIGN_KEYWORD</a></span></code>
<div class="block">Used to populate the Referrers > Campaigns report (clicking on a campaign loads all keywords for this campaign).</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#CAMPAIGN_NAME">CAMPAIGN_NAME</a></span></code>
<div class="block">Used to populate the Referrers > Campaigns report.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#CONTENT_INTERACTION">CONTENT_INTERACTION</a></span></code>
<div class="block">The name of the interaction with the content.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#CONTENT_NAME">CONTENT_NAME</a></span></code>
<div class="block">The name of the content.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#CONTENT_PIECE">CONTENT_PIECE</a></span></code>
<div class="block">The actual content piece.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#CONTENT_TARGET">CONTENT_TARGET</a></span></code>
<div class="block">The target of the content.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#COUNTRY">COUNTRY</a></span></code>
<div class="block">An override value for the country.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#DATETIME_OF_REQUEST">DATETIME_OF_REQUEST</a></span></code>
<div class="block">Override for the datetime of the request (normally the current time is used)</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#EVENT_ACTION">EVENT_ACTION</a></span></code>
<div class="block">The event action.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#EVENT_CATEGORY">EVENT_CATEGORY</a></span></code>
<div class="block">The event category.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#EVENT_NAME">EVENT_NAME</a></span></code>
<div class="block">The event name.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#EVENT_VALUE">EVENT_VALUE</a></span></code>
<div class="block">The event value.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#FIRST_VISIT_TIMESTAMP">FIRST_VISIT_TIMESTAMP</a></span></code>
<div class="block">The UNIX timestamp of this visitor's first visit (seconds since Jan 01 1970.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#GOAL_ID">GOAL_ID</a></span></code>
<div class="block">If specified, the tracking request will trigger a conversion for the goal of the website being tracked with this ID.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#HOURS">HOURS</a></span></code>
<div class="block">The current hour (local time).</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#LANGUAGE">LANGUAGE</a></span></code>
<div class="block">An override value for the Accept-Language HTTP header field.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#LATITUDE">LATITUDE</a></span></code>
<div class="block">An override value for the visitor's latitude, eg 22.456.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#LINK">LINK</a></span></code>
<div class="block">An external URL the user has opened.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#LONGITUDE">LONGITUDE</a></span></code>
<div class="block">An override value for the visitor's longitude, eg 22.456.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#MINUTES">MINUTES</a></span></code>
<div class="block">The current minute (local time).</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#PREVIOUS_VISIT_TIMESTAMP">PREVIOUS_VISIT_TIMESTAMP</a></span></code>
<div class="block">The UNIX timestamp of this visitor's previous visit (seconds since Jan 01 1970.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#RANDOM_NUMBER">RANDOM_NUMBER</a></span></code>
<div class="block">Meant to hold a random value that is generated before each request.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#RECORD">RECORD</a></span></code>
<div class="block">Required for tracking, must be set to one, eg, &rec=1.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#REFERRER">REFERRER</a></span></code>
<div class="block">The full HTTP Referrer URL.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#REVENUE">REVENUE</a></span></code>
<div class="block">A monetary value that was generated as revenue by this goal conversion.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#SCREEN_RESOLUTION">SCREEN_RESOLUTION</a></span></code>
<div class="block">The resolution of the device the visitor is using, eg 1280x1024.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#SCREEN_SCOPE_CUSTOM_VARIABLES">SCREEN_SCOPE_CUSTOM_VARIABLES</a></span></code>
<div class="block">This is a JSON encoded string of the custom variable array.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#SEARCH_CATEGORY">SEARCH_CATEGORY</a></span></code>
<div class="block">When <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#SEARCH_KEYWORD"><code>SEARCH_KEYWORD</code></a> is specified, you can optionally specify a search category with this parameter.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#SEARCH_KEYWORD">SEARCH_KEYWORD</a></span></code>
<div class="block">The Site Search keyword.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#SEARCH_NUMBER_OF_HITS">SEARCH_NUMBER_OF_HITS</a></span></code>
<div class="block">When <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#SEARCH_KEYWORD"><code>SEARCH_KEYWORD</code></a> is specified, we also recommend to set this to the number of search results.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#SECONDS">SECONDS</a></span></code>
<div class="block">The current second (local time).</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#SEND_IMAGE">SEND_IMAGE</a></span></code>
<div class="block">If set to 0 (send_image=0) UIUXAnalytics will respond with a HTTP 204 response code instead of a GIF image.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#SESSION_START">SESSION_START</a></span></code>
<div class="block">If set to 1, will force a new visit to be created for this action.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#TOTAL_NUMBER_OF_VISITS">TOTAL_NUMBER_OF_VISITS</a></span></code>
<div class="block">The current count of visits for this visitor.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#URL_PATH">URL_PATH</a></span></code>
<div class="block">The full URL for the current action.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#USER_AGENT">USER_AGENT</a></span></code>
<div class="block">An override value for the User-Agent HTTP header field.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#USER_ID">USER_ID</a></span></code>
<div class="block">Defines the User ID for this request.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#VISIT_SCOPE_CUSTOM_VARIABLES">VISIT_SCOPE_CUSTOM_VARIABLES</a></span></code>
<div class="block">This is a JSON encoded string of the custom variable array.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#VISITOR_ID">VISITOR_ID</a></span></code>
<div class="block">The unique visitor ID, must be a 16 characters hexadecimal string.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!--   -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#toString--">toString</a></span>()</code>&nbsp;</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#valueOf-java.lang.String-">valueOf</a></span>(java.lang.String&nbsp;name)</code>
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>static <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a>[]</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#values--">values</a></span>()</code>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Enum">
<!--   -->
</a>
<h3>Methods inherited from class&nbsp;java.lang.Enum</h3>
<code>compareTo, equals, getDeclaringClass, hashCode, name, ordinal, valueOf</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!--   -->
</a>
<h3>Methods inherited from class&nbsp;java.lang.Object</h3>
<code>getClass, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ ENUM CONSTANT DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="enum.constant.detail">
<!--   -->
</a>
<h3>Enum Constant Detail</h3>
<a name="APP_ID">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>APP_ID</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> APP_ID</pre>
<div class="block">The ID of the website we're tracking a visit/action for.
 <p/>
 (required)</div>
</li>
</ul>
<a name="RECORD">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>RECORD</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> RECORD</pre>
<div class="block">Required for tracking, must be set to one, eg, &rec=1.
 <p/>
 (required)</div>
</li>
</ul>
<a name="URL_PATH">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>URL_PATH</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> URL_PATH</pre>
<div class="block">The full URL for the current action.
 <p/>
 (required)</div>
</li>
</ul>
<a name="ACTION_NAME">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>ACTION_NAME</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> ACTION_NAME</pre>
<div class="block">The title of the action being tracked.<p>
 For example, Help / Feedback will create the Action Feedback in the category Help.
 <p/>
 (recommended)</div>
</li>
</ul>
<a name="VISITOR_ID">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>VISITOR_ID</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> VISITOR_ID</pre>
<div class="block">The unique visitor ID, must be a 16 characters hexadecimal string.<p>
 Every unique visitor must be assigned a different ID and this ID must not change after it is assigned.
 If this value is not set UIUXAnalytics will still track visits, but the unique visitors metric might be less accurate.
 <p/>
 (recommended)</div>
</li>
</ul>
<a name="RANDOM_NUMBER">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>RANDOM_NUMBER</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> RANDOM_NUMBER</pre>
<div class="block">Meant to hold a random value that is generated before each request.<p>
 Using it helps avoid the tracking request being cached by the browser or a proxy.
 <p/>
 (recommended)</div>
</li>
</ul>
<a name="API_VERSION">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>API_VERSION</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> API_VERSION</pre>
<div class="block">The parameter &apiv=1 defines the api version to use (currently always set to 1)
 <p/>
 (recommended)</div>
</li>
</ul>
<a name="REFERRER">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>REFERRER</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> REFERRER</pre>
<div class="block">The full HTTP Referrer URL.<p>
 This value is used to determine how someone got to your website (ie, through a website, search engine or campaign).</div>
</li>
</ul>
<a name="VISIT_SCOPE_CUSTOM_VARIABLES">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>VISIT_SCOPE_CUSTOM_VARIABLES</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> VISIT_SCOPE_CUSTOM_VARIABLES</pre>
<div class="block">This is a JSON encoded string of the custom variable array.</div>
</li>
</ul>
<a name="TOTAL_NUMBER_OF_VISITS">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>TOTAL_NUMBER_OF_VISITS</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> TOTAL_NUMBER_OF_VISITS</pre>
<div class="block">The current count of visits for this visitor.<p>
 To set this value correctly, it would be required to store the value for each visitor in your application (using sessions or persisting in a database).
 Then you would manually increment the counts by one on each new visit or "session", depending on how you choose to define a visit.
 This value is used to populate the report Visitors > Engagement > Visits by visit number.</div>
</li>
</ul>
<a name="PREVIOUS_VISIT_TIMESTAMP">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>PREVIOUS_VISIT_TIMESTAMP</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> PREVIOUS_VISIT_TIMESTAMP</pre>
<div class="block">The UNIX timestamp of this visitor's previous visit (seconds since Jan 01 1970. (UTC)).<p>
 This parameter is used to populate the report Visitors > Engagement > Visits by days since last visit.</div>
</li>
</ul>
<a name="FIRST_VISIT_TIMESTAMP">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>FIRST_VISIT_TIMESTAMP</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> FIRST_VISIT_TIMESTAMP</pre>
<div class="block">The UNIX timestamp of this visitor's first visit (seconds since Jan 01 1970. (UTC)).<p>
 This could be set to the date where the user first started using your software/app, or when he/she created an account.
 This parameter is used to populate the Goals > Days to Conversion report.</div>
</li>
</ul>
<a name="CAMPAIGN_NAME">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>CAMPAIGN_NAME</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> CAMPAIGN_NAME</pre>
<div class="block">Used to populate the Referrers > Campaigns report.
 Note: this parameter will only be used for the first pageview of a visit.</div>
</li>
</ul>
<a name="CAMPAIGN_KEYWORD">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>CAMPAIGN_KEYWORD</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> CAMPAIGN_KEYWORD</pre>
<div class="block">Used to populate the Referrers > Campaigns report (clicking on a campaign loads all keywords for this campaign).
 Note: this parameter will only be used for the first pageview of a visit.</div>
</li>
</ul>
<a name="SCREEN_RESOLUTION">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>SCREEN_RESOLUTION</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> SCREEN_RESOLUTION</pre>
<div class="block">The resolution of the device the visitor is using, eg 1280x1024.</div>
</li>
</ul>
<a name="HOURS">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>HOURS</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> HOURS</pre>
<div class="block">The current hour (local time).</div>
</li>
</ul>
<a name="MINUTES">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>MINUTES</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> MINUTES</pre>
<div class="block">The current minute (local time).</div>
</li>
</ul>
<a name="SECONDS">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>SECONDS</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> SECONDS</pre>
<div class="block">The current second (local time).</div>
</li>
</ul>
<a name="USER_AGENT">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>USER_AGENT</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> USER_AGENT</pre>
<div class="block">An override value for the User-Agent HTTP header field.<p>
 The user agent is used to detect the operating system and browser used.</div>
</li>
</ul>
<a name="LANGUAGE">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>LANGUAGE</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> LANGUAGE</pre>
<div class="block">An override value for the Accept-Language HTTP header field.<p></div>
</li>
</ul>
<a name="USER_ID">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>USER_ID</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> USER_ID</pre>
<div class="block">Defines the User ID for this request.<p>
 User ID is any non empty unique string identifying the user (such as an email address or a username).
 To access this value, users must be logged-in in your system so you can fetch this user ID from your system, and pass it to UIUXAnalytics.
 The User ID appears in the visitor log, the Visitor profile, and you can Segment reports for one or several User ID (userId segment).
 When specified, the User ID will be "enforced". This means that if there is no recent visit with this User ID, a new one will be created.
 If a visit is found in the last 30 minutes with your specified User ID, then the new action will be recorded to this existing visit.</div>
</li>
</ul>
<a name="SESSION_START">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>SESSION_START</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> SESSION_START</pre>
<div class="block">If set to 1, will force a new visit to be created for this action.</div>
</li>
</ul>
<a name="SCREEN_SCOPE_CUSTOM_VARIABLES">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>SCREEN_SCOPE_CUSTOM_VARIABLES</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> SCREEN_SCOPE_CUSTOM_VARIABLES</pre>
<div class="block">This is a JSON encoded string of the custom variable array.</div>
</li>
</ul>
<a name="LINK">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>LINK</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> LINK</pre>
<div class="block">An external URL the user has opened.<p>
 Used for tracking outlink clicks. We recommend to also set the url parameter to this same value.</div>
</li>
</ul>
<a name="SEARCH_KEYWORD">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>SEARCH_KEYWORD</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> SEARCH_KEYWORD</pre>
<div class="block">The Site Search keyword.<p></div>
</li>
</ul>
<a name="SEARCH_CATEGORY">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>SEARCH_CATEGORY</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> SEARCH_CATEGORY</pre>
<div class="block">When <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#SEARCH_KEYWORD"><code>SEARCH_KEYWORD</code></a> is specified, you can optionally specify a search category with this parameter.</div>
</li>
</ul>
<a name="SEARCH_NUMBER_OF_HITS">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>SEARCH_NUMBER_OF_HITS</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> SEARCH_NUMBER_OF_HITS</pre>
<div class="block">When <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#SEARCH_KEYWORD"><code>SEARCH_KEYWORD</code></a> is specified, we also recommend to set this to the number of search results.</div>
</li>
</ul>
<a name="GOAL_ID">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>GOAL_ID</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> GOAL_ID</pre>
<div class="block">If specified, the tracking request will trigger a conversion for the goal of the website being tracked with this ID.</div>
</li>
</ul>
<a name="REVENUE">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>REVENUE</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> REVENUE</pre>
<div class="block">A monetary value that was generated as revenue by this goal conversion.<p>
 Only used if <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#GOAL_ID"><code>GOAL_ID</code></a> is specified in the request.</div>
</li>
</ul>
<a name="AUTHENTICATION_TOKEN">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>AUTHENTICATION_TOKEN</h4>
<pre>@Deprecated
public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> AUTHENTICATION_TOKEN</pre>
<div class="block"><span class="deprecatedLabel">Deprecated.</span>&nbsp;<span class="deprecationComment">due to security concerns.</span></div>
<div class="block">32 character authorization key used to authenticate the API request.</div>
</li>
</ul>
<a name="COUNTRY">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>COUNTRY</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> COUNTRY</pre>
<div class="block">An override value for the country.<p>
 Should be set to the two letter country code of the visitor (lowercase), eg fr, de, us.
 Requires <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#AUTHENTICATION_TOKEN"><code>AUTHENTICATION_TOKEN</code></a>.</div>
</li>
</ul>
<a name="LATITUDE">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>LATITUDE</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> LATITUDE</pre>
<div class="block">An override value for the visitor's latitude, eg 22.456.<p>
 Requires <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#AUTHENTICATION_TOKEN"><code>AUTHENTICATION_TOKEN</code></a>.</div>
</li>
</ul>
<a name="LONGITUDE">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>LONGITUDE</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> LONGITUDE</pre>
<div class="block">An override value for the visitor's longitude, eg 22.456.<p>
 Requires <a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html#AUTHENTICATION_TOKEN"><code>AUTHENTICATION_TOKEN</code></a>.</div>
</li>
</ul>
<a name="DATETIME_OF_REQUEST">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>DATETIME_OF_REQUEST</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> DATETIME_OF_REQUEST</pre>
<div class="block">Override for the datetime of the request (normally the current time is used)</div>
</li>
</ul>
<a name="CONTENT_NAME">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>CONTENT_NAME</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> CONTENT_NAME</pre>
<div class="block">The name of the content. For instance 'Ad Foo Bar'</div>
</li>
</ul>
<a name="CONTENT_PIECE">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>CONTENT_PIECE</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> CONTENT_PIECE</pre>
<div class="block">The actual content piece. For instance the path to an image, video, audio, any text</div>
</li>
</ul>
<a name="CONTENT_TARGET">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>CONTENT_TARGET</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> CONTENT_TARGET</pre>
<div class="block">The target of the content. For instance the URL of a landing page</div>
</li>
</ul>
<a name="CONTENT_INTERACTION">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>CONTENT_INTERACTION</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> CONTENT_INTERACTION</pre>
<div class="block">The name of the interaction with the content. For instance a 'click'</div>
</li>
</ul>
<a name="EVENT_CATEGORY">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>EVENT_CATEGORY</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> EVENT_CATEGORY</pre>
<div class="block">The event category. Must not be empty. (eg. Videos, Music, Games...)</div>
</li>
</ul>
<a name="EVENT_ACTION">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>EVENT_ACTION</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> EVENT_ACTION</pre>
<div class="block">The event action. Must not be empty. (eg. Play, Pause, Duration, Add Playlist, Downloaded, Clicked...)</div>
</li>
</ul>
<a name="EVENT_NAME">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>EVENT_NAME</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> EVENT_NAME</pre>
<div class="block">The event name. (eg. a Movie name, or Song name, or File name...)</div>
</li>
</ul>
<a name="EVENT_VALUE">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>EVENT_VALUE</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> EVENT_VALUE</pre>
<div class="block">The event value. Must be a float or integer value (numeric), not a string.</div>
</li>
</ul>
<a name="SEND_IMAGE">
<!--   -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>SEND_IMAGE</h4>
<pre>public static final&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a> SEND_IMAGE</pre>
<div class="block">If set to 0 (send_image=0) UIUXAnalytics will respond with a HTTP 204 response code instead of a GIF image.<p>
 This improves performance and can fix errors if images are not allowed to be obtained directly (eg Chrome Apps). Available since UIUXAnalytics 2.10.0</div>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!--   -->
</a>
<h3>Method Detail</h3>
<a name="values--">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>values</h4>
<pre>public static&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a>[]&nbsp;values()</pre>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.  This method may be used to iterate
over the constants as follows:
<pre>
for (QueryParams c : QueryParams.values())
&nbsp;   System.out.println(c);
</pre></div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>an array containing the constants of this enum type, in the order they are declared</dd>
</dl>
</li>
</ul>
<a name="valueOf-java.lang.String-">
<!--   -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>valueOf</h4>
<pre>public static&nbsp;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a>&nbsp;valueOf(java.lang.String&nbsp;name)</pre>
<div class="block">Returns the enum constant of this type with the specified name.
The string must match <i>exactly</i> an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are 
not permitted.)</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>name</code> - the name of the enum constant to be returned.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the enum constant with the specified name</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.lang.IllegalArgumentException</code> - if this enum type has no constant with the specified name</dd>
<dd><code>java.lang.NullPointerException</code> - if the argument is null</dd>
</dl>
</li>
</ul>
<a name="toString--">
<!--   -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>toString</h4>
<pre>public&nbsp;java.lang.String&nbsp;toString()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code>toString</code>&nbsp;in class&nbsp;<code>java.lang.Enum&lt;<a href="../../../../../../org/uclab/mm/sl/uiux/analytics/QueryParams.html" title="enum in org.uclab.mm.sl.uiux.analytics">QueryParams</a>&gt;</code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!--   -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!--   -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/QueryParams.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/CustomVariables.html" title="class in org.uclab.mm.sl.uiux.analytics"><span class="typeNameLink">Prev&nbsp;Class</span></a></li>
<li><a href="../../../../../../org/uclab/mm/sl/uiux/analytics/R.html" title="class in org.uclab.mm.sl.uiux.analytics"><span class="typeNameLink">Next&nbsp;Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/uclab/mm/sl/uiux/analytics/QueryParams.html" target="_top">Frames</a></li>
<li><a href="QueryParams.html" target="_top">No&nbsp;Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
  allClassesLink = document.getElementById("allclasses_navbar_bottom");
  if(window==top) {
    allClassesLink.style.display = "block";
  }
  else {
    allClassesLink.style.display = "none";
  }
  //-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary:&nbsp;</li>
<li>Nested&nbsp;|&nbsp;</li>
<li><a href="#enum.constant.summary">Enum Constants</a>&nbsp;|&nbsp;</li>
<li>Field&nbsp;|&nbsp;</li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail:&nbsp;</li>
<li><a href="#enum.constant.detail">Enum Constants</a>&nbsp;|&nbsp;</li>
<li>Field&nbsp;|&nbsp;</li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!--   -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/sc/dataadapter/ActivityRecommendationLogAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.sc.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.sc.ActivityRecommendation;
import org.uclab.mm.datamodel.sc.ActivityRecommendationLog;

/**
 * This is ActivityRecommendationLogAdapter class which implements the Data Access Interface for CRUD operations
 * @author dcadmin
 */
public class ActivityRecommendationLogAdapter implements DataAccessInterface{
    
    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(ActivityRecommendationLogAdapter.class);
    public ActivityRecommendationLogAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving ActivityRecommendationLog. 
     * @param objActivityRecommendationLog
     * @return List of String
     */
    public List<String> Save(Object objActivityRecommendationLog) {
        ActivityRecommendationLog objInnerActivityRecommendationLog = new ActivityRecommendationLog();
        objInnerActivityRecommendationLog =  (ActivityRecommendationLog) objActivityRecommendationLog;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_ActivityRecommendationLog(?, ?, ?, ?)}");
            
            objCallableStatement.setLong("ActivityPlanID", objInnerActivityRecommendationLog.getActivityPlanId());
            objCallableStatement.setString("Description", objInnerActivityRecommendationLog.getDescription());
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
            Date dtTimestamp = sdf.parse(objInnerActivityRecommendationLog.getTimestamp());
            Timestamp tsTimestamp = new Timestamp(dtTimestamp.getYear(),dtTimestamp.getMonth(), dtTimestamp.getDate(), dtTimestamp.getHours(), dtTimestamp.getMinutes(), dtTimestamp.getSeconds(), 00);
            objCallableStatement.setTimestamp("Timestamp", tsTimestamp);
                                   
            objCallableStatement.registerOutParameter("ActivityRecommendationLogID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intActivityRecommendationLogID = objCallableStatement.getLong("ActivityRecommendationLogID");
            objDbResponse.add(String.valueOf(intActivityRecommendationLogID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("Activity Recommendation saved successfully, Activity Recommendation Details="+objActivityRecommendationLog);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding Activity Recommendation");
        	objDbResponse.add("Error in adding Activity Recommendation");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for Update ActivityRecommendationLog. 
     * Not implemented
     */
    @Override
    public <T> List<String> Update(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for retrieving ActivityRecommendationLog. 
     * @param objActivityRecommendationLog
     * @return List of ActivityRecommendationLog
     */
    @Override
    public List<ActivityRecommendationLog> RetriveData(Object objActivityRecommendationLog) {
        ActivityRecommendationLog objOuterActivityRecommendationLog = new ActivityRecommendationLog();
        List<ActivityRecommendationLog> objListInnerActivityRecommendationLog = new ArrayList<ActivityRecommendationLog>();
        objOuterActivityRecommendationLog =  (ActivityRecommendationLog) objActivityRecommendationLog;
        
        try
        {
            CallableStatement objCallableStatement = null;
            if(objOuterActivityRecommendationLog.getRequestType() == "ByPlan")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_ActivityRecommendationLogByActivityPlanID(?)}");
                objCallableStatement.setLong("ActivityPlanID", objOuterActivityRecommendationLog.getActivityPlanId());
            }
            else if(objOuterActivityRecommendationLog.getRequestType() == "ByUserDate")
            {
                objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_ActivityRecommendationLogByUserDate(?, ?, ?)}");
                objCallableStatement.setLong("UserID", objOuterActivityRecommendationLog.getUserID());
                
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm	
            
                Date dtStartTimeStamp = sdf.parse(objOuterActivityRecommendationLog.getStartTimestamp());
                Timestamp tsStartTimeStamp = new Timestamp(dtStartTimeStamp.getYear(),dtStartTimeStamp.getMonth(), dtStartTimeStamp.getDate(), dtStartTimeStamp.getHours(), dtStartTimeStamp.getMinutes(), dtStartTimeStamp.getSeconds(), 00);
                objCallableStatement.setTimestamp("StartTimeStamp", tsStartTimeStamp);

                Date dtEndTimeStamp = sdf.parse(objOuterActivityRecommendationLog.getEndTimestamp());
                Timestamp tsEndTimeStamp = new Timestamp(dtEndTimeStamp.getYear(),dtEndTimeStamp.getMonth(), dtEndTimeStamp.getDate(), dtEndTimeStamp.getHours(), dtEndTimeStamp.getMinutes(), dtEndTimeStamp.getSeconds(), 00);
                objCallableStatement.setTimestamp("EndTimeStamp", tsEndTimeStamp);
                
            }
            
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                ActivityRecommendationLog objInnerActivityRecommendationLog = new ActivityRecommendationLog();
                objInnerActivityRecommendationLog.setActivityRecommendationLogId(objResultSet.getLong("ActivityRecommendationLogID"));
                objInnerActivityRecommendationLog.setDescription(objResultSet.getString("Description"));
                
                Timestamp tsTimestamp = objResultSet.getTimestamp("Timestamp"); //updated
                objInnerActivityRecommendationLog.setTimestamp(tsTimestamp.toString());
                
                objListInnerActivityRecommendationLog.add(objInnerActivityRecommendationLog);
            }
            objConn.close();
            logger.info("Activity Recommendation loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading Activity Recommendation");
        }   
        return objListInnerActivityRecommendationLog;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf 
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>knowledge-curation-layer/DDKAT/src/main/java/org/uclab/mm/kcl/ddkat/algoselector/AutoAlgorithmSelector.java<|end_filename|>
/**
* Copyright [2017] [<NAME>, <NAME>, <NAME>]
* 
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.uclab.mm.kcl.ddkat.algoselector;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jcolibri.cbrcore.CBRCase;
import jcolibri.method.retrieve.RetrievalResult;

import org.uclab.mm.kcl.edket.algoselector.AutomaticAlgorithmSelector;
import org.uclab.mm.kcl.edket.algoselector.QueryManager;
import org.uclab.mm.kcl.edket.algoselector.SimilarityManager;
import org.uclab.mm.kcl.edket.algoselector.mfe.InputCaseBuilder;
import org.uclab.mm.kcl.edket.algoselector.mfe.MetaFeature;
import org.uclab.mm.kcl.edket.algoselector.mfe.MetaFeatureExtractor;


//TODO: Auto-generated Javadoc
/**
* This class recommends appropriate decision tree algorithm.
*/
public class AutoAlgorithmSelector {
	
	private ArrayList<String> caseIDs;
	private ArrayList<String> autoSelectedAlgos;
	private ArrayList<String> similarityScores;
	
	/** base directory to store resource data files */
	private static final String BASE_DIR = System.getProperty("user.home") + "/DDKAT/resources/";
	
	/**
	 * Constructor to instantiate a new AutoAlgorithmSelector object.
	 * @param dataUnorderedObject the json data object
	 * @throws Exception the exception
	 */
//	public AutoAlgorithmSelector(String inputfilePath) throws Exception {
	public AutoAlgorithmSelector() throws Exception {
    	
    	this.caseIDs = new ArrayList<String>();
    	this.autoSelectedAlgos = new ArrayList<String>();
    	this.similarityScores = new ArrayList<String>();
        /**** build inputCase file if not exists ****/	
    	String resolvedCasesFile = BASE_DIR + "AlgorithmsSelectionCaseBase.csv";
    	String outputFile = resolvedCasesFile.substring(0,resolvedCasesFile.lastIndexOf('/'));
     	InputCaseBuilder icb = new InputCaseBuilder();
    	icb.setMetaFeatureFile(resolvedCasesFile);
    	icb.buildCasesIfNotExists();
    	
    	String inputFile = BASE_DIR + "ProcessedDataSet.arff";
        Map<MetaFeature, Integer> simIntervals = InputCaseBuilder.detectSimIntervals(resolvedCasesFile);
               
        /****instantiate AutomaticAlgorithmSelector****/
        AutomaticAlgorithmSelector autoAlgoSelector = new AutomaticAlgorithmSelector(new QueryManager(), new SimilarityManager(simIntervals));
        autoAlgoSelector.configure();
        
        /**** set options and extract meta features ****/ 
        Map<String, String> options = new HashMap<String, String>();
        options.put("dataset_dir", "");
        options.put("dataset_file", inputFile);
        options.put("mode", "single");
        options.put("output_dir", outputFile + "/output/");
 
        MetaFeatureExtractor mfe = new MetaFeatureExtractor( options );
        List<Map<String, Double>> xFeaturesList = mfe.extractMetaFeatures();

        
        /**** build queryCase from the extracted features ****/
        Map<MetaFeature, Object> queryCase = buildQueryCase(xFeaturesList.get(0));
              
        /********* select cases ***********/
        Collection<CBRCase> selectedCases = autoAlgoSelector.evaluateSimilarity(queryCase).retrieveTopKResults(3);
        Collection<RetrievalResult> evaluation = autoAlgoSelector.getEvaluationList();
        
        /**** string parsing ****/
        for(RetrievalResult rr : evaluation){
        	
            if(selectedCases.contains(rr.get_case())){
            	
            	String originalDescriptionStr = rr.get_case().getDescription().toString(); 
            	String originalSolutionStr = rr.get_case().getSolution().toString();
            	    
            	String[] splitDescriptionArr = originalDescriptionStr.split("CaseID=");
                String subDescriptionStr = splitDescriptionArr[1];  
                String[] subDescriptionSplitArr = subDescriptionStr.split(", ",2);
                String caseIDStr = subDescriptionSplitArr[0];
                System.out.println("CASE ID : "+caseIDStr);
                this.caseIDs.add(caseIDStr);
                                 
                originalSolutionStr = originalSolutionStr.substring(1, originalSolutionStr.length()-1);
                String[] algorithmSplitArr = originalSolutionStr.split(": ",3);
                String tempAlgoStr;
                for(int i=0;i<3;i++){
                    tempAlgoStr = algorithmSplitArr[i];
                    tempAlgoStr = tempAlgoStr.substring(6, tempAlgoStr.length()-3);
                    System.out.println("Position:"+i+" "+tempAlgoStr);
                    if(!tempAlgoStr.equals("RandomForest") && !tempAlgoStr.equals("LADTree")){
                        System.out.println("Algo 1:"+tempAlgoStr);
                        this.autoSelectedAlgos.add(tempAlgoStr);
                        break;
                        }
                    }

                double similarityScore = rr.getEval();
                long factor = (long) Math.pow(10, 6);
                similarityScore = similarityScore * factor;
                long tmp = Math.round(similarityScore);
                double roundedSimilarityScore = (double) tmp / factor;
               	String similarityStr = String.valueOf(roundedSimilarityScore);
            	this.similarityScores.add(similarityStr);
            	
            	}
        	}
              
            
        /******* reuse *********/
        Collection<CBRCase> reuseCases = autoAlgoSelector.combineQueryAndCaseMethod(selectedCases);
        
        /******** revise *******/ 
        CBRCase bestCase = autoAlgoSelector.getBestCase(reuseCases);
        System.out.println("Best Algorithm: " + bestCase.getSolution().toString());

        /********* retain ********/
        //. autoAlgoSelector.retainCase(bestCase);
        
    }
    

	/**
     * builds queryCase from the extracted meta features.
     * Note: extracted features contains extra features that we don't need for our application, so here we are filtering only required features.
     * 
     * @param xFeatures
     * @return Map<MetaFeature, Object> queryCase
     */
    private Map<MetaFeature, Object> buildQueryCase(Map<String, Double> xFeatures){
        
        Map<MetaFeature, Object> queryCase = new HashMap<MetaFeature, Object>();
        for(String key : xFeatures.keySet()){
            
            //. filter out only required metaFeatures
            try{ 
                MetaFeature columnName = MetaFeature.valueOf(key);
                Object columnValue = xFeatures.get(key);
                queryCase.put(columnName, columnValue);
            } catch (IllegalArgumentException e){
                //. we do not need this feature
            }
        }
        return queryCase;
    }  
    
    
    public ArrayList<String> getCaseIDs() {
 		return caseIDs;
 	}

 	public void setCaseIDs(ArrayList<String> caseIDs) {
 		this.caseIDs = caseIDs;
 	}
    
    public ArrayList<String> getAutoSelectedAlgos() {
		return autoSelectedAlgos;
	}

	public void setAutoSelectedAlgos(ArrayList<String> autoSelectedAlgos) {
		this.autoSelectedAlgos = autoSelectedAlgos;
	}
	
	public ArrayList<String> getSimilarityScores() {
		return similarityScores;
	}

	public void setSimilarityScores(ArrayList<String> similarityScores) {
		this.similarityScores = similarityScores;
	}


}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/ic/dataadapter/UserPreferredLocationAdapter.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.ic.dataadapter;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.ic.UserPreferredLocation;

/**
 * This is UserPreferredLocationAdapter class which implements the Data Access Interface for CRUD operations
 * @author Taqdir
 */
public class UserPreferredLocationAdapter implements DataAccessInterface {

    private Connection objConn;
    private static final Logger logger = LoggerFactory.getLogger(UserPreferredLocationAdapter.class);
    public UserPreferredLocationAdapter()
    {
        
    }
    
    /**
     * This is implementation function for saving UserPreferredLocation. 
     * @param objUserPreferredLocation
     * @return List of String
     */
    @Override
    public  List<String> Save(Object objUserPreferredLocation) {
        UserPreferredLocation objInnerUserPreferredLocation = new UserPreferredLocation();
        objInnerUserPreferredLocation =  (UserPreferredLocation) objUserPreferredLocation;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_UserPreferredLocation(?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserID", objInnerUserPreferredLocation.getUserId());
            objCallableStatement.setFloat("Latitude", objInnerUserPreferredLocation.getLatitude());
            objCallableStatement.setFloat("Longitude", objInnerUserPreferredLocation.getLongitude());
            objCallableStatement.setString("LocationLabel", objInnerUserPreferredLocation.getLocationLabel());
            objCallableStatement.setString("LocationDescription", objInnerUserPreferredLocation.getLocationDescription());
                                   
            objCallableStatement.registerOutParameter("UserPreferredLocationID", Types.BIGINT);
            objCallableStatement.execute();
            
            Long intUserPreferredLocationID = objCallableStatement.getLong("UserPreferredLocationID");
            objDbResponse.add(String.valueOf(intUserPreferredLocationID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info("User Preferred Location saved successfully, User Details="+objUserPreferredLocation);
        }
        catch (Exception e)
        {
        	logger.info("Error in adding User Preferred Location");
        	objDbResponse.add("Error in adding User Preferred Location");
        } 
        return objDbResponse;
    }

    /**
     * This is implementation function for updating UserPreferredLocation. 
     * @param objUserPreferredLocation
     * @return List of String
     */
    @Override
    public List<String> Update(Object objUserPreferredLocation) {
        
        UserPreferredLocation objInnerUserPreferredLocation = new UserPreferredLocation();
        objInnerUserPreferredLocation =  (UserPreferredLocation) objUserPreferredLocation;
        List<String> objDbResponse = new ArrayList<>();
        
        try
        {

            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_UserPreferredLocation(?, ?, ?, ?, ?, ?)}");
            
            objCallableStatement.setLong("UserPreferredLocationID", objInnerUserPreferredLocation.getUserPreferredLocationId());
            objCallableStatement.setLong("UserID", objInnerUserPreferredLocation.getUserId());
            objCallableStatement.setFloat("Latitude", objInnerUserPreferredLocation.getLatitude());
            objCallableStatement.setFloat("Longitude", objInnerUserPreferredLocation.getLongitude());
            objCallableStatement.setString("LocationLabel", objInnerUserPreferredLocation.getLocationLabel());
            objCallableStatement.setString("LocationDescription", objInnerUserPreferredLocation.getLocationDescription());
                        
            objCallableStatement.execute();
            
            Long intUserPreferredLocationID = objInnerUserPreferredLocation.getUserPreferredLocationId();
            objDbResponse.add(String.valueOf(intUserPreferredLocationID));
            objDbResponse.add("No Error");

            objConn.close();
            logger.info(" User Preferred Location saved successfully,  User Preferred Location Details="+objUserPreferredLocation);
        }
        catch (Exception e)
        {
        	logger.info("Error in updating  User Preferred Location");
        	objDbResponse.add("Error in updating  User Preferred Location");
        } 
        return objDbResponse;
        
    }

    /**
     * This is implementation function for retrieving UserPreferredLocation. 
     * @param objUserPreferredLocation
     * @return List of UserPreferredLocation
     */
    @Override
    public List<UserPreferredLocation> RetriveData(Object objUserPreferredLocation) {
        UserPreferredLocation objOuterUserPreferredLocation = new UserPreferredLocation();
        List<UserPreferredLocation> objListUserPreferredLocation = new ArrayList<UserPreferredLocation>();
        objOuterUserPreferredLocation =  (UserPreferredLocation) objUserPreferredLocation;
        
        try
        {
            CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_UserPreferredLocationByUserID(?)}");
            
            objCallableStatement.setLong("UserID", objOuterUserPreferredLocation.getUserId());
            ResultSet objResultSet = objCallableStatement.executeQuery();

            while(objResultSet.next())
            {
                UserPreferredLocation objInnerUserPreferredLocation = new UserPreferredLocation();
                objInnerUserPreferredLocation.setUserPreferredLocationId(objResultSet.getLong("UserPreferredLocationID"));
                objInnerUserPreferredLocation.setUserId(objResultSet.getLong("UserID"));
                objInnerUserPreferredLocation.setLatitude(objResultSet.getFloat("Latitude"));
                objInnerUserPreferredLocation.setLongitude(objResultSet.getFloat("Longitude"));
                objInnerUserPreferredLocation.setLocationLabel(objResultSet.getString("LocationLabel"));
                objInnerUserPreferredLocation.setLocationDescription(objResultSet.getString("LocationDescription"));
                
                objListUserPreferredLocation.add(objInnerUserPreferredLocation);
            }
            objConn.close();
            logger.info("users preferred location loaded successfully");
        }
        catch (Exception e)
        {
        	logger.info("Error in loading  users preferred location");
        }   
        return objListUserPreferredLocation;
    }

    @Override
    public <T> List<T> Delete(T objEntity) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * This is implementation function for connection database.
     * @param objConf
     */
    @Override
     public void ConfigureAdapter(Object objConf) {
         try
         {
            objConn = (Connection)objConf;
            logger.info("Database connected successfully");
         }
         catch(Exception ex)
         {
        	 logger.info("Error in connection to Database");
         }
    }
    
}


<|start_filename|>data-curation-layer/passive-data-reader/src/main/java/com/uclab/dcl/LifelogSchemaModel.java<|end_filename|>
package com.uclab.dcl;

import java.util.ArrayList;
/**
 * Make a schema of table in the HIVE
 * @author CSHSC
 *
 */
public class LifelogSchemaModel {

	private final String schema_id;
	private final String schema_name;
	private final ArrayList<Object> schema_tables;

	public LifelogSchemaModel(String schema_id, String schema_name, ArrayList<Object> schema_tables) {
		this.schema_id = schema_id;
		this.schema_name = schema_name;
		this.schema_tables = schema_tables;
	}

	public String getSchema_id() {
		return schema_id;
	}

	public String getSchema_name() {
		return schema_name;
	}

	public ArrayList<Object> getSchema_tables() {
		return schema_tables;
	}

}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/DatabaseStorage.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package org.uclab.mm.datamodel;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.dc.PhysiologicalFactors;
import org.uclab.mm.datamodel.dc.UserDisabilities;
import org.uclab.mm.datamodel.dc.UserFacilities;
import org.uclab.mm.datamodel.dc.UserRiskFactors;
import org.uclab.mm.datamodel.dc.UserSchedule;
import org.uclab.mm.datamodel.dc.Users;
import org.uclab.mm.datamodel.ic.Device;
import org.uclab.mm.datamodel.ic.FoodLog;
import org.uclab.mm.datamodel.ic.UserAccelerometerData;
import org.uclab.mm.datamodel.ic.UserDetectedLocation;
import org.uclab.mm.datamodel.ic.UserDevice;
import org.uclab.mm.datamodel.ic.UserGPSData;
import org.uclab.mm.datamodel.ic.UserPreferredLocation;
import org.uclab.mm.datamodel.ic.UserRecognizedActivity;
import org.uclab.mm.datamodel.ic.UserRecognizedActivityAccumulate;
import org.uclab.mm.datamodel.ic.UserRecognizedActivityLog;
import org.uclab.mm.datamodel.ic.UserRecognizedEmotion;
import org.uclab.mm.datamodel.ic.UserRecognizedHLC;
import org.uclab.mm.datamodel.llm.LifelogMonitorActivity;
import org.uclab.mm.datamodel.sc.Achievements;
import org.uclab.mm.datamodel.sc.ActivityPlan;
import org.uclab.mm.datamodel.sc.ActivityRecommendation;
import org.uclab.mm.datamodel.sc.ActivityRecommendationLog;
import org.uclab.mm.datamodel.sc.Facts;
import org.uclab.mm.datamodel.sc.ProfileData;
import org.uclab.mm.datamodel.sc.Recommendation;
import org.uclab.mm.datamodel.sc.RecommendationException;
import org.uclab.mm.datamodel.sc.RecommendationExplanation;
import org.uclab.mm.datamodel.sc.Situation;
import org.uclab.mm.datamodel.sc.UserGoal;
import org.uclab.mm.datamodel.sc.UserPreferredActivities;
import org.uclab.mm.datamodel.sc.UserRewards;
import org.uclab.mm.datamodel.sl.ActiveSession;
import org.uclab.mm.datamodel.sl.ActivityFeedback;
import org.uclab.mm.datamodel.sl.ExpertReview;
import org.uclab.mm.datamodel.sl.FactsFeedback;
import org.uclab.mm.datamodel.sl.RecommendationFeedback;
import org.uclab.mm.datamodel.sl.UserAccelerometerDataVisulization;
import org.uclab.mm.datamodel.sl.UserGPSDataVisulization;



/**
 * This is the DatabaseStorage class, it extends the AbstractDataBridge class
 * @author Taqdir
 */
public class DatabaseStorage extends AbstractDataBridge {
    
    private Connection objConnection;
 
    public DatabaseStorage(DataAccessInterface objDAInterface)
    {
       setDataAdapter(objDAInterface);
    }

    private static final Logger logger = LoggerFactory.getLogger(DatabaseStorage.class);
    
    /**
     * This is implementation function for saving User.
     * @param objUser
     * @return List of String 
     */
    @Override
    public List<String> SaveUser(Users objUser) {
        
        List<String> objResponse = new ArrayList<>();
        try
        {
            objDAInterface.ConfigureAdapter(objConnection);
            objResponse = objDAInterface.Save(objUser);
            logger.info("User saved successfully, User Details="+objUser);
        }
        catch(Exception ex)
        {
        	logger.info("Error in saving user, User Details=");
        	objResponse.add("Error in saving user");
        }
        return objResponse;
    }

    /**
     * This is implementation function for updating User.
     * @param objUser
     * @return List of string
     *  
     */
    @Override
    public List<String> UpdateUser(Users objUser) {
        List<String> objResponse = new ArrayList<>();
        try{
        objDAInterface.ConfigureAdapter(objConnection);
        objResponse = objDAInterface.Update(objUser);     
        logger.info("User udpated successfully, User Details="+objUser);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating user, User Details=");
        	objResponse.add("Error in saving user");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving User. 
     * @param objUser
     * @return List of Users
     */
    @Override
    public List<Users> RetriveUser(Users objUser) {
    	List<Users> objListUsers = new  ArrayList<Users>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListUsers =  objDAInterface.RetriveData(objUser);
            logger.info("User loaded successfully.");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in getting user");
    	}
        return objListUsers;
    }

    /**
     * This is implementation function for deleting User.
     * @param objUser
     * @return List of String 
     */
    @Override
    public List<String> DeleteUser(Users objUser) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
    
    /**
     * This is implementation function for saving Device. 
     * @param objDevice
     * @return List of String
     */
    @Override
     public List<String> SaveDevice(Device objDevice) {
        
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objDevice);   
        	logger.info("Device saved successfully, Device Details="+objDevice);
        }
        catch(Exception ex)
        {
        	logger.info("Error in registring Device");
        	objResponse.add("Error in registering Device");
        }
        return objResponse;
    }

    /**
     * This is implementation function for updating Device. 
     * @param objDevice
     * @return List of String
     */
    @Override
    public List<String> UpdateDevice(Device objDevice) {
        List<String> objResponse = new ArrayList<>();
        try
        {
	        objDAInterface.ConfigureAdapter(objConnection);
	        objResponse = objDAInterface.Update(objDevice); 
	        logger.info("Device updated successfully, Device Details="+objDevice);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updated Device");
        	objResponse.add("Error in updated Device");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving Device. 
     * @param objDevice
     * @return List of String
     */
    @Override
    public List<Device> RetriveDevice(Device objDevice) {
    	List<Device> objListDevice = new  ArrayList<Device>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListDevice =  objDAInterface.RetriveData(objDevice);
            logger.info("Device loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in Device loadeding");
    	}
    	return objListDevice;
    }

    /**
     * This is implementation function for retrieving UserDevice. 
     * @param objUserDevice
     * @return List of String
     */
    @Override
    public List<UserDevice> RetriveUserDevice(UserDevice objUserDevice) {
    	List<UserDevice> objListUserDevice = new  ArrayList<UserDevice>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListUserDevice =  objDAInterface.RetriveData(objUserDevice);
            logger.info("Device loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in Device loadeding");
    	}
       
        return objListUserDevice;
    }

    /**
     * This is implementation function for adding UserDevice. 
     * @param objUserDevice
     * @return List of String
     */
    @Override
    public List<String> SaveUserDevice(UserDevice objUserDevice) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objUserDevice);   
        	logger.info("Device registered successfully, User Details="+objUserDevice);
        }
        catch(Exception ex)
        {
        	logger.info("Error in registering Device");
        	objResponse.add("Error in registering Device");
        }
        return objResponse;
    }

    /**
     * This is implementation function for updating UserDevice. 
     * @param objUserDevice
     * @return List of UserDevice
     */
    @Override
    public List<String> UpdateUserDevice(UserDevice objUserDevice) {
        List<String> objResponse = new ArrayList<>();
        try
        {
	        objDAInterface.ConfigureAdapter(objConnection);
	        objResponse = objDAInterface.Update(objUserDevice); 
	        logger.info("Sensor updated successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in subscribing sensor");
        	objResponse.add("Error in subscribing sensor");
        }
        return objResponse;
    }

    /**
     * This is implementation function for saving UserRiskFactors. 
     * @param objUserRiskFactors
     * @return List of String
     */
    @Override
    public List<String> SaveUserRiskFactors(UserRiskFactors objUserRiskFactors) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objUserRiskFactors);  
        	logger.info("Risk factor saved successfully, User Details=" + objUserRiskFactors);
        }
        catch(Exception ex)
        {

        	logger.info("Error in saving risk factor");
        	objResponse.add("Error in saving risk factor");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving UserRiskFactors.
     * @param objUserRiskFactors
     * @return List of UserRiskFactors 
     */
    @Override
    public List<UserRiskFactors> RetriveUserRiskFactors(UserRiskFactors objUserRiskFactors) {
    	List<UserRiskFactors> objListUserRiskFactors = new  ArrayList<UserRiskFactors>();
    	try
    	{
    		 objDAInterface.ConfigureAdapter(objConnection);
    	     objListUserRiskFactors =  objDAInterface.RetriveData(objUserRiskFactors);
    	     logger.info("Risk factor loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in getting risk factor");
    	}
        
        return objListUserRiskFactors;
    }
        
    
    /**
     * This is implementation function for updating UserRiskFactors. 
     * @param objUserRiskFactors
     * @return List of String
     */
    @Override
    public List<String> UpdateUserRiskFactors(UserRiskFactors objUserRiskFactors) {
         List<String> objResponse = new ArrayList<>();
         try
         {
        	 objDAInterface.ConfigureAdapter(objConnection);
        	 objResponse = objDAInterface.Update(objUserRiskFactors);
        	 logger.info("Risk factor saved successfully, User Details="+objUserRiskFactors);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating risk factor");
        	objResponse.add("Error in updating risk factor");
        }
        return objResponse;
    }
    
    /**
     * This is implementation function for saving PhysiologicalFactors. 
     * @param objPhysiologicalFactors
     * @return List of String
     */

    @Override
    public List<String> SavePhysiologicalFactors(PhysiologicalFactors objPhysiologicalFactors) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objPhysiologicalFactors);  
        	logger.info("Physiological factor saved successfully, User Details="+objPhysiologicalFactors);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Physiological factors");
        	objResponse.add("Error in adding Physiological factors");
        }
        return objResponse;
    }

    /**
     * This is implementation function for updating PhysiologicalFactors. 
     * @param objPhysiologicalFactors
     * @return List of String
     */
    @Override
    public List<String> UpdatePhysiologicalFactors(PhysiologicalFactors objPhysiologicalFactors) {
         List<String> objResponse = new ArrayList<>();
         try
         {
        	 objDAInterface.ConfigureAdapter(objConnection);
        	 objResponse = objDAInterface.Update(objPhysiologicalFactors);   
        	 logger.info("Physiological factor updated successfully, User Details="+objPhysiologicalFactors);
         }
        catch(Exception ex)
        {
        	logger.info("Error in updated Physiological factors");
        	objResponse.add("Error in updated Physiological factors");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving PhysiologicalFactors.
     * @param objPhysiologicalFactors
     * @return List of PhysiologicalFactors 
     */
    @Override
    public List<PhysiologicalFactors> RetrivePhysiologicalFactors(PhysiologicalFactors objPhysiologicalFactors) {
    	List<PhysiologicalFactors> objListPhysiologicalFactors = new  ArrayList<PhysiologicalFactors>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListPhysiologicalFactors =  objDAInterface.RetriveData(objPhysiologicalFactors);
            logger.info("Physiological is loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in Loading Physiological factors");
    	}
        
        return objListPhysiologicalFactors;
    }

    /**
     * This is implementation function for saving UserFacilities. 
     * @param objUserFacilities
     * @return List of String
     */
    @Override
    public List<String> SaveUserFacilities(UserFacilities objUserFacilities) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objUserFacilities); 
        	logger.info("user Facilities saved successfully, User Details="+objUserFacilities);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding user Facilities");
        	objResponse.add("Error in adding user Facilities");
        }
        return objResponse;
    }

    /**
     * This is implementation function for updating UserFacilities. 
     * @param objUserFacilities
     * @return List of String
     */
    @Override
    public List<String> UpdateUserFacilities(UserFacilities objUserFacilities) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Update(objUserFacilities);
        	logger.info("user Facilities saved successfully, UserFacilities Details="+objUserFacilities);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updated user Facilities");
        	objResponse.add("Error in updated user Facilities");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving UserFacilities.
     * @param objUserFacilities
     * @return List of UserFacilities
     */
    @Override
    public List<UserFacilities> RetriveUserFacilities(UserFacilities objUserFacilities) {
    	List<UserFacilities> objListUserFacilities = new  ArrayList<UserFacilities>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListUserFacilities =  objDAInterface.RetriveData(objUserFacilities);
            logger.info("user Facilities loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading user Facilities");
    	}
        return objListUserFacilities;
    }

    /**
     * This is implementation function for saving UserPreferredActivities.
     * @param objUserPreferredActivities
     * @return List of String
     */
    @Override
    public List<String> SaveUserPreferredActivities(UserPreferredActivities objUserPreferredActivities) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objUserPreferredActivities);
        	 logger.info("User Preferred Activities saved successfully, User Preferred Activities Details="+objUserPreferredActivities);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding User Preferred Activities");
        	objResponse.add("Error in adding User Preferred Activities");
        }
        return objResponse;
    }

    /**
     * This is implementation function for updating UserPreferredActivities. 
     * @param objUserPreferredActivities
     * @return List of String
     */
    @Override
    public List<String> UpdateUserPreferredActivities(UserPreferredActivities objUserPreferredActivities) {
         List<String> objResponse = new ArrayList<>();
         try
         {
        	 objDAInterface.ConfigureAdapter(objConnection);
        	 objResponse = objDAInterface.Update(objUserPreferredActivities); 
        	 logger.info("User Preferred Activities updated successfully, User Preferred Activities Details="+objUserPreferredActivities);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating User Preferred Activities");
        	objResponse.add("Error in updating User Preferred Activities");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving UserPreferredActivities. 
     * @param objUserPreferredActivities
     * @return List of UserPreferredActivities
     */
    @Override
    public List<UserPreferredActivities> RetriveUserPreferredActivities(UserPreferredActivities objUserPreferredActivities) {
    	List<UserPreferredActivities> objListUserPreferredActivities = new  ArrayList<UserPreferredActivities>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListUserPreferredActivities =  objDAInterface.RetriveData(objUserPreferredActivities);
            logger.info("User Preferred Activities Data loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading User Preferred Activities");
    	}
        return objListUserPreferredActivities;
    }

    /**
     * This is implementation function for saving UserGPSData. 
     * @param objUserGPSData
     * @return List of String
     */
    @Override
    public List<String> SaveUserGPSData(UserGPSData objUserGPSData) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objUserGPSData);   
        	logger.info("User GPS Data added successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding User GPS Data");
        	objResponse.add("Error in adding User GPS Data");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving UserGPSData. 
     * @param objUserGPSData
     * @return List of UserGPSData
     */
    @Override
    public List<UserGPSData> RetriveUserGPSData(UserGPSData objUserGPSData) {
    	List<UserGPSData> objListUserGPSData = new  ArrayList<UserGPSData>();
    	try
    	{
    		 objDAInterface.ConfigureAdapter(objConnection);
    	     objListUserGPSData =  objDAInterface.RetriveData(objUserGPSData);
    	     logger.info("User GPS Data loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading User GPS Data");
    	}
        return objListUserGPSData;
    }

    /**
     * This is implementation function for saving UserAccelerometerData. 
     * @param objUserAccelerometerData
     * @return List of String
     */
    @Override
    public List<String> SaveUserAccelerometerData(UserAccelerometerData objUserAccelerometerData) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objUserAccelerometerData);  
        	logger.info("Use rAccelerometer Data added successfully");
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding User Accelerometer Data");
        	objResponse.add("Error in adding User Accelerometer Data");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving UserAccelerometerData. 
     * @param objUserAccelerometerData
     * @return List of UserAccelerometerData
     */
    @Override
    public List<UserAccelerometerData> RetriveUserAccelerometerData(UserAccelerometerData objUserAccelerometerData) {
    	List<UserAccelerometerData> objListUserAccelerometerData = new  ArrayList<UserAccelerometerData>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListUserAccelerometerData =  objDAInterface.RetriveData(objUserAccelerometerData);
            logger.info("Use rAccelerometer Data loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading User Accelerometer Data");
    	}
        
        return objListUserAccelerometerData;
    }

    /**
     * This is implementation function for saving UserRecognizedActivity.
     * @param objUserRecognizedActivity
     * @return List of String 
     */
    @Override
    public List<String> SaveUserRecognizedActivity(UserRecognizedActivity objUserRecognizedActivity) {
         List<String> objResponse = new ArrayList<>();
         try
         {
        	 objDAInterface.ConfigureAdapter(objConnection);
        	 objResponse = objDAInterface.Save(objUserRecognizedActivity);  
        	 logger.info("user recognized activities saved successfully, user recognized activities Details="+objUserRecognizedActivity);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding  user recognized activities");
        	objResponse.add("Error in adding user recognized activities");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving UserRecognizedActivity.
     * @param objUserRecognizedActivity
     * @return List of UserRecognizedActivity 
     */
    @Override
    public List<UserRecognizedActivity> RetriveUserRecognizedActivity(UserRecognizedActivity objUserRecognizedActivity) {
    	List<UserRecognizedActivity> objListUserRecognizedActivity = new ArrayList<UserRecognizedActivity>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListUserRecognizedActivity =  objDAInterface.RetriveData(objUserRecognizedActivity);
            logger.info("users recognized activities successfully loaded");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading users recognized activities");
    	}
        return objListUserRecognizedActivity;
    }

    /**
     * This is implementation function for saving UserDetectedLocation. 
     * @param objUserDetectedLocation
     * @return List of String
     */
    @Override
    public List<String> SaveUserDetectedLocation(UserDetectedLocation objUserDetectedLocation) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objUserDetectedLocation);   
        	logger.info("User Detected Location saved successfully, User Detected Location Details="+objUserDetectedLocation);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding User Detected Location");
        	objResponse.add("Error in adding User Detected Location");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving UserDetectedLocation.
     * @param objUserDetectedLocation
     * @return List of UserDetectedLocation 
     */
    @Override
    public List<UserDetectedLocation> RetriveUserDetectedLocation(UserDetectedLocation objUserDetectedLocation) {
    	List<UserDetectedLocation> objListUserDetectedLocation = new ArrayList<UserDetectedLocation>();
    	try
    	{
    		 objDAInterface.ConfigureAdapter(objConnection);
    	     objListUserDetectedLocation =  objDAInterface.RetriveData(objUserDetectedLocation);
    	     logger.info("User Detected Location laoded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading User Detected Location");
    	}
        return objListUserDetectedLocation;
    }

    /**
     * This is implementation function for saving UserGoal. 
     * @param objUserGoal
     * @return List of String
     */
    @Override
    public List<String> SaveUserGoal(UserGoal objUserGoal) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objUserGoal); 
        	logger.info("User Goal saved successfully, User Goal Details="+objUserGoal);
        }
        catch(Exception ex)
        {
        	logger.info("Error in Adding User Goal");
        	objResponse.add("Error in Adding User Goal");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving UserGoal.
     * @param objUserGoal
     * @return List of UserGoal 
     */
    @Override
    public List<UserGoal> RetriveUserGoal(UserGoal objUserGoal) {
    	 List<UserGoal> objListUserGoal = new  ArrayList<UserGoal>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListUserGoal =  objDAInterface.RetriveData(objUserGoal);
            logger.info(" User Goal loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading  User Goal");
    	}
        return objListUserGoal;
    }

    /**
     * This is implementation function for saving ActivityPlan. 
     * @param objActivityPlan
     * @return List of String
     */
    @Override
    public List<String> SaveActivityPlan(ActivityPlan objActivityPlan) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objActivityPlan);   
        	logger.info("Activity Plan saved successfully, Activity Plan Details="+objActivityPlan);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Activity Plan");
        	objResponse.add("Error in adding Activity Plan");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving ActivityPlan. 
     * @param objActivityPlan
     * @return List of ActivityPlan
     * 
     */
    @Override
    public List<ActivityPlan> RetriveActivityPlan(ActivityPlan objActivityPlan) {
    	List<ActivityPlan> objListActivityPlan = new  ArrayList<ActivityPlan>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListActivityPlan =  objDAInterface.RetriveData(objActivityPlan);
            logger.info("User Goal loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading User Goal");
    	}
        return objListActivityPlan;
    }

    /**
     * This is implementation function for saving ActivityRecommendation. 
     * @param objActivityRecommendation
     * @return List of String
     */
    @Override
    public List<String> SaveActivityRecommendation(ActivityRecommendation objActivityRecommendation) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objActivityRecommendation);    
        	logger.info("Activity Recommendation saved successfully, Activity Recommendation Details="+objActivityRecommendation);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Activity Recommendation");
        	objResponse.add("Error in adding Activity Recommendation");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving ActivityRecommendation. 
     * @param objActivityRecommendation
     * @return List of ActivityRecommendation
     */
    @Override
    public List<ActivityRecommendation> RetriveActivityRecommendation(ActivityRecommendation objActivityRecommendation) {
    	List<ActivityRecommendation> objListActivityRecommendation = new  ArrayList<ActivityRecommendation>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListActivityRecommendation =  objDAInterface.RetriveData(objActivityRecommendation);
            logger.info("Activity Recommendation loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading Activity Recommendation");
    	}
        return objListActivityRecommendation;
    }

    /**
     * This is implementation function for validating Users. 
     * @param objUsers
     * @return List of String
     */
    @Override
    public List<String> IsUserValid(Users objUsers) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    /**
     * This is implementation function for saving ActiveSession. 
     * @param objActiveSession
     * @return List of String
     */
    @Override
    public List<String> SaveActiveSession(ActiveSession objActiveSession) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objActiveSession);    
        	logger.info("Active Session saved successfully.");
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Active Session");
        }
        return objResponse;
    }

    /**
     * This is implementation function setter of DataAccessInterface. 
     * @param DAInterface
     */
    @Override
    public void setDataAdapter(DataAccessInterface DAInterface) {
        super.objDAInterface = DAInterface;
        
        try
        {
            if(objConnection == null || objConnection.isClosed())
            {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                objConnection = DriverManager.getConnection("jdbc:sqlserver://BILAL-OFFICE-PC\\SQLEXPRESS;database=DBMiningMindsV1_5;user=sa;password=<PASSWORD>;");
                logger.info("Database connected successfully");
            }
        }
        catch (Exception e)
        {
        	logger.info("Error in connecting database");
        }  
    }

    /**
     * This is implementation function for retrieving ProfileData. 
     * @param objProfileData
     * @return List of ProfileData
     */
    @Override
    public List<ProfileData> RetriveProfileData(ProfileData objProfileData) {
    	List<ProfileData> objListProfileData = new  ArrayList<>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListProfileData =  objDAInterface.RetriveData(objProfileData);
            logger.info("Profile Data loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading Profile Data");
    	}
        return objListProfileData;
    }
    /**
     * This is implementation function for retrieving UserGPSDataVisulization. 
     * @param objUserGPSData
    * @return List of UserGPSDataVisulization
     */

    @Override
    public List<UserGPSDataVisulization> RetriveUserGPSDataVisulization(UserGPSDataVisulization objUserGPSData) {
    	List<UserGPSDataVisulization> objListUserGPSData = new  ArrayList<UserGPSDataVisulization>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListUserGPSData =  objDAInterface.RetriveData(objUserGPSData);
            logger.info("User GPS Data Visulization loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading User GPS Data Visulization");
    	}
        return objListUserGPSData;
    }
    
    /**
     * This is implementation function for retrieving UserAccelerometerDataVisulization. 
     * @param objUserAccelerometerData
    * @return List of UserAccelerometerDataVisulization
     */
    @Override
    public List<UserAccelerometerDataVisulization> RetriveUserAccelerometerDataVisulization(UserAccelerometerDataVisulization objUserAccelerometerData) {
    	
    	List<UserAccelerometerDataVisulization> objListUserAccelerometerData = new  ArrayList<UserAccelerometerDataVisulization>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListUserAccelerometerData =  objDAInterface.RetriveData(objUserAccelerometerData);
            logger.info("User Accelerometer Data Visulization loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading User Accelerometer Data Visulization");
    	}
       
        return objListUserAccelerometerData;
    }

    /**
     * This is implementation function for retrieving UserRewards. 
     * @param objUserRewards
    * @return List of UserRewards
     */
    @Override
    public List<UserRewards> RetriveUserRewards(UserRewards objUserRewards) {
    	List<UserRewards> objListUserRewards = new  ArrayList<UserRewards>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListUserRewards =  objDAInterface.RetriveData(objUserRewards);
            logger.info("User Rewards loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading User Rewards");
    	}
        return objListUserRewards;
        
    }

    /**
     * This is implementation function for saving UserRewards. 
     * @param objUserRewards
   * @return List of String
     */
    @Override
    public List<String> SaveUserRewards(UserRewards objUserRewards) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objUserRewards);    
        	logger.info("User Rewards saved successfully, User Rewards Details="+objUserRewards);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding User Rewards");
        	objResponse.add("Error in adding User Rewards");
        }
        return objResponse;
    }

    /**
     * This is implementation function for updating UserRewards.
     * @param objUserRewards
   * @return List of String 
     */
    @Override
    public List<String> UpdateUserRewards(UserRewards objUserRewards) {
        List<String> objResponse = new ArrayList<>();
        try
       	{
    	   objDAInterface.ConfigureAdapter(objConnection);
    	   objResponse = objDAInterface.Update(objUserRewards);  
    	   logger.info("User Rewards updated successfully, User Rewards Details="+objUserRewards);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating User Rewards");
        	objResponse.add("Error in updating User Rewards");
        }
        return objResponse;
    }

    /**
     * This is implementation function for saving UserRecognizedActivityLog. 
     * @param objUserRecognizedActivityLog
   * @return List of String
     */
    @Override
    public List<String> SaveUserRecognizedActivityLog(UserRecognizedActivityLog objUserRecognizedActivityLog) {
       List<String> objResponse = new ArrayList<>();
         try
         {
        	 objDAInterface.ConfigureAdapter(objConnection);
        	 objResponse = objDAInterface.Save(objUserRecognizedActivityLog);  
        	 logger.info("user recognized activities Log saved successfully, User Details="+objUserRecognizedActivityLog);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding user recognized activities Log");
        	objResponse.add("Error in adding user recognized activities Log");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving UserRecognizedActivityLog. 
     * @param objUserRecognizedActivityLog
     * @return List of UserRecognizedActivityLog
     */
    @Override
    public List<UserRecognizedActivityLog> RetriveUserRecognizedActivityLog(UserRecognizedActivityLog objUserRecognizedActivityLog) {
    	List<UserRecognizedActivityLog> objListUserRecognizedActivityLog = new ArrayList<UserRecognizedActivityLog>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListUserRecognizedActivityLog =  objDAInterface.RetriveData(objUserRecognizedActivityLog);
            logger.info("users recognized activities log laoded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading users recognized activities log");
    	}
        return objListUserRecognizedActivityLog;
    }

    /**
     * This is implementation function for saving ActivityRecommendationLog. 
     * @param objActivityRecommendationLog
     * @return List of String
     */
    @Override
    public List<String> SaveActivityRecommendationLog(ActivityRecommendationLog objActivityRecommendationLog) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objActivityRecommendationLog); 
        	logger.info("Activity Recommendation saved successfully, Activity Recommendation Details="+objActivityRecommendationLog);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Activity Recommendation");
        	objResponse.add("Error in adding Activity Recommendation");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving ActivityRecommendationLog. 
     * @param objActivityRecommendationLog
     * @return List of ActivityRecommendationLog
     */
    @Override
    public List<ActivityRecommendationLog> RetriveActivityRecommendationLog(ActivityRecommendationLog objActivityRecommendationLog) {
    	List<ActivityRecommendationLog> objListActivityRecommendationLog = new  ArrayList<ActivityRecommendationLog>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListActivityRecommendationLog =  objDAInterface.RetriveData(objActivityRecommendationLog);
            logger.info("Activity Recommendation loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading Activity Recommendation");
    	}
        return objListActivityRecommendationLog;
    }

    /**
     * This is implementation function for saving Situation. 
     * @param objSituation
     * @return List of String
     */
    @Override
    public List<String> SaveSituation(Situation objSituation) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objSituation); 
        	logger.info("situation saved successfully, User Details="+objSituation);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding situation");
        	objResponse.add("Error in adding situation");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving Situation.
     * @param objSituation
     * @return List of Situation 
     */
    @Override
    public List<Situation> RetriveSituation(Situation objSituation) {
    	List<Situation> objListSituation = new  ArrayList<Situation>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListSituation =  objDAInterface.RetriveData(objSituation);
            logger.info("situation loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading situation");
    	}
        return objListSituation;
    }

    /**
     * This is implementation function for updating Situation. 
     * @param objSituation
     * @return List of String
     */
    @Override
    public List<String> UpdateSituation(Situation objSituation) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Update(objSituation); 
        	logger.info("situation saved successfully, situation Details="+objSituation);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating situation");
        	objResponse.add("Error in updating situation");
        }
        return objResponse;
    }

    /**
     * This is implementation function for saving Recommendation. 
     * @param objRecommendation
     * @return List of String
     */
    @Override
    public List<String> SaveRecommendation(Recommendation objRecommendation) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objRecommendation);  
        	logger.info("Recommendation saved successfully, Recommendation Details="+objRecommendation);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Recommendation");
        	objResponse.add("Error in adding Recommendation");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving Recommendation. 
     * @param objRecommendation
     * @return List of Recommendation
     */
    @Override
    public List<Recommendation> RetriveRecommendation(Recommendation objRecommendation) {
    	List<Recommendation> objListRecommendation = new  ArrayList<Recommendation>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListRecommendation =  objDAInterface.RetriveData(objRecommendation);
            logger.info("Recommendation loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading Recommendation");
    	}
        
        return objListRecommendation;
    }

    /**
     * This is implementation function for updating Recommendation. 
     * @param objRecommendation
     * @return List of String
     */
    @Override
    public List<String> UpdateRecommendation(Recommendation objRecommendation) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Update(objRecommendation);
        	logger.info("Recommendation saved successfully, Recommendation Details="+objRecommendation);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating Recommendation");
        	objResponse.add("Error in updating Recommendation");
        }
        return objResponse;
    }

    /**
     * This is implementation function for saving RecommendationException.
     * @param objRecommendationException
     * @return List of String 
     */
    @Override
    public List<String> SaveRecommendationException(RecommendationException objRecommendationException) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objRecommendationException);   
        	logger.info("RecommendationException saved successfully, RecommendationException Details="+objRecommendationException);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding RecommendationException");
        	objResponse.add("Error in adding RecommendationException");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving RecommendationException.
     * @param objRecommendationException
     * @return List of RecommendationException 
     */
    @Override
    public List<RecommendationException> RetriveRecommendationException(RecommendationException objRecommendationException) {
    	List<RecommendationException> objListRecommendationException = new  ArrayList<RecommendationException>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListRecommendationException =  objDAInterface.RetriveData(objRecommendationException);
            logger.info("Recommendation Exception loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading Recommendation Exception");
    	}
        return objListRecommendationException;
    }

    /**
     * This is implementation function for updating RecommendationException.
     * @param objRecommendationException
     * @return List of RecommendationException 
     */
    @Override
    public List<String> UpdateRecommendationException(RecommendationException objRecommendationException) {
         List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Update(objRecommendationException);   
        	logger.info("RecommendationException updated successfully, RecommendationException Details="+objRecommendationException);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating RecommendationException");
        	objResponse.add("Error in updating RecommendationException");
        }
        return objResponse;
    }

    /**
     * This is implementation function for saving RecommendationExplanation. 
     * @param objRecommendationExplanation
     * @return List of String
     */
    @Override
    public List<String> SaveRecommendationExplanation(RecommendationExplanation objRecommendationExplanation) {
         List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objRecommendationExplanation);  
        	logger.info("RecommendationExplanation saved successfully, RecommendationExplanation Details="+objRecommendationExplanation);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding RecommendationExplanation");
        	objResponse.add("Error in adding RecommendationExplanation");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving RecommendationExplanation. 
     * @param objRecommendationExplanation
     * @return List of RecommendationExplanation
     */
    @Override
    public List<RecommendationExplanation> RetriveRecommendationExplanation(RecommendationExplanation objRecommendationExplanation) {
    	List<RecommendationExplanation> objListRecommendationExplanation = new  ArrayList<RecommendationExplanation>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListRecommendationExplanation =  objDAInterface.RetriveData(objRecommendationExplanation);
            logger.info("Recommendation Explanation loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading Recommendation Explanation");
    	}
        return objListRecommendationExplanation;
    }

    /**
     * This is implementation function for updating RecommendationExplanation. 
     * @param objRecommendationExplanation
     * @return List of String
     */
    @Override
    public List<String> UpdateRecommendationExplanation(RecommendationExplanation objRecommendationExplanation) {
         List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Update(objRecommendationExplanation);  
        	logger.info("RecommendationExplanation updated successfully, RecommendationExplanation Details="+objRecommendationExplanation);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating RecommendationExplanation");
        	objResponse.add("Error in updating RecommendationExplanation");
        }
        return objResponse;
    }

    /**
     * This is implementation function for saving RecommendationFeedback. 
     * @param objRecommendationFeedback
     * @return List of String
     */
    @Override
    public List<String> SaveRecommendationFeedback(RecommendationFeedback objRecommendationFeedback) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objRecommendationFeedback);   
        	logger.info("Recommendation Feedback saved successfully, Recommendation Feedback Details="+objRecommendationFeedback);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Recommendation Feedback");
        	objResponse.add("Error in adding Recommendation Feedback");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving RecommendationFeedback. 
     * @param objRecommendationFeedback
     * @return List of RecommendationFeedback
     */
    @Override
    public List<RecommendationFeedback> RetriveRecommendationFeedback(RecommendationFeedback objRecommendationFeedback) {
    	List<RecommendationFeedback> objListRecommendationFeedback = new  ArrayList<RecommendationFeedback>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListRecommendationFeedback =  objDAInterface.RetriveData(objRecommendationFeedback);
            logger.info("Recommendation Feedback loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading Recommendation Feedback");
    	}
        
        return objListRecommendationFeedback;
    }
    
    /**
     * This is implementation function for updating RecommendationFeedback. 
     * @param objRecommendationFeedback
     * @return List of String
     */

    @Override
    public List<String> UpdateRecommendationFeedback(RecommendationFeedback objRecommendationFeedback) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Update(objRecommendationFeedback);
        	logger.info("Recommendation Feedback updated successfully, Recommendation Feedback Details="+objRecommendationFeedback);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating Recommendation Feedback");
        	objResponse.add("Error in updating Recommendation Feedback");
        }
        return objResponse;
    }

    /**
     * This is implementation function for saving ActivityFeedback. 
     * @param objActivityFeedback
     * @return List of String
     */
    @Override
    public List<String> SaveActivityFeedback(ActivityFeedback objActivityFeedback) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objActivityFeedback);  
        	logger.info("Activity Feedback saved successfully, Activity Feedback Details="+objActivityFeedback);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Activity Feedback");
        	objResponse.add("Error in adding Activity Feedback");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving ActivityFeedback. 
     * @param objActivityFeedback
     * @return List of ActivityFeedback
     */
    @Override
    public List<ActivityFeedback> RetriveActivityFeedback(ActivityFeedback objActivityFeedback) {
    	List<ActivityFeedback> objListActivityFeedback = new  ArrayList<ActivityFeedback>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListActivityFeedback =  objDAInterface.RetriveData(objActivityFeedback);
            logger.info("recommendation Feedback loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading recommendation Feedback");
    	}
        
        return objListActivityFeedback;
    }

    /**
     * This is implementation function for updating ActivityFeedback. 
     * @param objActivityFeedback
     * @return List of String
     */
    @Override
    public List<String> UpdateActivityFeedback(ActivityFeedback objActivityFeedback) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Update(objActivityFeedback);  
        	logger.info("Activity Feedback updated successfully, Activity Feedback Details="+objActivityFeedback);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating Activity Feedback");
        	objResponse.add("Error in updating Activity Feedback");
        }
        return objResponse;
    }

    /**
     * This is implementation function for saving ExpertReview. 
     * @param objExpertReview
     * @return List of String
     */
    @Override
    public List<String> SaveExpertReview(ExpertReview objExpertReview) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objExpertReview); 
        	logger.info("Expert Review saved successfully, Expert Review Details="+objExpertReview);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Expert Review");
        	objResponse.add("Error in adding Expert Review");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving ExpertReview. 
     * @param objExpertReview
     * @return List of ExpertReview
     */
    @Override
    public List<ExpertReview> RetriveExpertReview(ExpertReview objExpertReview) {
    	List<ExpertReview> objListExpertReview = new  ArrayList<ExpertReview>();
    	try
    	{
    		 objDAInterface.ConfigureAdapter(objConnection);
    	     objListExpertReview =  objDAInterface.RetriveData(objExpertReview);
    	     logger.info("Expert Review loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading Expert Review");
    	}
        return objListExpertReview;
    }

    /**
     * This is implementation function for updating ExpertReview. 
     * @param objExpertReview
     * @return List of String
     */
    @Override
    public List<String> UpdateExpertReview(ExpertReview objExpertReview) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Update(objExpertReview);
        	logger.info("Expert Review updated successfully, Expert Review Details="+objExpertReview);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating Expert Review");
        	objResponse.add("Error in updating Expert Review");
        }
        return objResponse;
    }

    /**
     * This is implementation function for saving UserDisabilities. 
     * @param objUserDisabilities
     * @return List of String
     */
    @Override
    public List<String> SaveUserDisabilities(UserDisabilities objUserDisabilities) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objUserDisabilities);  
        	logger.info("User Disabilities saved successfully, User Disabilities Details="+objUserDisabilities);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding User Disabilities");
        	objResponse.add("Error in adding User Disabilities");
        }
        return objResponse;
    }

    /**
     * This is implementation function for updating UserDisabilities. 
     * @param objUserDisabilities
     * @return List of String
     */
    @Override
    public List<String> UpdateUserDisabilities(UserDisabilities objUserDisabilities) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Update(objUserDisabilities); 
        	logger.info("User Disabilities updated successfully, User Details="+objUserDisabilities);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updated User Disabilities");
        	objResponse.add("Error in updated User Disabilities");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving UserDisabilities. 
     * @param objUserDisabilities
     * @return List of UserDisabilities
     */
    @Override
    public List<UserDisabilities> RetriveUserDisabilities(UserDisabilities objUserDisabilities) {
    	List<UserDisabilities> objListUserDisabilities = new  ArrayList<UserDisabilities>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListUserDisabilities =  objDAInterface.RetriveData(objUserDisabilities);
            logger.info("User Disabilities loaded successfully, User Details=");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading User Disabilities");
    	}
        return objListUserDisabilities;
    }

    /**
     * This is implementation function for saving UserSchedule. 
     * @param objUserSchedule
     * @return List of String
     */
    @Override
    public List<String> SaveUserSchedule(UserSchedule objUserSchedule) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objUserSchedule);  
        	logger.info(" User Schedule saved successfully, User Details="+objUserSchedule);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding User Schedule");
        	objResponse.add("Error in adding User Schedule");
        }
        return objResponse;
    }

    /**
     * This is implementation function for updating UserSchedule. 
     * @param objUserSchedule
     * @return List of String
     */
    @Override
    public List<String> UpdateUserSchedule(UserSchedule objUserSchedule) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Update(objUserSchedule);   
        	logger.info("User Schedule saved successfully, User Details="+objUserSchedule);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updated User Schedule");
        	objResponse.add("Error in updated User Schedule");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving UserSchedule.
     * @param objUserSchedule
     * @return List of UserSchedule 
     */
    @Override
    public List<UserSchedule> RetriveUserSchedule(UserSchedule objUserSchedule) {
    	List<UserSchedule> objListUserSchedule = new ArrayList<UserSchedule>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListUserSchedule =  objDAInterface.RetriveData(objUserSchedule);
            logger.info("User Schedule loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading User Schedule");
    	}
        
        return objListUserSchedule;
    }

    /**
     * This is implementation function for saving LifelogMonitorActivity. 
     * @param objLifelogMonitorActivity
     * @return List of LifelogMonitorActivity
     */ 
    @Override
    public List<LifelogMonitorActivity> RetriveLifelogMonitorActivity(LifelogMonitorActivity objLifelogMonitorActivity) {
    	List<LifelogMonitorActivity> objListLifelogMonitorActivity = new ArrayList<LifelogMonitorActivity>();
    	try
    	{
    		 objDAInterface.ConfigureAdapter(objConnection);
    	     objListLifelogMonitorActivity =  objDAInterface.RetriveData(objLifelogMonitorActivity);
    	     logger.info("Lifelog Monitor Activity loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading Lifelog Monitor Activity");
    	}
        return objListLifelogMonitorActivity;
    }

    /**
     * This is implementation function for saving Facts. 
     * @param objFacts
     * @return List of String
     */
    @Override
    public List<String> SaveFacts(Facts objFacts) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objFacts);  
        	logger.info("Facts saved successfully, Facts Feedback Details="+objFacts);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Facts");
        	objResponse.add("Error in adding Facts");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving Facts. 
     * @param objFacts
     * @return List of Facts
     */
    @Override
    public List<Facts> RetriveFacts(Facts objFacts) {
    	List<Facts> objListFacts = new  ArrayList<Facts>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListFacts =  objDAInterface.RetriveData(objFacts);
            logger.info("Facts loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading Facts");
    	}
        
        return objListFacts;
    }

    /**
     * This is implementation function for updating Facts. 
     * @param objFacts
     * @return List of String
     */
    @Override
    public List<String> UpdateFacts(Facts objFacts) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Update(objFacts);
        	logger.info("Facts updated successfully, Facts Details="+objFacts);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating Facts");
        	objResponse.add("Error in updating Facts");
        }
        return objResponse;
    }

    /**
     * This is implementation function for saving FactsFeedback. 
     * @param objFactsFeedback
     * @return List of String
     */
    @Override
    public List<String> SaveFactsFeedback(FactsFeedback objFactsFeedback) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objFactsFeedback);
        	logger.info("Facts Feedback saved successfully, Facts Feedback Details="+objFactsFeedback);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Facts Feedback");
        	objResponse.add("Error in adding Facts Feedback");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving FactsFeedback.
     * @param objFactsFeedback
     * @return List of FactsFeedback 
     */
    @Override
    public List<FactsFeedback> RetriveFactsFeedback(FactsFeedback objFactsFeedback) {
    	List<FactsFeedback> objListFactsFeedback = new  ArrayList<FactsFeedback>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListFactsFeedback =  objDAInterface.RetriveData(objFactsFeedback);
            logger.info("Facts Feedback loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading Facts Feedback");
    	}
        return objListFactsFeedback;
    }

    /**
     * This is implementation function for updating FactsFeedback. 
     * @param objFactsFeedback
     * @return List of String
     */
    @Override
    public List<String> UpdateFactsFeedback(FactsFeedback objFactsFeedback) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Update(objFactsFeedback); 
        	logger.info("Facts Feedback saved successfully, Facts Feedback Details="+objFactsFeedback);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Facts Feedback");
        	objResponse.add("Error in adding Facts Feedback");
        }
        return objResponse;
    }

    /**
     * This is implementation function for saving UserRecognizedActivityAccumulate. 
     * @param objUserRecognizedActivityAccumulate
     * @return List of String
     */
    @Override
    public List<String> SaveUserRecognizedActivityAccumulate(UserRecognizedActivityAccumulate objUserRecognizedActivityAccumulate) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objUserRecognizedActivityAccumulate);  
        	logger.info("User Recognized Activity Accumulate saved successfully, User Details="+objUserRecognizedActivityAccumulate);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding User Recognized Activity Accumulate");
        	objResponse.add("Error in adding User Recognized Activity Accumulate");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving UserRecognizedActivityAccumulate. 
     * @param objUserRecognizedActivityAccumulate
     * @return List of RetriveUserRecognizedActivityAccumulate
     */
    @Override
    public List<UserRecognizedActivityAccumulate> RetriveUserRecognizedActivityAccumulate(UserRecognizedActivityAccumulate objUserRecognizedActivityAccumulate) {
    	List<UserRecognizedActivityAccumulate> objListUserRecognizedActivityAccumulate = new ArrayList<UserRecognizedActivityAccumulate>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListUserRecognizedActivityAccumulate =  objDAInterface.RetriveData(objUserRecognizedActivityAccumulate);
            logger.info("Recognized Activity Accumulate are loaded successfully.");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading Recognized Activity Accumulate");
    	}
        
        return objListUserRecognizedActivityAccumulate;
    }

    /**
     * This is implementation function for updating UserRecognizedActivityAccumulate.
     * @param objUserRecognizedActivityAccumulate
     * @return List of String 
     */
    @Override
    public List<String> UpdateUserRecognizedActivityAccumulate(UserRecognizedActivityAccumulate objUserRecognizedActivityAccumulate) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Update(objUserRecognizedActivityAccumulate);  
        	logger.info("Recognized Activity Accumulate updated successfully, User Details="+objUserRecognizedActivityAccumulate);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating Recognized Activity Accumulate");
        	objResponse.add("Error in updating Recognized Activity Accumulate");
        }
        return objResponse;
    }

    /**
     * This is implementation function for saving Achievements. 
     * @param objAchievements
     * @return List of String
     */
    @Override
    public List<String> SaveAchievements(Achievements objAchievements) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objAchievements); 
        	logger.info("Achievements saved successfully, Achievements Details="+objAchievements);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding Achievements");
        	objResponse.add("Error in adding Achievements");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving Achievements. 
     * @param objAchievements
     * @return List of Achievements
     */
    @Override
    public List<Achievements> RetriveAchievements(Achievements objAchievements) {
    	List<Achievements> objListAchievements = new  ArrayList<Achievements>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListAchievements =  objDAInterface.RetriveData(objAchievements);
    		logger.info("Achievements loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading Achievements");
    	}
        return objListAchievements;
    }

    /**
     * This is implementation function for updating Achievements. 
     * @param objAchievements
     * @return List of String
     */
    @Override
    public List<String> UpdateAchievements(Achievements objAchievements) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Update(objAchievements);  
        	logger.info("Achievements updated successfully, Achievements Details="+objAchievements);    
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating Achievements");
        	objResponse.add("Error in updating Achievements");
        }
        return objResponse;
    }

    /**
     * This is implementation function for saving UserRecognizedEmotion. 
     * @param objUserRecognizedEmotion
     * @return List of String
     */
    @Override
    public List<String> SaveUserRecognizedEmotion(UserRecognizedEmotion objUserRecognizedEmotion) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objUserRecognizedEmotion);
        	logger.info("User Recognized Emotion saved successfully, User Recognized Emotion Details="+objUserRecognizedEmotion);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding User Recognized Emotion");
        	objResponse.add("Error in adding User Recognized Emotion");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving UserRecognizedEmotion.
     * @param objUserRecognizedEmotion
     * @return List of RetriveUserRecognizedEmotion 
     */
    @Override
    public List<UserRecognizedEmotion> RetriveUserRecognizedEmotion(UserRecognizedEmotion objUserRecognizedEmotion) {
    	List<UserRecognizedEmotion> objListUserRecognizedEmotion = new ArrayList<UserRecognizedEmotion>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListUserRecognizedEmotion =  objDAInterface.RetriveData(objUserRecognizedEmotion);
            logger.info("User Recognized emotion are loaded successfully.");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading User Recognized emotion");
    	}
        
        return objListUserRecognizedEmotion;
    }

    /**
     * This is implementation function for saving UserRecognizedHLC. 
     * @param objUserRecognizedHLC
     * @return List of String
     */
    @Override
    public List<String> SaveUserRecognizedHLC(UserRecognizedHLC objUserRecognizedHLC) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objUserRecognizedHLC);
        	logger.info("User Recognized HighLC saved successfully, User Recognized HighLC Details="+objUserRecognizedHLC);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding User Recognized HighLC");
        	objResponse.add("Error in adding User Recognized HighLC");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving UserRecognizedHLC.
     * @param objUserRecognizedHLC
     * @return List of UserRecognizedHLC 
     */
    @Override
    public List<UserRecognizedHLC> RetriveUserRecognizedHLC(UserRecognizedHLC objUserRecognizedHLC) {
    	List<UserRecognizedHLC> objListUserRecognizedHLC = new ArrayList<UserRecognizedHLC>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListUserRecognizedHLC =  objDAInterface.RetriveData(objUserRecognizedHLC);
            logger.info("User Recognized HLC are loaded successfully.");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading User Recognized HLC");
    	}
    	
        return objListUserRecognizedHLC;
    }

    /**
     * This is implementation function for saving UserPreferredLocation. 
     * @param objUserPreferredLocation
     * @return List of String
     */
    @Override
    public List<String> SaveUserPreferredLocation(UserPreferredLocation objUserPreferredLocation) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objUserPreferredLocation); 
        	logger.info("User Preferred Location saved successfully, User Details="+objUserPreferredLocation);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding User Preferred Location");
        	objResponse.add("Error in adding User Preferred Location");
        }
        return objResponse;
    }

    /**
     * This is implementation function for retrieving UserPreferredLocation. 
     * @param objUserPreferredLocation
     * @return List of UserPreferredLocation
     */
    @Override
    public List<UserPreferredLocation> RetriveUserPreferredLocation(UserPreferredLocation objUserPreferredLocation) {
    	List<UserPreferredLocation> objListUserPreferredLocation = new  ArrayList<UserPreferredLocation>();
    	try
    	{
    		objDAInterface.ConfigureAdapter(objConnection);
            objListUserPreferredLocation =  objDAInterface.RetriveData(objUserPreferredLocation);
            logger.info("users preferred location loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading  users preferred location");
    	}
        
        return objListUserPreferredLocation;
    }

    /**
     * This is implementation function for updating UserPreferredLocation. 
     * @param objUserPreferredLocation
     * @return List of String
     */
    @Override
    public List<String> UpdateUserPreferredLocation(UserPreferredLocation objUserPreferredLocation) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Update(objUserPreferredLocation);   
        	logger.info(" User Preferred Location saved successfully,  User Preferred Location Details="+objUserPreferredLocation);
        }
        catch(Exception ex)
        {
        	logger.info("Error in updating  User Preferred Location");
        	objResponse.add("Error in updating  User Preferred Location");
        }
        return objResponse;
    }
    
    /**
     * This is implementation function for saving FoodLog. 
     * @param objFoodLog
     * @return List of String
     */
     @Override
    public List<String> SaveFoodLog(FoodLog objFoodLog) {
        List<String> objResponse = new ArrayList<>();
        try
        {
        	objDAInterface.ConfigureAdapter(objConnection);
        	objResponse = objDAInterface.Save(objFoodLog);
        	logger.info("food log saved successfully, food log Details="+objFoodLog);
        }
        catch(Exception ex)
        {
        	logger.info("Error in adding food log");
        	objResponse.add("Error in adding food log");
        }
        return objResponse;
    }

     /**
      * This is implementation function for retrieving FoodLog.
      * @param objFoodLog
      * @return List of FoodLog 
      */
    @Override
    public List<FoodLog> RetriveFoodLog(FoodLog objFoodLog) {
    	List<FoodLog> objListFoodLog = new ArrayList<FoodLog>();
    	try
    	{
    		 objDAInterface.ConfigureAdapter(objConnection);
    	     objListFoodLog =  objDAInterface.RetriveData(objFoodLog);
    	     logger.info("food log loaded successfully");
    	}
    	catch(Exception ex)
    	{
    		logger.info("Error in loading  food log");
    	}
        return objListFoodLog;
    }
}


<|start_filename|>data-curation-layer/lifelog-mapping-and-representation/IntermediateDatabaseLibrary/src/main/java/org/uclab/mm/datamodel/kc/Columns.java<|end_filename|>
/*
 Copyright [2016] [<NAME>]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package org.uclab.mm.datamodel.kc;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author Taqdir
 */
public class Columns implements Serializable  {
    
}


<|start_filename|>information-curation-layer/low-level-context-awareness/src/org/uclab/mm/icl/llc/LLCManager/LLCCounter.java<|end_filename|>
package org.uclab.mm.icl.llc.LLCManager;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.log4j.Logger;
import org.uclab.mm.icl.llc.config.ContextType;

/*
 Copyright [2016] [<NAME>, Kang]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * This class is counter class which is required in the recognition process of low level context.
 * With this runnable class, each recognized context are unified in predefined window period.
 * @author Nailbrainz
 *
 */
public class LLCCounter implements Runnable{
	String startTime = null;
	ExecutorService es;
	int windowTime;
	LLCUnifier unifier;
	ContextType ct;
	LLCNotifier notifier;
	long userID;
	final static Logger logger = Logger.getLogger(LLCCounter.class);
	AtomicBoolean flag;	
	
	/**
	 * Unique constructor of the LLCCounter instance
	 * @param userID user ID to set on counter
	 * @param startTime startTime of the counting
	 * @param es executorservice to run the thread
	 * @param unifier unifier instance, which stores all the recognized low level context
	 * @param notifier notifier instance, which will be used in notifying unified labels into DCL
	 * @param ct contextType of the counter instance
	 * @param flag Flag variable, indicating whether the counter is running or not.
	 */
	public LLCCounter(long userID, String startTime, ExecutorService es, LLCUnifier unifier, LLCNotifier notifier, ContextType ct, AtomicBoolean flag){
		this.startTime = startTime;
		this.es = es;
		this.windowTime = ct.getWindowSize();
		this.unifier = unifier;
		this.ct = ct;
		this.userID = userID;
		this.notifier = notifier;
		this.flag = flag;
	}
	
	/**
	 * Set the running indicator of context counter instance
	 * @param bool boolean value to set on the indicator of context counter instance
	 */
	public void setRunning(boolean bool){
		flag.set(bool);
	}
	
	/**
	 * Returns whether the context counter instance is running
	 * @return boolean variable, indicating whether the context counter is running
	 */
	public boolean isRunning(){
		return flag.get();
	}
	
	
	@Override
	public void run() throws NullPointerException{
		// TODO Auto-generated method stub
		try {
			synchronized(this){
				wait(1000*ct.getWindowSize());
			}
				//unifier.mVoting(curTime); //majority voting and sending
			es.execute(new Runnable(){
				@Override
				public void run() {
					ContextLabel llc = unifier.unify(startTime, ct);
					if(llc != null){
						notifier.Notify(llc, ct);
					}else{
						notifier.Notify(ct.getBasicLabel(userID, startTime), ct);
					}
					if(llc != null)logger.info("Out of llc = " + llc.getLabel());
					else logger.info("loc null");
					flag.set(false);
				}
			});
			
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			logger.error(e);
		}
	}
}